@@ -105,6 +105,41 @@ function merge($ancestor, $ours, $theirs) {
105105 return $ ours ;
106106}
107107
108+ // Sort composer packages
109+ // Method was taken from https://github.com/composer/composer/blob/master/src/Composer/Json/JsonManipulator.php#L117-L146
110+ function sortPackages (&$ packages )
111+ {
112+ $ prefix = function ($ requirement ) {
113+ // value was taken from https://github.com/composer/composer/blob/master/src/Composer/Repository/PlatformRepository.php#L27
114+ $ platformPackageRegexp = '{^(?:php(?:-64bit|-ipv6|-zts|-debug)?|hhvm|(?:ext|lib)-[^/ ]+)$}i ' ;
115+
116+ if (preg_match ($ platformPackageRegexp , $ requirement )) {
117+ return preg_replace (
118+ array (
119+ '/^php/ ' ,
120+ '/^hhvm/ ' ,
121+ '/^ext/ ' ,
122+ '/^lib/ ' ,
123+ '/^\D/ ' ,
124+ ),
125+ array (
126+ '0-$0 ' ,
127+ '1-$0 ' ,
128+ '2-$0 ' ,
129+ '3-$0 ' ,
130+ '4-$0 ' ,
131+ ),
132+ $ requirement
133+ );
134+ }
135+ return '5- ' .$ requirement ;
136+ };
137+
138+ uksort ($ packages , function ($ a , $ b ) use ($ prefix ) {
139+ return strnatcmp ($ prefix ($ a ), $ prefix ($ b ));
140+ });
141+ }
142+
108143// special handling for lock files
109144if ($ isLock ) {
110145 // @todo handle alias property as well
@@ -155,7 +190,19 @@ if ($isLock) {
155190
156191 $ merged = json_encode ($ merged , JSON_ENCODE_OPTIONS );
157192} else {
158- $ merged = json_encode (merge ($ ancestor , $ ours , $ theirs ), JSON_ENCODE_OPTIONS );
193+ $ merged = merge ($ ancestor , $ ours , $ theirs );
194+
195+ if (isset ($ merged ['config ' ]['sort-packages ' ]) && $ merged ['config ' ]['sort-packages ' ] === true ) {
196+ foreach (['require ' , 'require-dev ' ] as $ section ) {
197+ $ packageArray = $ merged [$ section ];
198+
199+ sortPackages ($ packageArray );
200+
201+ $ merged [$ section ] = $ packageArray ;
202+ }
203+ }
204+
205+ $ merged = json_encode ($ merged , JSON_ENCODE_OPTIONS );
159206}
160207
161208// if we have conflicts, replace the conflict markers with the actual conflicting values
0 commit comments