Passed
Push — master ( 755472...23808d )
by Adam
03:58
created

ListDiff   C

Complexity

Total Complexity 63

Size/Duplication

Total Lines 307
Duplicated Lines 10.1 %

Coupling/Cohesion

Components 1
Dependencies 5

Test Coverage

Coverage 0%

Importance

Changes 26
Bugs 2 Features 2
Metric Value
c 26
b 2
f 2
dl 31
loc 307
ccs 0
cts 197
cp 0
rs 5.8893
wmc 63
lcom 1
cbo 5

9 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 10 10 2
A build() 21 21 4
F diffLists() 0 137 31
B hasBetterMatch() 0 14 5
C buildDiffList() 0 75 13
A isOpeningListTag() 0 6 2
A isClosingListTag() 0 6 2
A isOpeningListItemTag() 0 6 2
A isClosingListItemTag() 0 6 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like ListDiff often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ListDiff, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Caxy\HtmlDiff;
4
5
use Caxy\HtmlDiff\ListDiff\DiffList;
6
use Caxy\HtmlDiff\ListDiff\DiffListItem;
7
8
class ListDiff extends AbstractDiff
9
{
10
    protected static $listTypes = array('ul', 'ol', 'dl');
11
12
    /**
13
     * @param string              $oldText
14
     * @param string              $newText
15
     * @param HtmlDiffConfig|null $config
16
     *
17
     * @return ListDiff
18
     */
19 View Code Duplication
    public static function create($oldText, $newText, HtmlDiffConfig $config = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
20
    {
21
        $diff = new self($oldText, $newText);
22
23
        if (null !== $config) {
24
            $diff->setConfig($config);
25
        }
26
27
        return $diff;
28
    }
29
30 View Code Duplication
    public function build()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
31
    {
32
        if ($this->hasDiffCache() && $this->getDiffCache()->contains($this->oldText, $this->newText)) {
33
            $this->content = $this->getDiffCache()->fetch($this->oldText, $this->newText);
34
35
            return $this->content;
36
        }
37
38
        $this->splitInputsToWords();
39
40
        $this->content = $this->diffLists(
41
            $this->buildDiffList($this->oldWords),
42
            $this->buildDiffList($this->newWords)
43
        );
44
45
        if ($this->hasDiffCache()) {
46
            $this->getDiffCache()->save($this->oldText, $this->newText, $this->content);
47
        }
48
49
        return $this->content;
50
    }
51
52
    protected function diffLists(DiffList $oldList, DiffList $newList)
53
    {
54
        $oldMatchData = array();
55
        $newMatchData = array();
56
        $oldListIndices = array();
57
        $newListIndices = array();
58
        $oldListItems = array();
59
        $newListItems = array();
60
61
        foreach ($oldList->getListItems() as $oldIndex => $oldListItem) {
62
            if ($oldListItem instanceof DiffListItem) {
63
                $oldListItems[$oldIndex] = $oldListItem;
64
65
                $oldListIndices[] = $oldIndex;
66
                $oldMatchData[$oldIndex] = array();
67
68
                // Get match percentages
69
                foreach ($newList->getListItems() as $newIndex => $newListItem) {
70
                    if ($newListItem instanceof DiffListItem) {
71
                        if (!in_array($newListItem, $newListItems)) {
72
                            $newListItems[$newIndex] = $newListItem;
73
                        }
74
                        if (!in_array($newIndex, $newListIndices)) {
75
                            $newListIndices[] = $newIndex;
76
                        }
77
                        if (!array_key_exists($newIndex, $newMatchData)) {
78
                            $newMatchData[$newIndex] = array();
79
                        }
80
81
                        $oldText = implode('', $oldListItem->getText());
82
                        $newText = implode('', $newListItem->getText());
83
84
                        // similar_text
85
                        $percentage = null;
86
                        similar_text($oldText, $newText, $percentage);
87
88
                        $oldMatchData[$oldIndex][$newIndex] = $percentage;
89
                        $newMatchData[$newIndex][$oldIndex] = $percentage;
90
                    }
91
                }
92
            }
93
        }
94
95
        $currentIndexInOld = 0;
96
        $currentIndexInNew = 0;
97
        $oldCount = count($oldListIndices);
98
        $newCount = count($newListIndices);
99
        $difference = max($oldCount, $newCount) - min($oldCount, $newCount);
100
101
        $diffOutput = '';
102
103
        foreach ($newList->getListItems() as $newIndex => $newListItem) {
104
            if ($newListItem instanceof DiffListItem) {
105
                $operation = null;
0 ignored issues
show
Unused Code introduced by
$operation is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
106
107
                $oldListIndex = array_key_exists($currentIndexInOld, $oldListIndices) ? $oldListIndices[$currentIndexInOld] : null;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 131 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
108
                $class = 'normal';
0 ignored issues
show
Unused Code introduced by
$class is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
109
110
                if (null !== $oldListIndex && array_key_exists($oldListIndex, $oldMatchData)) {
111
                    // Check percentage matches of upcoming list items in old.
112
                    $matchPercentage = $oldMatchData[$oldListIndex][$newIndex];
113
114
                    // does the old list item match better?
115
                    $otherMatchBetter = false;
116
                    foreach ($oldMatchData[$oldListIndex] as $index => $percentage) {
117
                        if ($index > $newIndex && $percentage > $matchPercentage) {
118
                            $otherMatchBetter = $index;
119
                        }
120
                    }
121
122
                    if (false !== $otherMatchBetter && $newCount > $oldCount && $difference > 0) {
123
                        $diffOutput .= sprintf('%s', $newListItem->getHtml('normal new', 'ins'));
124
                        ++$currentIndexInNew;
125
                        --$difference;
126
127
                        continue;
128
                    }
129
130
                    $replacement = false;
131
132
                    // is there a better old list item match coming up?
133
                    if ($oldCount > $newCount) {
134
                        while ($difference > 0 && $this->hasBetterMatch($newMatchData[$newIndex], $oldListIndex)) {
135
                            $diffOutput .= sprintf('%s', $oldListItems[$oldListIndex]->getHtml('removed', 'del'));
136
137
                            ++$currentIndexInOld;
138
                            --$difference;
139
                            $oldListIndex = array_key_exists($currentIndexInOld, $oldListIndices) ? $oldListIndices[$currentIndexInOld] : null;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 143 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
140
                            $matchPercentage = $oldMatchData[$oldListIndex][$newIndex];
141
                            $replacement = true;
142
                        }
143
                    }
144
145
                    $nextOldListIndex = array_key_exists($currentIndexInOld + 1, $oldListIndices) ? $oldListIndices[$currentIndexInOld + 1] : null;
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 147 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
146
147
                    if ($nextOldListIndex !== null && $oldMatchData[$nextOldListIndex][$newIndex] > $matchPercentage && $oldMatchData[$nextOldListIndex][$newIndex] > $this->config->getMatchThreshold()) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 203 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
148
                        // Following list item in old is better match, use that.
149
                        $diffOutput .= sprintf('%s', $oldListItems[$oldListIndex]->getHtml('removed', 'del'));
150
151
                        ++$currentIndexInOld;
152
                        $oldListIndex = $nextOldListIndex;
153
                        $matchPercentage = $oldMatchData[$oldListIndex][$newIndex];
154
                        $replacement = true;
155
                    }
156
157
                    if ($matchPercentage > $this->config->getMatchThreshold() || $currentIndexInNew === $currentIndexInOld) {
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 125 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
158
                        // Diff the two lists.
159
                        $htmlDiff = HtmlDiff::create(
160
                            $oldListItems[$oldListIndex]->getInnerHtml(),
161
                            $newListItem->getInnerHtml(),
162
                            $this->config
163
                        );
164
                        $diffContent = $htmlDiff->build();
165
166
                        $diffOutput .= sprintf('%s%s%s', $newListItem->getStartTagWithDiffClass($replacement ? 'replacement' : 'normal'), $diffContent, $newListItem->getEndTag());
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 179 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
167
                    } else {
168
                        $diffOutput .= sprintf('%s', $oldListItems[$oldListIndex]->getHtml('removed', 'del'));
169
                        $diffOutput .= sprintf('%s', $newListItem->getHtml('replacement', 'ins'));
170
                    }
171
                    ++$currentIndexInOld;
172
                } else {
173
                    $diffOutput .= sprintf('%s', $newListItem->getHtml('normal new', 'ins'));
174
                }
175
176
                ++$currentIndexInNew;
177
            }
178
        }
179
180
        // Output any additional list items
181
        while (array_key_exists($currentIndexInOld, $oldListIndices)) {
182
            $oldListIndex = $oldListIndices[$currentIndexInOld];
183
            $diffOutput .= sprintf('%s', $oldListItems[$oldListIndex]->getHtml('removed', 'del'));
184
            ++$currentIndexInOld;
185
        }
186
187
        return sprintf('%s%s%s', $newList->getStartTagWithDiffClass(), $diffOutput, $newList->getEndTag());
188
    }
189
190
    /**
191
     * @param array $matchData
192
     * @param int   $currentIndex
193
     *
194
     * @return bool
195
     */
196
    protected function hasBetterMatch(array $matchData, $currentIndex)
197
    {
198
        $matchPercentage = $matchData[$currentIndex];
199
        foreach ($matchData as $index => $percentage) {
200
            if ($index > $currentIndex &&
201
                $percentage > $matchPercentage &&
202
                $percentage > $this->config->getMatchThreshold()
203
            ) {
204
                return true;
205
            }
206
        }
207
208
        return false;
209
    }
210
211
    protected function buildDiffList($words)
212
    {
213
        $listType = null;
214
        $listStartTag = null;
215
        $listEndTag = null;
216
        $attributes = array();
217
        $openLists = 0;
218
        $openListItems = 0;
219
        $list = array();
220
        $currentListItem = null;
221
        $listItemType = null;
222
        $listItemStart = null;
223
        $listItemEnd = null;
0 ignored issues
show
Unused Code introduced by
$listItemEnd is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
224
225
        foreach ($words as $i => $word) {
226
            if ($this->isOpeningListTag($word, $listType)) {
227
                if ($openLists > 0) {
228
                    if ($openListItems > 0) {
229
                        $currentListItem[] = $word;
230
                    } else {
231
                        $list[] = $word;
232
                    }
233
                } else {
234
                    $listType = substr($word, 1, 2);
235
                    $listStartTag = $word;
236
                }
237
238
                ++$openLists;
239
            } elseif ($this->isClosingListTag($word, $listType)) {
240
                if ($openLists > 1) {
241
                    if ($openListItems > 0) {
242
                        $currentListItem[] = $word;
243
                    } else {
244
                        $list[] = $word;
245
                    }
246
                } else {
247
                    $listEndTag = $word;
248
                }
249
250
                --$openLists;
251
            } elseif ($this->isOpeningListItemTag($word, $listItemType)) {
252
                if ($openListItems === 0) {
253
                    // New top-level list item
254
                    $currentListItem = array();
255
                    $listItemType = substr($word, 1, 2);
256
                    $listItemStart = $word;
257
                } else {
258
                    $currentListItem[] = $word;
259
                }
260
261
                ++$openListItems;
262
            } elseif ($this->isClosingListItemTag($word, $listItemType)) {
263
                if ($openListItems === 1) {
264
                    $listItemEnd = $word;
265
                    $listItem = new DiffListItem($currentListItem, array(), $listItemStart, $listItemEnd);
266
                    $list[] = $listItem;
267
                    $currentListItem = null;
268
                } else {
269
                    $currentListItem[] = $word;
270
                }
271
272
                --$openListItems;
273
            } else {
274
                if ($openListItems > 0) {
275
                    $currentListItem[] = $word;
276
                } else {
277
                    $list[] = $word;
278
                }
279
            }
280
        }
281
282
        $diffList = new DiffList($listType, $listStartTag, $listEndTag, $list, $attributes);
283
284
        return $diffList;
285
    }
286
287
    protected function isOpeningListTag($word, $type = null)
288
    {
289
        $filter = $type !== null ? array('<'.$type) : array('<ul', '<ol', '<dl');
290
291
        return in_array(substr($word, 0, 3), $filter);
292
    }
293
294
    protected function isClosingListTag($word, $type = null)
295
    {
296
        $filter = $type !== null ? array('</'.$type) : array('</ul', '</ol', '</dl');
297
298
        return in_array(substr($word, 0, 4), $filter);
299
    }
300
301
    protected function isOpeningListItemTag($word, $type = null)
302
    {
303
        $filter = $type !== null ? array('<'.$type) : array('<li', '<dd', '<dt');
304
305
        return in_array(substr($word, 0, 3), $filter);
306
    }
307
308
    protected function isClosingListItemTag($word, $type = null)
309
    {
310
        $filter = $type !== null ? array('</'.$type) : array('</li', '</dd', '</dt');
311
312
        return in_array(substr($word, 0, 4), $filter);
313
    }
314
}
315