Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
59 / 59
100.00% covered (success)
100.00%
4 / 4
CRAP
100.00% covered (success)
100.00%
1 / 1
ZObjectListDiffer
100.00% covered (success)
100.00%
59 / 59
100.00% covered (success)
100.00%
4 / 4
28
100.00% covered (success)
100.00%
1 / 1
 setZObjectDiffer
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 doDiff
100.00% covered (success)
100.00%
32 / 32
100.00% covered (success)
100.00%
1 / 1
13
 unpairedIndices
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 permutationDiff
100.00% covered (success)
100.00%
20 / 20
100.00% covered (success)
100.00%
1 / 1
10
1<?php
2/**
3 * WikiLambda ZObjectListDiffer. Implements doDiff to calculate the diff
4 * between two non-associative arrays or lists.
5 *
6 * @file
7 * @ingroup Extensions
8 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
9 * @license MIT
10 */
11
12namespace MediaWiki\Extension\WikiLambda\Diff;
13
14use Diff\Differ\Differ;
15use Diff\DiffOp\DiffOp;
16use Diff\DiffOp\DiffOpAdd;
17use Diff\DiffOp\DiffOpRemove;
18use Exception;
19
20class ZObjectListDiffer implements Differ {
21
22    private ZObjectDiffer $zObjectDiffer;
23
24    /**
25     * Setter for the differ service that will calculate
26     * the diffs for every idem of the list.
27     *
28     * @param ZObjectDiffer $zObjectDiffer
29     */
30    public function setZObjectDiffer( ZObjectDiffer $zObjectDiffer ): void {
31        $this->zObjectDiffer = $zObjectDiffer;
32    }
33
34    /**
35     * @see Differ::doDiff
36     *
37     * Compares the difference between two Typed Lists
38     *
39     * @param array $oldArray The first array
40     * @param array $newArray The second array
41     *
42     * @throws Exception
43     * @return DiffOp[]
44     */
45    public function doDiff( array $oldArray, array $newArray ): array {
46        // 0. If both lists hold the same identifiable items in a different order,
47        //    pair them up by identity rather than by position.
48        $permutation = $this->permutationDiff( $oldArray, $newArray );
49        if ( $permutation !== null ) {
50            return $permutation;
51        }
52
53        // 1. Compare length of arrays
54        // 2. If the length is the same, go item by item and diff them
55        //         using $this->zObjectDiffer;
56        // 3. If the length is not the same then wtf.
57
58        $listDiff = [];
59
60        /**
61         * TODO (T436773): Re-ordering is only detected where the two lists hold the
62         * same identifiable items, which permutationDiff() has already handled by
63         * the time we get here. Two gaps remain.
64         *
65         * A list that was both re-ordered and added to or removed from still
66         * reports position by position. Telling those apart means addressing a
67         * removal in the old list's index space and an addition in the new list's
68         * at the same time, which a Diff cannot hold, since it keys one operation
69         * per index. It would need the operations to carry their own addressing
70         * rather than taking it from their key — a change visible to
71         * ZObjectAuthorization, whose rules match paths containing those indices.
72         *
73         * And DiffMatrix below still diffs every old item against every new one,
74         * O(n*m) full recursive diffs, even where unpairedIndices() has already
75         * said which item was added or removed. Only its guess is skipped, not
76         * its work.
77         */
78
79        // If $newArray and $oldArray have the same number of items,
80        // check diff one by one using ZObjectDiffer
81        if ( count( $oldArray ) === count( $newArray ) ) {
82            for ( $index = 0; $index < count( $oldArray ); $index++ ) {
83                $oldItem = $oldArray[ $index ];
84                $newItem = $newArray[ $index ];
85
86                $itemDiff = $this->zObjectDiffer->doDiff( $oldItem, $newItem );
87
88                if ( $itemDiff->isAtomic() || ( $itemDiff->count() > 0 ) ) {
89                    $listDiff[ $index ] = $itemDiff;
90                }
91            }
92        } else {
93            $matrix = new DiffMatrix( $this->zObjectDiffer, $oldArray, $newArray );
94
95            if ( count( $oldArray ) > count( $newArray ) ) {
96                // If $oldArray has more items than $newArray, the
97                // matrix has more rows than colums, so we need to
98                // find which rows have been deleted. The join keys say so
99                // exactly where they can; failing that, fall back to the
100                // rows with a larger number of edits.
101                $deletedIndices = $this->unpairedIndices( $oldArray, $newArray )
102                    ?? $matrix->getIndicesOfRemovedItems();
103                for ( $index = 0; $index < count( $oldArray ); $index++ ) {
104                    if ( in_array( $index, $deletedIndices ) ) {
105                        // If this is one of the deleted items, create Remove operation:
106                        $listDiff[ $index ] = new DiffOpRemove( $oldArray[ $index ] );
107                    } else {
108                        // If this is one of the non deleted items, add any changes
109                        // available in the appropriate position of the matrix:
110                        $normalizer = $matrix->getNormalizer( $deletedIndices, $index );
111                        $colIndex = $index - $normalizer;
112                        if ( $matrix->hasDiffOps( $index, $colIndex ) ) {
113                            $listDiff[ $index ] = $matrix->getDiffOps( $index, $colIndex );
114                        }
115                    }
116                }
117            } else {
118                // If $newArray has more items than $oldArray, the
119                // matrix has more colums than rows, and we need to
120                // find which columns have been added. The join keys say so
121                // exactly where they can; failing that, fall back to the
122                // columns with a larger number of edits.
123                $addedIndices = $this->unpairedIndices( $newArray, $oldArray )
124                    ?? $matrix->getIndicesOfAddedItems();
125                for ( $index = 0; $index < count( $newArray ); $index++ ) {
126                    if ( in_array( $index, $addedIndices ) ) {
127                        // If this is one of the deleted items, create Add operation:
128                        $listDiff[ $index ] = new DiffOpAdd( $newArray[ $index ] );
129                    } else {
130                        // If this is one of the non deleted items, add any changes
131                        // available in the appropriate position of the matrix:
132                        $normalizer = $matrix->getNormalizer( $addedIndices, $index );
133                        $rowIndex = $index - $normalizer;
134                        if ( $matrix->hasDiffOps( $rowIndex, $index ) ) {
135                            $listDiff[ $index ] = $matrix->getDiffOps( $rowIndex, $index );
136                        }
137                    }
138                }
139            }
140        }
141        return $listDiff;
142    }
143
144    /**
145     * The indices of the items one list holds that the other does not, by their
146     * join keys, or null where the keys cannot say.
147     *
148     * DiffMatrix has to guess this from edit counts, and its guess is that the
149     * added or removed item is whichever has no identical counterpart and differs
150     * most from everything on the other side. An item edited in place answers that
151     * description too, and being edited makes it differ more, so it wins: editing
152     * one alias set of eight languages reports the language edited as newly added,
153     * shifts every language after it by one, and turns a change of one entry into
154     * a change of all of them. Join keys tell the two cases apart, because an item
155     * keeps its key when its content changes.
156     *
157     * This answers only for lists whose every item carries a key of its own, since
158     * an item that cannot be keyed might be the one that went, and only where the
159     * keys account for the whole change of length. A list that both gained and lost
160     * items needs a removal addressed in the old list's index space and an addition
161     * in the new list's at once, which a Diff cannot hold; that is left to the guess
162     * along with everything else the keys cannot settle.
163     *
164     * @param array $items The longer list: the one holding the unpaired items
165     * @param array $others The shorter list
166     * @return int[]|null Indices into $items, ascending
167     */
168    private function unpairedIndices( array $items, array $others ): ?array {
169        $keys = DiffItemKeyer::uniqueJoinKeys( $items );
170        $otherKeys = DiffItemKeyer::uniqueJoinKeys( $others );
171        if ( count( $keys ) !== count( $items ) || count( $otherKeys ) !== count( $others ) ) {
172            return null;
173        }
174
175        $unpaired = array_values( array_diff_key( $keys, $otherKeys ) );
176        return ( count( $unpaired ) === count( $items ) - count( $others ) ) ? $unpaired : null;
177    }
178
179    /**
180     * Diff two lists that hold the same items in a different order, reporting what
181     * moved rather than what each position now holds.
182     *
183     * Pairing by position makes a re-ordering look like a change to every position
184     * the moved item passed, which describes the positions rather than the item,
185     * and for a list where order carries meaning — which implementation of a
186     * function is preferred, say — hides the only thing that actually happened.
187     *
188     * This applies only where every item on both sides carries a join key of its
189     * own and the two sides carry the same set of them, which is what makes the
190     * pairing certain rather than a guess. Anything else — an item that cannot be
191     * keyed, two items sharing a key, a list that changed length or membership —
192     * is left to the positional pass. That leaves a list which was both re-ordered
193     * and added to reported as it is today; separating those needs an operation
194     * addressed in both lists' index spaces at once, which the diff structure,
195     * holding one operation per index, cannot express.
196     *
197     * Where an item both moved and changed, the change is reported and the move is
198     * not: the row is headed by the item either way, and its content changing is
199     * the more informative half.
200     *
201     * @param array $oldArray
202     * @param array $newArray
203     * @return array|null Null when the two lists are not a re-ordering of one set
204     *   of identifiable items, and must be paired up by position instead
205     */
206    private function permutationDiff( array $oldArray, array $newArray ): ?array {
207        if ( count( $oldArray ) !== count( $newArray ) ) {
208            return null;
209        }
210
211        $oldKeys = DiffItemKeyer::uniqueJoinKeys( $oldArray );
212        $newKeys = DiffItemKeyer::uniqueJoinKeys( $newArray );
213        if ( count( $oldKeys ) !== count( $oldArray )
214            || count( $newKeys ) !== count( $newArray )
215            || array_diff_key( $oldKeys, $newKeys ) !== []
216        ) {
217            return null;
218        }
219
220        // Same items, same places: nothing moved, so let the positional pass
221        // report any content changes exactly as it always has.
222        if ( $oldKeys === $newKeys ) {
223            return null;
224        }
225
226        $listDiff = [];
227        foreach ( $newKeys as $key => $newIndex ) {
228            $oldIndex = $oldKeys[$key];
229            $itemDiff = $this->zObjectDiffer->doDiff( $oldArray[$oldIndex], $newArray[$newIndex] );
230
231            if ( $itemDiff->isAtomic() || ( $itemDiff->count() > 0 ) ) {
232                $listDiff[$newIndex] = $itemDiff;
233            } elseif ( $oldIndex !== $newIndex ) {
234                $listDiff[$newIndex] = new DiffOpMove( $newArray[$newIndex], $oldIndex, $newIndex );
235            }
236        }
237
238        // Report in list order, as the positional pass does.
239        ksort( $listDiff );
240        return $listDiff;
241    }
242}