Passed
Push — master ( 78d0af...d10895 )
by Brian
02:44
created

Attributes   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
eloc 13
c 2
b 0
f 0
dl 0
loc 33
ccs 14
cts 14
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A translate() 0 16 3
A readAttr() 0 9 2
1
<?php
2
3
namespace Bmatovu\Ussd\Traits;
4
5
use Illuminate\Support\Str;
6
7
trait Attributes
8
{
9
    /**
10
     * @see https://stackoverflow.com/q/413071/2732184
11
     * @see https://www.regextester.com/97707
12
     */
13 24
    public function translate(string $text, string $pattern = '/[^{{\}\}]+(?=}})/'): string
14
    {
15 24
        preg_match_all($pattern, $text, $matches);
16
17 24
        if (0 === \count($matches[0])) {
18 23
            return $text;
19
        }
20
21 2
        $replace_vars = [];
22
23 2
        foreach ($matches[0] as $match) {
24 2
            $var = Str::slug($match, '_');
25 2
            $replace_vars["{{{$match}}}"] = $this->store->get($var, "{{$var}}");
26
        }
27
28 2
        return strtr($text, $replace_vars);
29
    }
30
31 25
    public function readAttr(string $name, $default = null)
32
    {
33 25
        $value = $this->node->attributes->getNamedItem($name)->nodeValue ?? $default;
34
35 25
        if (! $value) {
36 5
            return $value;
37
        }
38
39 24
        return $this->translate($value);
40
    }
41
}
42