@@ -104,9 +104,25 @@ public function addRule(Rule $ruleToAdd, ?Rule $sibling = null): void
104104 $ position = \count ($ this ->rules [$ propertyName ]);
105105
106106 if ($ sibling !== null ) {
107+ $ siblingIsInSet = false ;
107108 $ siblingPosition = \array_search ($ sibling , $ this ->rules [$ propertyName ], true );
108109 if ($ siblingPosition !== false ) {
110+ $ siblingIsInSet = true ;
109111 $ 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 ) {
110126 // Increment column number of all existing rules on same line, starting at sibling
111127 $ siblingLineNumber = $ sibling ->getLineNumber ();
112128 $ siblingColumnNumber = $ sibling ->getColumnNumber ();
@@ -123,6 +139,7 @@ public function addRule(Rule $ruleToAdd, ?Rule $sibling = null): void
123139 $ ruleToAdd ->setPosition ($ siblingLineNumber , $ siblingColumnNumber );
124140 }
125141 }
142+
126143 if ($ ruleToAdd ->getLineNumber () === null ) {
127144 //this node is added manually, give it the next best line
128145 $ columnNumber = $ ruleToAdd ->getColumnNumber () ?? 0 ;
@@ -305,4 +322,15 @@ private static function comparePositionable(Positionable $first, Positionable $s
305322 }
306323 return $ first ->getLineNo () - $ second ->getLineNo ();
307324 }
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+ }
308336}
0 commit comments