Passed
Push — master ( e1cbde...b292fd )
by Brian
06:56
created

Attributes::translate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 8
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 16
rs 10
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
    public function translate(string $text, string $pattern = '/[^{{\}\}]+(?=}})/'): string
14
    {
15
        preg_match_all($pattern, $text, $matches);
16
17
        if (0 === \count($matches[0])) {
18
            return $text;
19
        }
20
21
        $replace_vars = [];
22
23
        foreach ($matches[0] as $match) {
24
            $var = Str::slug($match, '_');
25
            $replace_vars["{{{$match}}}"] = $this->cache->get("{$this->prefix}_{$var}", "{{$var}}");
26
        }
27
28
        return strtr($text, $replace_vars);
29
    }
30
31
    public function readAttr(string $name, mixed $default = null): mixed
32
    {
33
        $value = $this->node->attributes->getNamedItem($name)->nodeValue ?? $default;
34
35
        return $this->translate($value);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type null; however, parameter $text of Bmatovu\Ussd\Traits\Attributes::translate() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

35
        return $this->translate(/** @scrutinizer ignore-type */ $value);
Loading history...
36
    }
37
}
38