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

Attributes::translate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 8
c 1
b 0
f 0
dl 0
loc 16
ccs 9
cts 9
cp 1
rs 10
cc 3
nc 3
nop 2
crap 3
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