RegexTextFinder::addPattern()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
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));
29 14
            $content = preg_replace($pattern, '', $content);
30
        }
31 16
        return $texts;
32
    }
33
34 14
    private function findTexts(string $pattern, string $content, int $textPosition): array
35
    {
36 14
        $texts = [];
37 14
        preg_match_all($pattern, $content, $matches);
38 14
        $matchesCount = count($matches[0]);
39 14
        for ($i = 0; $i < $matchesCount; ++$i) {
40 14
            $text = trim($matches[$textPosition][$i]);
41 14
            if ($text === '') {
42 8
                continue;
43
            }
44 14
            $texts[trim($matches[0][$i])] = $text;
45
        }
46 14
        return $texts;
47
    }
48
}
49