vanderlee /
Comprehend
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Vanderlee\Comprehend\Parser\Terminal; |
||
| 4 | |||
| 5 | use InvalidArgumentException; |
||
| 6 | use Vanderlee\Comprehend\Core\Context; |
||
| 7 | use Vanderlee\Comprehend\Parser\Parser; |
||
| 8 | |||
| 9 | /** |
||
| 10 | * Matches regular expressions. |
||
| 11 | * |
||
| 12 | * @author Martijn |
||
| 13 | */ |
||
| 14 | class Regex extends Parser |
||
| 15 | { |
||
| 16 | use CaseSensitiveTrait; |
||
| 17 | |||
| 18 | /** |
||
| 19 | * @var string|null |
||
| 20 | */ |
||
| 21 | private $pattern = null; |
||
| 22 | |||
| 23 | 12 | public function __construct(string $pattern) |
|
| 24 | { |
||
| 25 | 12 | if (empty($pattern)) { |
|
| 26 | 1 | throw new InvalidArgumentException('Empty pattern'); |
|
| 27 | } |
||
| 28 | |||
| 29 | 11 | if (@preg_match($pattern, null) === false) { |
|
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 30 | 2 | throw new InvalidArgumentException('Invalid pattern'); |
|
| 31 | } |
||
| 32 | |||
| 33 | 9 | $this->pattern = $pattern; |
|
| 34 | 9 | } |
|
| 35 | |||
| 36 | 9 | protected function parse(&$input, $offset, Context $context) |
|
| 37 | { |
||
| 38 | 9 | $this->pushCaseSensitivityToContext($context); |
|
| 39 | 9 | $pattern = $this->pattern . ($context->isCaseSensitive() |
|
| 40 | 8 | ? '' |
|
| 41 | 9 | : 'i'); |
|
| 42 | 9 | $this->popCaseSensitivityFromContext($context); |
|
| 43 | |||
| 44 | 9 | if (preg_match($pattern, $input, $match, 0, $offset) !== false) { |
|
| 45 | 9 | if (count($match) > 0 && mb_strlen($match[0]) > 0 && strpos($input, $match[0], $offset) === $offset) { |
|
| 46 | 6 | return $this->success($input, $offset, mb_strlen($match[0])); |
|
| 47 | } |
||
| 48 | } |
||
| 49 | |||
| 50 | 3 | return $this->failure($input, $offset); |
|
| 51 | } |
||
| 52 | |||
| 53 | 9 | public function __toString() |
|
| 54 | { |
||
| 55 | 9 | return (string)$this->pattern; |
|
| 56 | } |
||
| 57 | } |
||
| 58 |