FirstDiff::firstDifference()   B
last analyzed

Complexity

Conditions 7
Paths 6

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 7

Importance

Changes 0
Metric Value
cc 7
eloc 10
nc 6
nop 2
dl 0
loc 19
rs 8.8333
c 0
b 0
f 0
ccs 12
cts 12
cp 1
crap 7
1
<?php
2
/**
3
 * This file is part of graze/console-diff-renderer.
4
 *
5
 * Copyright (c) 2017 Nature Delivered Ltd. <https://www.graze.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license https://github.com/graze/console-diff-renderer/blob/master/LICENSE.md
11
 * @link    https://github.com/graze/console-diff-renderer
12
 */
13
14
namespace Graze\DiffRenderer\Diff;
15
16
class FirstDiff
17
{
18
    /**
19
     * Loop through each line, and produce a difference report of what to write out to the terminal
20
     *
21
     * Assumes the beginning of old and new are the same line
22
     *
23
     * @param string[] $old
24
     * @param string[] $new
25
     *
26
     * @return array [[:col, :str]]
27
     */
28 17
    public function lines(array $old, array $new)
29
    {
30 17
        $out = [];
31 17
        $newLen = count($new);
32 17
        $oldLen = count($old);
33 17
        for ($i = 0; $i < $oldLen || $i < $newLen; $i++) {
34 17
            if ($i >= $oldLen) {
35 2
                $out[] = ['col' => 0, 'str' => $new[$i]]; // write out the entire line for extra lines
36 17
            } elseif ($i >= $newLen) {
37 1
                $out[] = ['col' => 0, 'str' => '']; // clear the line if the new array has less entries than the old one
38 1
            } else {
39 17
                $col = $this->firstDifference($old[$i], $new[$i]);
40 17
                if ($col === -1) {
41 8
                    $out[] = null;
42 8
                } else {
43 15
                    $out[] = ['col' => $col, 'str' => mb_substr($new[$i], $col)];
44
                }
45
            }
46 17
        }
47 17
        return $out;
48
    }
49
50
    /**
51
     * Looks through a line to find the character to of the first difference between the 2 strings.
52
     *
53
     * If no difference is found, returns -1
54
     *
55
     * @param string $old
56
     * @param string $new
57
     *
58
     * @return int
59
     */
60 10
    public function firstDifference($old, $new)
61
    {
62
        // loop through old and new character by character and compare
63 10
        $oldLen = mb_strlen($old);
64 10
        $newLen = mb_strlen($new);
65
66 10
        if ($oldLen === 0) {
67 1
            return 0;
68
        }
69
70 9
        for ($i = 0; $i < $oldLen && $i < $newLen; $i++) {
71 8
            if (mb_substr($old, $i, 1) !== mb_substr($new, $i, 1)) {
72 4
                return $i;
73
            }
74 7
        }
75 6
        if ($i < $oldLen || $i < $newLen) {
76 3
            return $i;
77
        }
78 3
        return -1;
79
    }
80
}
81