(string $expression)
| 278 | } |
| 279 | |
| 280 | private function compile(string $expression): array { |
| 281 | $tokens = []; |
| 282 | $offset = 0; |
| 283 | while ($offset < strlen($expression)) { |
| 284 | if (preg_match('/\G\s+/A', $expression, $match, 0, $offset)) { |
| 285 | $offset += strlen($match[0]); |
| 286 | continue; |
| 287 | } |
| 288 | if (!preg_match('/\G(\{[A-Za-z0-9_:-]+\}|(?:\d+(?:\.\d*)?|\.\d+)|\'(?:[^\']|\'\')*\'|LOOKUP\b|[(),+*\/-])/Ai', $expression, $match, 0, $offset)) { |
| 289 | throw new \InvalidArgumentException('The formula contains an unsupported token.'); |
| 290 | } |
| 291 | $tokens[] = $match[1]; |
| 292 | $offset += strlen($match[0]); |
| 293 | } |
| 294 | if ($tokens === []) { |
| 295 | throw new \InvalidArgumentException('A formula is required.'); |
| 296 | } |
| 297 | $position = 0; |
| 298 | $parse = function (int $minimum = 0) use (&$parse, &$position, $tokens): array { |
| 299 | $token = $tokens[$position++] ?? ''; |
| 300 | if ($token === '-') { |
| 301 | $output = [...$parse(3), 'neg']; |
| 302 | } elseif ($token === '(') { |
| 303 | $output = $parse(); |
| 304 | if (($tokens[$position++] ?? '') !== ')') throw new \InvalidArgumentException('Unmatched formula parenthesis.'); |
| 305 | } elseif (strtoupper($token) === 'LOOKUP') { |
| 306 | if (($tokens[$position++] ?? '') !== '(') throw new \InvalidArgumentException('LOOKUP requires parentheses.'); |
| 307 | $output = []; |
| 308 | $count = 0; |
| 309 | do { |
| 310 | $output = [...$output, ...$parse()]; |
| 311 | $count++; |
| 312 | $separator = $tokens[$position++] ?? ''; |
| 313 | } while ($separator === ','); |
| 314 | if ($separator !== ')' || $count < 4 || $count % 2 !== 0) { |
| 315 | throw new \InvalidArgumentException('Use LOOKUP(value, match, score, ..., fallback).'); |
| 316 | } |
| 317 | $output[] = 'lookup:' . $count; |
| 318 | } elseif (is_numeric($token) || str_starts_with($token, '{') || str_starts_with($token, "'")) { |
| 319 | $output = [$token]; |
| 320 | } else { |
| 321 | throw new \InvalidArgumentException('Missing formula operand.'); |
| 322 | } |
| 323 | $precedence = ['+' => 1, '-' => 1, '*' => 2, '/' => 2]; |
| 324 | while (isset($precedence[$tokens[$position] ?? '']) && $precedence[$tokens[$position]] >= $minimum) { |
| 325 | $operator = $tokens[$position++]; |
| 326 | $output = [...$output, ...$parse($precedence[$operator] + 1), $operator]; |
| 327 | } |
| 328 | return $output; |
| 329 | }; |
| 330 | $output = $parse(); |
| 331 | if ($position !== count($tokens)) throw new \InvalidArgumentException('Unexpected formula token.'); |
| 332 | return $output; |
| 333 | } |
| 334 | |
| 335 | private function evaluate(array $rpn, array $row): ?float { |
| 336 | $stack = []; |
no test coverage detected