1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Vanderlee\Comprehend\Parser\Terminal; |
4
|
|
|
|
5
|
|
|
use Vanderlee\Comprehend\Core\Context; |
6
|
|
|
use Vanderlee\Comprehend\Parser\Parser; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Description of SetParser |
10
|
|
|
* |
11
|
|
|
* @author Martijn |
12
|
|
|
*/ |
13
|
|
|
class Set extends Parser |
14
|
|
|
{ |
15
|
|
|
|
16
|
|
|
use CaseSensitiveTrait; |
17
|
|
|
|
18
|
|
|
private $set = null; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Match only characters inside the set (`true`) or outside (`false`). |
22
|
|
|
* |
23
|
|
|
* @var bool |
24
|
|
|
*/ |
25
|
|
|
private $include = true; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Match any single character in the set or not in the set. |
29
|
|
|
* |
30
|
|
|
* @param string $set |
31
|
|
|
* @param bool $include Set to false to match only characters NOT in the set |
32
|
|
|
* @throws \Exception |
33
|
|
|
*/ |
34
|
|
|
public function __construct(string $set, $include = true) |
35
|
|
|
{ |
36
|
|
|
if (mb_strlen($set) <= 0) { |
37
|
|
|
throw new \InvalidArgumentException('Empty set'); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$this->set = count_chars($set, 3); |
41
|
|
|
$this->include = (bool)$include; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
protected function parse(&$input, $offset, Context $context) |
45
|
|
|
{ |
46
|
|
|
if ($offset >= mb_strlen($input)) { |
47
|
|
|
return $this->failure($input, $offset); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$this->pushCaseSensitivityToContext($context); |
51
|
|
|
|
52
|
|
|
if (strchr($context->handleCase($this->set), $context->handleCase($input[$offset])) !== false) { |
53
|
|
|
$this->popCaseSensitivityFromContext($context); |
54
|
|
|
|
55
|
|
|
return $this->makeMatch($this->include, $input, $offset, 1); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$this->popCaseSensitivityFromContext($context); |
59
|
|
|
|
60
|
|
|
return $this->makeMatch(!$this->include, $input, $offset, 1); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function __toString() |
64
|
|
|
{ |
65
|
|
|
return ($this->include ? '' : chr(0xAC)) . '( \'' . join('\' | \'', str_split($this->set)) . '\' )'; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
} |
69
|
|
|
|