Completed
Pull Request — master (#16)
by Michal
10:05
created

RegexTextFinder::findTexts()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 3
nop 3
dl 0
loc 13
ccs 3
cts 3
cp 1
crap 3
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace Efabrica\TranslationsAutomatization\TextFinder;
4
5
class RegexTextFinder implements TextFinderInterface
6
{
7
    private $patterns = [];
8
9
    /**
10
     * @param string $pattern
11
     * @param int|null $textPosition position of text in pattern, use null to remove possible false positives only
12
     * @return RegexTextFinder
13
     */
14 16
    public function addPattern(string $pattern, ?int $textPosition = 1): RegexTextFinder
15
    {
16 16
        $this->patterns[$pattern] = $textPosition;
17 16
        return $this;
18
    }
19
20 16
    public function find(string $content): array
21
    {
22 16
        $texts = [];
23 16
        foreach ($this->patterns as $pattern => $textPosition) {
24 14
            if ($textPosition === null) {
25 2
                $content = preg_replace($pattern, '', $content);
26 2
                continue;
27
            }
28 14
            $texts = array_merge($texts, $this->findTexts($pattern, $content, $textPosition, $texts));
0 ignored issues
show
Unused Code introduced by
The call to Efabrica\TranslationsAut...TextFinder::findTexts() has too many arguments starting with $texts. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

28
            $texts = array_merge($texts, $this->/** @scrutinizer ignore-call */ findTexts($pattern, $content, $textPosition, $texts));

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
29 14
            $content = preg_replace($pattern, '', $content);
30 14
        }
31 14
        return $texts;
32 14
    }
33 8
34
    private function findTexts(string $pattern, string $content, int $textPosition): array
35 14
    {
36
        $texts = [];
37 14
        preg_match_all($pattern, $content, $matches);
38
        $matchesCount = count($matches[0]);
39
        for ($i = 0; $i < $matchesCount; ++$i) {
40 16
            $text = trim($matches[$textPosition][$i]);
41
            if ($text === '') {
42
                continue;
43
            }
44
            $texts[trim($matches[0][$i])] = $text;
45
        }
46
        return $texts;
47
    }
48
}
49