Completed
Push — master ( aa415b...e4e762 )
by Harry
02:09
created

ConsoleDiff   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 11
lcom 1
cbo 1
dl 0
loc 59
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 2
B lines() 0 19 7
A getUnclosedTags() 0 7 2
1
<?php
2
3
namespace Graze\BufferedConsole\Diff;
4
5
use Symfony\Component\Console\Output\OutputInterface;
6
7
class ConsoleDiff extends FirstDiff
8
{
9
    const UNCLOSED_TAGS = '/<(?P<tag>[a-z;=]+)>(?!.*?<\/(?:(?P=tag)|)>)/i';
10
11
    /** @var FirstDiff */
12
    private $diff;
13
14
    /**
15
     * ConsoleDiff constructor.
16
     *
17
     * @param FirstDiff|null $differ
18
     */
19
    public function __construct($differ = null)
20
    {
21
        $this->diff = $differ ?: new FirstDiff();
22
    }
23
24
    /**
25
     * @param string[] $old
26
     * @param string[] $new
27
     * @param int      $options
28
     *
29
     * @return string[]
30
     */
31
    public function lines(array $old, array $new, $options = OutputInterface::OUTPUT_NORMAL)
32
    {
33
        $diff = $this->diff->lines($old, $new);
34
35
        if (($options & OutputInterface::OUTPUT_NORMAL) == OutputInterface::OUTPUT_NORMAL) {
36
            // replace col number with strip_tags version to represent what is outputted to the user
37
            for ($i = 0; $i < count($new); $i++) {
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function count() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
38
                if (isset($diff[$i]) && !is_null($new[$i]) && $diff[$i]['col'] > 0) {
39
                    $tags = $this->getUnclosedTags(mb_substr($new[$i], 0, $diff[$i]['col']));
40
                    if (count($tags) > 0) {
41
                        $diff[$i]['str'] = '<' . implode('><', $tags) . '>' . $diff[$i]['str'];
42
                    }
43
                    $diff[$i]['col'] = mb_strlen(strip_tags(mb_substr($new[$i], 0, $diff[$i]['col'])));
44
                }
45
            }
46
        }
47
48
        return $diff;
49
    }
50
51
    /**
52
     * Find a list of unclosed tags
53
     *
54
     * @param string $string
55
     *
56
     * @return string[]
57
     */
58
    private function getUnclosedTags($string)
59
    {
60
        if (preg_match_all(static::UNCLOSED_TAGS, $string, $matches)) {
61
            return $matches['tag'];
62
        }
63
        return [];
64
    }
65
}
66