Passed
Push — master ( 64f30d...d93186 )
by Brian
02:27
created

Helper::getDomElements()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 17
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 3
b 0
f 0
nc 1
nop 2
dl 0
loc 17
ccs 8
cts 8
cp 1
crap 3
rs 10
1
<?php
2
3
namespace Bmatovu\Ussd\Support;
4
5
use Illuminate\Contracts\Cache\Repository as CacheContract;
6
use Illuminate\Support\Str;
7
8
class Helper
9
{
10 11
    public static function getDomElements(\DOMNodeList $nodeList, ?string $nodeName): array
11
    {
12 11
        $els = array_filter(iterator_to_array($nodeList), function ($node) use ($nodeName) {
13
            // return $node instanceof \DOMElement && ($nodeName && $node->nodeName === $nodeName);
14
15 11
            if (! $node instanceof \DOMElement) {
16 10
                return false;
17
            }
18
19 11
            if (! $nodeName) {
20 4
                return true;
21
            }
22
23 7
            return $node->nodeName === $nodeName;
24
        });
25
26 11
        return array_values($els);
27
    }
28
29
    /**
30
     * @see https://stackoverflow.com/q/413071/2732184
31
     * @see https://www.regextester.com/97707
32
     */
33 2
    public static function translate(CacheContract $cache, string $prefix, string $text, string $pattern = '/[^{\}]+(?=})/'): string
34
    {
35 2
        preg_match_all($pattern, $text, $matches);
36
37 2
        if (0 === \count($matches[0])) {
38 1
            return $text;
39
        }
40
41 2
        $replace_vars = [];
42
43 2
        foreach ($matches[0] as $match) {
44 2
            $var = Str::slug($match, '_');
45 2
            $replace_vars["{{$match}}"] = $cache->get("{$prefix}_{$var}", "{{$var}}");
46
        }
47
48 2
        return strtr($text, $replace_vars);
49
    }
50
}
51