@@ -104,9 +104,25 @@ public function addRule(Rule $ruleToAdd, ?Rule $sibling = null): void
104
104
$ position = \count ($ this ->rules [$ propertyName ]);
105
105
106
106
if ($ sibling !== null ) {
107
+ $ siblingIsInSet = false ;
107
108
$ siblingPosition = \array_search ($ sibling , $ this ->rules [$ propertyName ], true );
108
109
if ($ siblingPosition !== false ) {
110
+ $ siblingIsInSet = true ;
109
111
$ position = $ siblingPosition ;
112
+ } else {
113
+ $ siblingIsInSet = $ this ->hasRule ($ sibling );
114
+ if ($ siblingIsInSet ) {
115
+ // Maintain ordering within `$this->rules[$propertyName]`
116
+ // by inserting before first `Rule` with a same-or-later position than the sibling.
117
+ foreach ($ this ->rules [$ propertyName ] as $ index => $ rule ) {
118
+ if (self ::comparePositionable ($ rule , $ sibling ) >= 0 ) {
119
+ $ position = $ index ;
120
+ break ;
121
+ }
122
+ }
123
+ }
124
+ }
125
+ if ($ siblingIsInSet ) {
110
126
// Increment column number of all existing rules on same line, starting at sibling
111
127
$ siblingLineNumber = $ sibling ->getLineNumber ();
112
128
$ siblingColumnNumber = $ sibling ->getColumnNumber ();
@@ -123,6 +139,7 @@ public function addRule(Rule $ruleToAdd, ?Rule $sibling = null): void
123
139
$ ruleToAdd ->setPosition ($ siblingLineNumber , $ siblingColumnNumber );
124
140
}
125
141
}
142
+
126
143
if ($ ruleToAdd ->getLineNumber () === null ) {
127
144
//this node is added manually, give it the next best line
128
145
$ columnNumber = $ ruleToAdd ->getColumnNumber () ?? 0 ;
@@ -305,4 +322,15 @@ private static function comparePositionable(Positionable $first, Positionable $s
305
322
}
306
323
return $ first ->getLineNo () - $ second ->getLineNo ();
307
324
}
325
+
326
+ private function hasRule (Rule $ rule ): bool
327
+ {
328
+ foreach ($ this ->rules as $ rulesForAProperty ) {
329
+ if (\in_array ($ rule , $ rulesForAProperty , true )) {
330
+ return true ;
331
+ }
332
+ }
333
+
334
+ return false ;
335
+ }
308
336
}
0 commit comments