Passed
Push — master ( ef65fe...aab2bb )
by Brian
06:54
created

ParserUtils::xpathFromStr()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 7
ccs 3
cts 3
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Bmatovu\Ussd\Traits;
4
5
use Bmatovu\Ussd\Contracts\RenderableTag;
6
use Illuminate\Container\Container;
7
use Illuminate\Support\Facades\Log;
8
use Illuminate\Support\Str;
9
10
trait ParserUtils
11 1
{
12
    public function __get(string $key)
13 1
    {
14
        return $this->{$key};
15
    }
16
17
    public function __set(string $key, $value)
18
    {
19
        $this->{$key} = $value;
20
    }
21
22
    /**
23
     * @see https://stackoverflow.com/q/413071/2732184
24
     * @see https://www.regextester.com/97707
25
     */
26
    public function translate(string $text, string $pattern = '/[^{{\}\}]+(?=}})/'): string
27
    {
28
        preg_match_all($pattern, $text, $matches);
29
30
        if (0 === \count($matches[0])) {
31
            return $text;
32
        }
33
34
        $replace_vars = [];
35
36
        foreach ($matches[0] as $match) {
37
            $var = Str::slug($match, '_');
38
            $replace_vars["{{{$match}}}"] = $this->store->get("{$prefix}{$var}", "{{$var}}");
0 ignored issues
show
Bug Best Practice introduced by
The property store does not exist on Bmatovu\Ussd\Traits\ParserUtils. Since you implemented __get, consider adding a @property annotation.
Loading history...
Comprehensibility Best Practice introduced by
The variable $prefix seems to be never defined.
Loading history...
39
        }
40
41
        return strtr($text, $replace_vars);
42
    }
43 5
44
    protected function xpathFromStr(string $file): \DOMXPath
45 5
    {
46
        $doc = new \DOMDocument();
47 5
48
        $doc->load($file);
49
50 3
        return new \DOMXPath($doc);
51
    }
52 3
53 3
    protected function sessionExists(string $sessionId): bool
54
    {
55
        $preSessionId = $this->store->get('_session_id', '');
0 ignored issues
show
Bug Best Practice introduced by
The property store does not exist on Bmatovu\Ussd\Traits\ParserUtils. Since you implemented __get, consider adding a @property annotation.
Loading history...
56
57
        return $preSessionId === $sessionId;
58
    }
59 5
60
    protected function clean(string $code = ''): string
61 5
    {
62 5
        if (! $code) {
63
            return $code;
64
        }
65
66
        return rtrim(ltrim($code, '*'), '#');
67
    }
68
69
    protected function getAnswer(?string $userInput): ?string
70
    {
71
        if (! $userInput) {
72
            return '';
73
        }
74
75
        $preAnswer = $this->store->get('_answer', '');
0 ignored issues
show
Bug Best Practice introduced by
The property store does not exist on Bmatovu\Ussd\Traits\ParserUtils. Since you implemented __get, consider adding a @property annotation.
Loading history...
76
77 5
        $answer = $this->clean(str_replace($preAnswer, '', $userInput));
78
79 5
        if(! $answer) {
80
            Log::debug('ANSWERS', ['_answer' => $preAnswer, 'input' => $userInput, 'answer' => $answer]);
81 5
            return $answer;
82 5
        }
83
84
        if(! $preAnswer || Str::endsWith($preAnswer, '*')) {
85
            $this->store->append('_answer', "{$answer}*");
86
        } else {
87
            $this->store->append('_answer', "*{$answer}*");
88
        }
89
90 5
        Log::debug('ANSWERS', ['_answer' => $preAnswer, 'input' => $userInput, 'answer' => $answer]);
91
92
        return $answer;
93 5
    }
94 5
95
    protected function resolveTagName(\DOMNode $node): string
96 5
    {
97
        $tagName = $node->tagName;
98 5
99
        if ('action' !== strtolower($tagName)) {
100 5
            return Str::studly("{$tagName}Tag");
101 5
        }
102 5
103 4
        $tagName = $node->attributes->getNamedItem('name')->nodeValue;
0 ignored issues
show
Bug introduced by
The method getNamedItem() does not exist on null. ( Ignorable by Annotation )

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

103
        $tagName = $node->attributes->/** @scrutinizer ignore-call */ getNamedItem('name')->nodeValue;

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
104
105
        return Str::studly("{$tagName}Action");
106
    }
107 1
108
    protected function resolveTagClass(string $tagName): string
109
    {
110 5
        // $config = Container::getInstance()->make('config');
111
        $tagNs = config('ussd.tag-ns', []);
112 5
        $actionNs = config('ussd.action-ns', []);
113
114 4
        $namespaces = array_merge($tagNs, $actionNs);
115
116
        $fqcn = $tagName;
0 ignored issues
show
Unused Code introduced by
The assignment to $fqcn is dead and can be removed.
Loading history...
117
118
        foreach ($namespaces as $ns) {
119
            $fqcn = "{$ns}\\{$tagName}";
120
            if (class_exists($fqcn)) {
121
                return $fqcn;
122
            }
123
        }
124
125
        throw new \Exception("Missing class: {$tagName}");
126
    }
127
128
    protected function instantiateTag(string $tagName, array $args = []): RenderableTag
129
    {
130
        $fqcn = $this->resolveTagClass($tagName);
131
132
        return \call_user_func_array([new \ReflectionClass($fqcn), 'newInstance'], $args);
133
    }
134
}
135