Passed
Push — master ( a380f8...e1cbde )
by Brian
03:07
created

Helper::renderNode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 9
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
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 1
    public static function renderNode(\DOMNode $node): string
11
    {
12 1
        $attrs = '';
13
14 1
        foreach ($node->attributes as $attr) {
15 1
            $attrs .= " {$attr->name}=\"{$attr->value}\"";
16
        }
17
18 1
        return "<{$node->tagName}{$attrs}/>";
19
    }
20
21 11
    public static function getDomElements(\DOMNodeList $nodeList, ?string $nodeName): array
22
    {
23 11
        $els = array_filter(iterator_to_array($nodeList), function ($node) use ($nodeName) {
24
            // return $node instanceof \DOMElement && ($nodeName && $node->nodeName === $nodeName);
25
26 11
            if (! $node instanceof \DOMElement) {
27 10
                return false;
28
            }
29
30 11
            if (! $nodeName) {
31 4
                return true;
32
            }
33
34 7
            return $node->nodeName === $nodeName;
35
        });
36
37 11
        return array_values($els);
38
    }
39
40
    /**
41
     * @see https://stackoverflow.com/q/413071/2732184
42
     * @see https://www.regextester.com/97707
43
     */
44 2
    public static function translate(CacheContract $cache, string $prefix, string $text, string $pattern = '/[^{\}]+(?=})/'): string
45
    {
46 2
        preg_match_all($pattern, $text, $matches);
47
48 2
        if (0 === \count($matches[0])) {
49 1
            return $text;
50
        }
51
52 2
        $replace_vars = [];
53
54 2
        foreach ($matches[0] as $match) {
55 2
            $var = Str::slug($match, '_');
56 2
            $replace_vars["{{$match}}"] = $cache->get("{$prefix}_{$var}", "{{$var}}");
57
        }
58
59 2
        return strtr($text, $replace_vars);
60
    }
61
}
62