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