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

Helper   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 41
ccs 17
cts 17
cp 1
rs 10
c 3
b 0
f 0
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A translate() 0 16 3
A getDomElements() 0 17 3
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