Passed
Push — master ( 633b25...e5131a )
by Alexander
01:44 queued 10s
created

BinaryOperator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 56
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B accept() 0 25 7
1
<?php
2
3
4
namespace App\Node;
5
6
7
use App\Exception\DivisionByZeroException;
8
use App\Exception\VisitorException;
9
use App\Token;
10
use App\Visitor;
11
12
class BinaryOperator implements Visitable
13
{
14
    /**
15
     * @var Visitable
16
     */
17
    public $left;
18
    /**
19
     * @var Token
20
     */
21
    public $operator;
22
    /**
23
     * @var Visitable
24
     */
25
    public $right;
26
27
    /**
28
     * BinaryOperator constructor.
29
     * @param Visitable $left
30
     * @param Token $operator
31
     * @param Visitable $right
32
     */
33
    public function __construct(Visitable $left, Token $operator, Visitable $right)
34
    {
35
        $this->left     = $left;
36
        $this->operator = $operator;
37
        $this->right    = $right;
38
    }
39
40
    /**
41
     * @inheritDoc
42
     */
43
    public function accept(Visitor $visitor)
44
    {
45
        /** @var int|float $leftValue */
46
        $leftValue = $visitor->visit($this->left);
47
        /** @var int|float $rightValue */
48
        $rightValue = $visitor->visit($this->right);
49
        switch ($this->operator->type) {
50
            case Token::PLUS:
51
                return $leftValue + $rightValue;
52
            case Token::MINUS;
53
                return $leftValue - $rightValue;
54
            case Token::MUL;
55
                return $leftValue * $rightValue;
56
            case Token::POWER:
57
                return $leftValue ** $rightValue;
58
            case Token::REALDIV;
59
                //not strict for int/float
60
                /** @noinspection TypeUnsafeComparisonInspection */
61
                if ($rightValue == 0) {
62
                    throw new DivisionByZeroException('Division be zero not allowed');
63
                }
64
                return $leftValue / $rightValue;
65
        }
66
67
        throw new VisitorException('Unknown operator for BinaryOperator');
68
    }
69
}