Completed
Push — master ( 066343...e5de66 )
by Nico
01:23
created

Parser::parseExpression()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 6
nc 2
nop 0
crap 3

1 Method

Rating   Name   Duplication   Size   Complexity  
A Parser::assignVariableValueFromToken() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
/**
6
 * @license     http://opensource.org/licenses/mit-license.php MIT
7
 * @link        https://github.com/nicoSWD
8
 * @author      Nicolas Oelgart <[email protected]>
9
 */
10
namespace nicoSWD\Rules;
11
12
use Closure;
13
use InvalidArgumentException;
14
use nicoSWD\Rules\Core\CallableUserFunction;
15
use nicoSWD\Rules\Exceptions\ParserException;
16
use nicoSWD\Rules\Tokens\BaseToken;
17
use SplStack;
18
19
class Parser
20
{
21
    /** @var array */
22
    public $variables = [];
23
24
    /** @var null|BaseToken */
25
    private $operator = null;
26
27
    /** @var SplStack */
28
    private $values;
29
30
    /** @var TokenizerInterface */
31
    private $tokenizer;
32
33
    /** @var Expressions\ExpressionFactory */
34
    private $expressionFactory;
35
36
    /** @var Callable[] */
37
    private $userDefinedFunctions = [];
38
39
    /** @var RuleGenerator */
40
    private $ruleGenerator;
41
42 228
    public function __construct(
43
        TokenizerInterface $tokenizer,
44
        Expressions\ExpressionFactory $expressionFactory,
45
        RuleGenerator $ruleGenerator
46
    ) {
47 228
        $this->tokenizer = $tokenizer;
48 228
        $this->expressionFactory = $expressionFactory;
49 228
        $this->ruleGenerator = $ruleGenerator;
50 228
        $this->values = new SplStack();
51 228
    }
52
53 222
    public function parse(string $rule): string
54
    {
55 222
        $this->ruleGenerator->clear();
56 222
        $this->operator = null;
57
58 222
        foreach (new AST($this->tokenizer->tokenize($rule), $this) as $token) {
59 184
            switch ($token->getType()) {
60 184
                case TokenType::VALUE:
61 180
                    $this->assignVariableValueFromToken($token);
62 180
                    break;
63 184
                case TokenType::LOGICAL:
64 36
                    $this->ruleGenerator->addLogical($token);
65 36
                    continue 2;
66 184
                case TokenType::PARENTHESES:
67 22
                    $this->ruleGenerator->addParentheses($token);
68 20
                    continue 2;
69 184
                case TokenType::OPERATOR:
70 180
                    $this->assignOperator($token);
71 178
                    continue 2;
72 182
                case TokenType::COMMENT:
73 182
                case TokenType::SPACE:
74 180
                    continue 2;
75
                default:
76 6
                    throw Exceptions\ParserException::unknownToken($token);
77
            }
78
79 180
            $this->evaluateExpression();
80
        }
81
82 162
        return $this->ruleGenerator->get();
83
    }
84
85 222
    public function assignVariables(array $variables)
86
    {
87 222
        $this->variables = $variables;
88 222
    }
89
90 30
    public function registerFunctionClass(string $className)
91
    {
92
        /** @var CallableUserFunction $function */
93 30
        $function = new $className();
94
95 30
        if (!$function instanceof CallableUserFunction) {
96 2
            throw new InvalidArgumentException(
97 2
                sprintf(
98 2
                    "%s must be an instance of %s",
99 2
                    $className,
100 2
                    CallableUserFunction::class
101
                )
102
            );
103
        }
104
105 28
        $this->registerFunction($function->getName(), function () use ($function): BaseToken {
106 24
            return $function->call(...func_get_args());
0 ignored issues
show
Documentation introduced by
func_get_args() is of type array, but the function expects a object<nicoSWD\Rules\Tokens\BaseToken>|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
107 28
        });
108 28
    }
109
110 28
    public function getFunction(string $name): Closure
111
    {
112 28
        if (!isset($this->userDefinedFunctions[$name])) {
113 4
            throw new Exceptions\ParserException(sprintf(
114 4
                '%s is not defined',
115 4
                $name
116
            ));
117
        }
118
119 24
        return $this->userDefinedFunctions[$name];
120
    }
121
122 180
    private function assignVariableValueFromToken(BaseToken $token)
123
    {
124 180
        $this->ruleGenerator->flipOperatorRequired($token);
125 180
        $this->values->push($token->getValue());
126 180
    }
127
128 180
    private function assignOperator(BaseToken $token)
129
    {
130 180
        if (isset($this->operator)) {
131 2
            throw Exceptions\ParserException::unexpectedToken($token);
132 180
        } elseif ($this->values->isEmpty()) {
133 2
            throw Exceptions\ParserException::incompleteExpression($token);
134
        }
135
136 178
        $this->ruleGenerator->operatorRequired(false);
137 178
        $this->operator = $token;
138 178
    }
139
140 180
    private function evaluateExpression()
141
    {
142 180
        if (!isset($this->operator) || $this->values->count() !== 2) {
143 180
            return;
144
        }
145
146 176
        list($rightValue, $leftValue) = $this->values;
147
148 176
        $this->ruleGenerator->addBoolean($this->getExpression()->evaluate($leftValue, $rightValue));
149 174
        $this->values->pop();
150 174
        $this->values->pop();
151
152 174
        unset($this->operator);
153 174
    }
154
155 28
    private function registerFunction(string $name, Closure $callback)
156
    {
157 28
        $this->userDefinedFunctions[$name] = $callback;
158 28
    }
159
160 176
    private function getExpression(): Expressions\BaseExpression
161
    {
162 176
        return $this->expressionFactory->createFromOperator($this->operator);
0 ignored issues
show
Bug introduced by
It seems like $this->operator can be null; however, createFromOperator() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
163
    }
164
}
165