aboutsummaryrefslogtreecommitdiff
path: root/src/NXP/MathExecutor.php
blob: e7e825966de99dc4bf6aa93b25f0c6bcb5a87082 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
<?php
/**
 * This file is part of the MathExecutor package
 *
 * (c) Alexander Kiryukhin
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code
 */

namespace NXP;

use NXP\Classes\Calculator;
use NXP\Classes\CustomFunction;
use NXP\Classes\Operator;
use NXP\Classes\Token;
use NXP\Classes\Tokenizer;
use NXP\Exception\DivisionByZeroException;
use NXP\Exception\IncorrectNumberOfFunctionParametersException;
use NXP\Exception\MathExecutorException;
use NXP\Exception\UnknownVariableException;
use ReflectionException;

/**
 * Class MathExecutor
 * @package NXP
 */
class MathExecutor
{
    /**
     * Available variables
     *
     * @var array<string, float|string>
     */
    protected array $variables = [];

    /**
     * @var callable|null
     */
    protected $onVarNotFound = null;

    /**
     * @var callable|null
     */
    protected $onVarValidation = null;

    /**
     * @var Operator[]
     */
    protected array $operators = [];

    /**
     * @var array<string, CustomFunction>
     */
    protected array $functions = [];

    /**
     * @var array<string, Token[]>
     */
    protected array $cache = [];

    /**
     * Base math operators
     */
    public function __construct()
    {
        $this->addDefaults();
    }

    public function __clone()
    {
        $this->addDefaults();
    }

    /**
     * Add operator to executor
     *
     * @return MathExecutor
     */
    public function addOperator(Operator $operator) : self
    {
        $this->operators[$operator->operator] = $operator;

        return $this;
    }

    /**
     * Execute expression
     *
     * @throws Exception\IncorrectBracketsException
     * @throws Exception\IncorrectExpressionException
     * @throws Exception\UnknownOperatorException
     * @throws UnknownVariableException
     * @return int|float|string|null
     */
    public function execute(string $expression, bool $cache = true)
    {
        $cacheKey = $expression;

        if (! \array_key_exists($cacheKey, $this->cache)) {
            $tokens = (new Tokenizer($expression, $this->operators))->tokenize()->buildReversePolishNotation();

            if ($cache) {
                $this->cache[$cacheKey] = $tokens;
            }
        } else {
            $tokens = $this->cache[$cacheKey];
        }

        $calculator = new Calculator($this->functions, $this->operators);

        return $calculator->calculate($tokens, $this->variables, $this->onVarNotFound);
    }

    /**
     * Add function to executor
     *
     * @param string        $name     Name of function
     * @param callable|null $function Function
     *
     * @throws ReflectionException
     * @throws Exception\IncorrectNumberOfFunctionParametersException
     * @return MathExecutor
     */
    public function addFunction(string $name, ?callable $function = null) : self
    {
        $this->functions[$name] = new CustomFunction($name, $function);

        return $this;
    }

    /**
     * Get all vars
     *
     * @return array<string, float|string>
     */
    public function getVars() : array
    {
        return $this->variables;
    }

    /**
     * Get a specific var
     *
     * @throws UnknownVariableException if VarNotFoundHandler is not set
     * @return int|float
     */
    public function getVar(string $variable)
    {
        if (! \array_key_exists($variable, $this->variables)) {
            if ($this->onVarNotFound) {
                return \call_user_func($this->onVarNotFound, $variable);
            }

            throw new UnknownVariableException("Variable ({$variable}) not set");
        }

        return $this->variables[$variable];
    }

    /**
     * Add variable to executor. To set a custom validator use setVarValidationHandler.
     *
     * @throws MathExecutorException if the value is invalid based on the default or custom validator
     * @return MathExecutor
     */
    public function setVar(string $variable, $value) : self
    {
        if ($this->onVarValidation) {
            \call_user_func($this->onVarValidation, $variable, $value);
        }

        $this->variables[$variable] = $value;

        return $this;
    }

    /**
     * Test to see if a variable exists
     *
     */
    public function varExists(string $variable) : bool
    {
        return \array_key_exists($variable, $this->variables);
    }

    /**
     * Add variables to executor
     *
     * @param  array<string, float|int|string> $variables
     * @param  bool $clear Clear previous variables
     * @throws \Exception
     * @return MathExecutor
     */
    public function setVars(array $variables, bool $clear = true) : self
    {
        if ($clear) {
            $this->removeVars();
        }

        foreach ($variables as $name => $value) {
            $this->setVar($name, $value);
        }

        return $this;
    }

    /**
     * Define a method that will be invoked when a variable is not found.
     * The first parameter will be the variable name, and the returned value will be used as the variable value.
     *
     *
     * @return MathExecutor
     */
    public function setVarNotFoundHandler(callable $handler) : self
    {
        $this->onVarNotFound = $handler;

        return $this;
    }

    /**
     * Define a validation method that will be invoked when a variable is set using setVar.
     * The first parameter will be the variable name, and the second will be the variable value.
     * Set to null to disable validation.
     *
     * @param ?callable $handler throws a MathExecutorException in case of an invalid variable
     *
     * @return MathExecutor
     */
    public function setVarValidationHandler(?callable $handler) : self
    {
        $this->onVarValidation = $handler;

        return $this;
    }

    /**
     * Remove variable from executor
     *
     * @return MathExecutor
     */
    public function removeVar(string $variable) : self
    {
        unset($this->variables[$variable]);

        return $this;
    }

    /**
     * Remove all variables and the variable not found handler
     * @return MathExecutor
     */
    public function removeVars() : self
    {
        $this->variables = [];
        $this->onVarNotFound = null;

        return $this;
    }

    /**
     * Get all registered operators to executor
     *
     * @return array<Operator> of operator class names
     */
    public function getOperators()
    {
        return $this->operators;
    }

    /**
     * Get all registered functions
     *
     * @return array<string, CustomFunction> containing callback and places indexed by
     *         function name
     */
    public function getFunctions() : array
    {
        return $this->functions;
    }

    /**
     * Set division by zero returns zero instead of throwing DivisionByZeroException
     */
    public function setDivisionByZeroIsZero() : self
    {
        $this->addOperator(new Operator('/', false, 180, static fn($a, $b) => 0 == $b ? 0 : $a / $b));

        return $this;
    }

    /**
     * Get cache array with tokens
     * @return array<string, Token[]>
     */
    public function getCache() : array
    {
        return $this->cache;
    }

    /**
     * Clear token's cache
     */
    public function clearCache() : void
    {
        $this->cache = [];
    }

    /**
     * Set default operands and functions
     * @throws ReflectionException
     */
    protected function addDefaults() : void
    {
        foreach ($this->defaultOperators() as $name => $operator) {
            [$callable, $priority, $isRightAssoc] = $operator;
            $this->addOperator(new Operator($name, $isRightAssoc, $priority, $callable));
        }

        foreach ($this->defaultFunctions() as $name => $callable) {
            $this->addFunction($name, $callable);
        }

        $this->onVarValidation = [$this, 'defaultVarValidation'];
        $this->variables = $this->defaultVars();
    }

    /**
     * Get the default operators
     *
     * @return array<string, array{callable, int, bool}>
     */
    protected function defaultOperators() : array
    {
        return [
          '+' => [static fn($a, $b) => $a + $b, 170, false],
          '-' => [static fn($a, $b) => $a - $b, 170, false],
          // unary positive token
          'uPos' => [static fn($a) => $a, 200, false],
          // unary minus token
          'uNeg' => [static fn($a) => 0 - $a, 200, false],
          '*' => [static fn($a, $b) => $a * $b, 180, false],
          '/' => [
            static function($a, $b) { /** @todo PHP8: Use throw as expression -> static fn($a, $b) => 0 == $b ? throw new DivisionByZeroException() : $a / $b */
                if (0 == $b) {
                    throw new DivisionByZeroException();
                }

                return $a / $b;
            },
            180,
            false
          ],
          '^' => [static fn($a, $b) => \pow($a, $b), 220, true],
          '&&' => [static fn($a, $b) => $a && $b, 100, false],
          '||' => [static fn($a, $b) => $a || $b, 90, false],
          '==' => [static fn($a, $b) => \is_string($a) || \is_string($b) ? 0 == \strcmp($a, $b) : $a == $b, 140, false],
          '!=' => [static fn($a, $b) => \is_string($a) || \is_string($b) ? 0 != \strcmp($a, $b) : $a != $b, 140, false],
          '>=' => [static fn($a, $b) => $a >= $b, 150, false],
          '>' => [static fn($a, $b) => $a > $b, 150, false],
          '<=' => [static fn($a, $b) => $a <= $b, 150, false],
          '<' => [static fn($a, $b) => $a < $b, 150, false],
        ];
    }

    /**
     * Gets the default functions as an array.  Key is function name
     * and value is the function as a closure.
     *
     * @return array<callable>
     */
    protected function defaultFunctions() : array
    {
        return [
          'abs' => static fn($arg) => \abs($arg),
          'acos' => static fn($arg) => \acos($arg),
          'acosh' => static fn($arg) => \acosh($arg),
          'arcsin' => static fn($arg) => \asin($arg),
          'arcctg' => static fn($arg) => M_PI / 2 - \atan($arg),
          'arccot' => static fn($arg) => M_PI / 2 - \atan($arg),
          'arccotan' => static fn($arg) => M_PI / 2 - \atan($arg),
          'arcsec' => static fn($arg) => \acos(1 / $arg),
          'arccosec' => static fn($arg) => \asin(1 / $arg),
          'arccsc' => static fn($arg) => \asin(1 / $arg),
          'arccos' => static fn($arg) => \acos($arg),
          'arctan' => static fn($arg) => \atan($arg),
          'arctg' => static fn($arg) => \atan($arg),
          'asin' => static fn($arg) => \asin($arg),
          'atan' => static fn($arg) => \atan($arg),
          'atan2' => static fn($arg1, $arg2) => \atan2($arg1, $arg2),
          'atanh' => static fn($arg) => \atanh($arg),
          'atn' => static fn($arg) => \atan($arg),
          'avg' => static function($arg1, $args) {
              if (\is_array($arg1)){
                  return \array_sum($arg1) / \count($arg1);
              }

              if (0 === \count($args)){
                  throw new IncorrectNumberOfFunctionParametersException();
              }
              $args = [$arg1, ...$args];

              return \array_sum($args) / \count($args);
          },
          'bindec' => static fn($arg) => \bindec($arg),
          'ceil' => static fn($arg) => \ceil($arg),
          'cos' => static fn($arg) => \cos($arg),
          'cosec' => static fn($arg) => 1 / \sin($arg),
          'csc' => static fn($arg) => 1 / \sin($arg),
          'cosh' => static fn($arg) => \cosh($arg),
          'ctg' => static fn($arg) => \cos($arg) / \sin($arg),
          'cot' => static fn($arg) => \cos($arg) / \sin($arg),
          'cotan' => static fn($arg) => \cos($arg) / \sin($arg),
          'cotg' => static fn($arg) => \cos($arg) / \sin($arg),
          'ctn' => static fn($arg) => \cos($arg) / \sin($arg),
          'decbin' => static fn($arg) => \decbin($arg),
          'dechex' => static fn($arg) => \dechex($arg),
          'decoct' => static fn($arg) => \decoct($arg),
          'deg2rad' => static fn($arg) => \deg2rad($arg),
          'exp' => static fn($arg) => \exp($arg),
          'expm1' => static fn($arg) => \expm1($arg),
          'floor' => static fn($arg) => \floor($arg),
          'fmod' => static fn($arg1, $arg2) => \fmod($arg1, $arg2),
          'hexdec' => static fn($arg) => \hexdec($arg),
          'hypot' => static fn($arg1, $arg2) => \hypot($arg1, $arg2),
          'if' => function($expr, $trueval, $falseval) {
              if (true === $expr || false === $expr) {
                  $exres = $expr;
              } else {
                  $exres = $this->execute($expr);
              }

              if ($exres) {
                  return $this->execute($trueval);
              }

              return $this->execute($falseval);
          },
          'intdiv' => static fn($arg1, $arg2) => \intdiv($arg1, $arg2),
          'ln' => static fn($arg) => \log($arg),
          'lg' => static fn($arg) => \log10($arg),
          'log' => static fn($arg) => \log($arg),
          'log10' => static fn($arg) => \log10($arg),
          'log1p' => static fn($arg) => \log1p($arg),
          'max' => static function($arg1, ...$args) {
              if (! \is_array($arg1) && 0 === \count($args)){
                  throw new IncorrectNumberOfFunctionParametersException();
              }

              return \max($arg1, ...$args);
          },
          'min' => static function($arg1, ...$args) {
              if (! \is_array($arg1) && 0 === \count($args)){
                  throw new IncorrectNumberOfFunctionParametersException();
              }

              return \min($arg1, ...$args);
          },
          'octdec' => static fn($arg) => \octdec($arg),
          'pi' => static fn() => M_PI,
          'pow' => static fn($arg1, $arg2) => $arg1 ** $arg2,
          'rad2deg' => static fn($arg) => \rad2deg($arg),
          'round' => static fn($num, int $precision = 0) => \round($num, $precision),
          'sin' => static fn($arg) => \sin($arg),
          'sinh' => static fn($arg) => \sinh($arg),
          'sec' => static fn($arg) => 1 / \cos($arg),
          'sqrt' => static fn($arg) => \sqrt($arg),
          'tan' => static fn($arg) => \tan($arg),
          'tanh' => static fn($arg) => \tanh($arg),
          'tn' => static fn($arg) => \tan($arg),
          'tg' => static fn($arg) => \tan($arg)
        ];
    }

    /**
     * Returns the default variables names as key/value pairs
     *
     * @return array<string, float>
     */
    protected function defaultVars() : array
    {
        return [
          'pi' => 3.14159265359,
          'e' => 2.71828182846
        ];
    }

    /**
     * Default variable validation, ensures that the value is a scalar.
     * @throws MathExecutorException if the value is not a scalar
     */
    protected function defaultVarValidation(string $variable, $value) : void
    {
        if (! \is_scalar($value) && ! \is_array($value) && null !== $value) {
            $type = \gettype($value);

            throw new MathExecutorException("Variable ({$variable}) type ({$type}) is not scalar or array!");
        }
    }
}