Completed
Push — master ( bbe544...1bc078 )
by ReliQ
03:23 queued 11s
created

buildPatternsAndReplacementsFromMap()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 2
dl 0
loc 16
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ReliqArts\DirectTranslator\Translation\Replacer;
6
7
use ReliqArts\DirectTranslator\Translation\Replacer;
8
use ReliqArts\DirectTranslator\Vocabulary;
9
10
final class PatternReplacer implements Replacer
11
{
12
    /**
13
     * {@inheritdoc}
14
     *
15
     * @return string
16
     */
17
    public function replace(
18
        string $inputText,
19
        Vocabulary $vocabulary,
20
        string $direction = self::DIRECTION_LTR
21
    ): string {
22
        $map = array_replace($vocabulary->getPhrases(), $vocabulary->getWords());
23
24
        list($patterns, $replacements) = $this->buildPatternsAndReplacementsFromMap($map, $direction);
25
26
        return preg_replace($patterns, $replacements, $inputText);
27
    }
28
29
    /**
30
     * @param array  $map
31
     * @param string $direction
32
     *
33
     * @return string[]
34
     */
35
    private function buildPatternsAndReplacementsFromMap(array $map, string $direction): array
36
    {
37
        $finalMap = $map;
38
        if ($direction === self::DIRECTION_RTL) {
39
            $finalMap = array_flip($map);
40
        }
41
42
        $patterns = array_map(
43
            function (string $wordOrPhrase): string {
44
                return sprintf('/\b%s\b/ui', $wordOrPhrase);
45
            },
46
            array_keys($finalMap)
0 ignored issues
show
Bug introduced by
It seems like $finalMap can also be of type null; however, parameter $input of array_keys() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

46
            array_keys(/** @scrutinizer ignore-type */ $finalMap)
Loading history...
47
        );
48
        $replacements = array_values($finalMap);
0 ignored issues
show
Bug introduced by
It seems like $finalMap can also be of type null; however, parameter $input of array_values() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

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

48
        $replacements = array_values(/** @scrutinizer ignore-type */ $finalMap);
Loading history...
49
50
        return [$patterns, $replacements];
0 ignored issues
show
Bug Best Practice introduced by
The expression return array($patterns, $replacements) returns the type array<integer,array> which is incompatible with the documented return type string[].
Loading history...
51
    }
52
}
53