Calc   B
last analyzed

Complexity

Total Complexity 37

Size/Duplication

Total Lines 193
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 37
c 3
b 0
f 0
lcom 1
cbo 3
dl 0
loc 193
rs 8.6

10 Methods

Rating   Name   Duplication   Size   Complexity  
D __construct() 0 44 9
A match_numeral() 0 4 1
A match_dice() 0 5 1
A match_set() 0 4 1
A match_variable() 0 4 1
A match_parens() 0 11 4
A match_operator() 0 13 4
A clear_stack() 0 5 2
C __invoke() 0 34 13
A infix() 0 3 1
1
<?php
2
3
namespace DiceCalc;
4
5
/**
6
 * Class Calc
7
 *
8
 * @package DiceCalc
9
 * @author  Owen Winkler <[email protected]>
10
 * @license MIT http://opensource.org/licenses/MIT
11
 */
12
class Calc {
13
14
    const DICE_REGEX = '(?P<multiple>\d*)d(?P<dietype>\d+|f|\%|\[[^\]]+\])
15
(
16
(?P<keep>k(?:eep)?(?P<keepeval>[<>])(?P<keeprange>\d+))
17
|
18
(?P<lowest>l(?:owest)?(?P<lowdice>\d+))
19
|
20
(?P<highest>h(?:ighest)?(?P<highdice>\d+))
21
|
22
(?P<reroll>r(?:eroll)?(?P<rerolleval>[<>])(?P<rerolllimit>\d+))
23
|
24
(?P<openroll>o(?:pen)?(?P<openrolleval>[<>=])(?P<openrolllimit>\d+))
25
|
26
(?P<flags>[z]+)
27
)*';
28
29
    /**
30
     * @var array $ooo A list of operators with comparative order of operations
31
     */
32
    private $ooo = [
33
        '>' => 0,
34
        '<' => 0,
35
        '=' => 0,
36
        '-' => 10,
37
        '+' => 10,
38
        '*' => 20,
39
        '/' => 20,
40
        '^' => 30,
41
    ];
42
43
    protected $expression;
44
    protected $rpn = [];
45
    protected $infix = [];
46
47
    protected $stack = [];
48
49
    /**
50
     * Create a dice calculation
51
     *
52
     * @param string $expression An expression to calculate
53
     */
54
    public function __construct($expression = '') {
55
        $this->expression = str_replace(' ', '', $expression);
56
57
        preg_match_all('%(?:
58
            (?P<dice>' . self::DICE_REGEX . ')
59
            |
60
            (?P<set>\d*\[[^\]]+\])
61
            |
62
            (?P<numeral>[\d\.]+)
63
            |
64
            (?P<operator>[+\-*^><=/])
65
            |
66
            (?P<variable>\$[a-z_]+)
67
            |
68
            (?P<parens>[()])
69
        )%ix', $this->expression, $matches, PREG_SET_ORDER);
70
71
        $this->stack = [];
72
73
        foreach ($matches as $match) {
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
74
            $match = array_filter($match, function ($value) {
75
                return $value !== false && $value !== '';
76
            });
77
78
            if (isset($match['numeral'])) {
79
                $this->match_numeral($match['numeral']);
80
            } elseif (isset($match['dice'])) {
81
                $this->match_dice($match['dice']);
82
            } elseif (isset($match['set'])) {
83
                $this->match_set($match['set']);
84
            } elseif (isset($match['operator'])) {
85
                $this->match_operator($match['operator']);
86
            } elseif (isset($match['variable'])) {
87
                $this->match_variable($match['variable']);
88
            } elseif (isset($match['parens'])) {
89
                $this->match_parens($match['parens']);
90
            } else {
91
                $this->stack = ['Invalid token:', $match];
92
                break;
93
            }
94
        }
95
96
        $this->clear_stack();
97
    }
98
99
    /**
100
     * @param int $numeral Numeral to add to the RPN stack
101
     */
102
    protected function match_numeral($numeral) {
103
        $this->rpn[]   = $numeral;
104
        $this->infix[] = $numeral;
105
    }
106
107
    protected function match_dice($dice) {
108
        $dice          = new CalcDice($dice);
109
        $this->rpn[]   = $dice->value();
110
        $this->infix[] = $dice;
111
    }
112
113
    protected function match_set($set) {
114
        $this->rpn[]   = new CalcSet($set);
115
        $this->infix[] = end($this->rpn);
116
    }
117
118
    /**
119
     * @param $variable
120
     */
121
    protected function match_variable($variable) {
122
        $this->rpn[]   = $variable;
123
        $this->infix[] = end($this->rpn);
124
    }
125
126
    protected function match_parens($parenthesis) {
127
        $this->infix[] = $parenthesis;
128
        if ($parenthesis == '(') {
129
            $this->stack[] = $parenthesis;
130
        } else {
131
            while (count($this->stack) > 0 && end($this->stack) != '(') {
132
                $this->rpn[] = array_pop($this->stack);
133
            }
134
            array_pop($this->stack);
135
        }
136
    }
137
138
    /**
139
     * @param $operator
140
     */
141
    protected function match_operator($operator) {
142
        while (
143
            count($this->stack) > 0
144
            &&
145
            end($this->stack) != '('
146
            &&
147
            $this->ooo[$operator] <= $this->ooo[end($this->stack)]
148
        ) {
149
            $this->rpn[] = array_pop($this->stack);
150
        }
151
        $this->stack[] = $operator;
152
        $this->infix[] = $operator;
153
    }
154
155
    protected function clear_stack() {
156
        while (count($this->stack) > 0) {
157
            $this->rpn[] = array_pop($this->stack);
158
        }
159
    }
160
161
    /**
162
     * @return mixed|string
163
     * @throws \Exception
164
     */
165
    public function __invoke() {
166
167
        $stack = [];
168
169
        foreach ($this->rpn as $step) {
170
            if (is_object($step) || !isset($this->ooo[$step])) {
171
                $stack[] = $step;
172
            } else {
173
                $r1 = array_pop($stack);
174
                $r2 = array_pop($stack);
175
176
                if (is_numeric($r1) && is_numeric($r2)) {
177
                    $stack[] = CalcOperation::calc($step, $r2, $r1);
178
                }
179
                if ($r1 instanceof CalcSet && is_numeric($r2)) {
180
                    $stack[] = $r1->calc($step, $r2);
181
                }
182
                if (is_numeric($r1) && $r2 instanceof CalcSet) {
183
                    $stack[] = $r2->rcalc($step, $r1);
184
                }
185
                if ($r1 instanceof CalcSet && $r2 instanceof CalcSet) {
186
                    $stack[] = $r1->mcalc($step, $r2);
187
                }
188
            }
189
        }
190
191
        if (count($stack) > 1) {
192
            throw new \Exception('Missing operator near "' . $stack[1] . '".');
193
        } else {
194
            $out = reset($stack);
195
196
            return $out;
197
        }
198
    }
199
200
    public function infix() {
201
        return implode(' ', $this->infix);
202
    }
203
204
}
205