1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Vanderlee\Comprehend\Core; |
4
|
|
|
|
5
|
|
|
use Vanderlee\Comprehend\Parser\Parser; |
6
|
|
|
use Vanderlee\Comprehend\Parser\Structure\Choice; |
7
|
|
|
use Vanderlee\Comprehend\Parser\Structure\Sequence; |
8
|
|
|
use Vanderlee\Comprehend\Parser\Terminal\Char; |
9
|
|
|
use Vanderlee\Comprehend\Parser\Terminal\Text; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Process arguments |
13
|
|
|
* |
14
|
|
|
* @author Martijn |
15
|
|
|
*/ |
16
|
|
|
trait ArgumentsTrait |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Convert the argument to a parser |
21
|
|
|
* |
22
|
|
|
* @param mixed $argument |
23
|
|
|
* @param bool $arrayToSequence if argument is an array, convert to Sequence (`true`) or Choice (`false`) |
24
|
|
|
* @return Parser |
25
|
|
|
*/ |
26
|
|
|
protected static function getArgument($argument, $arrayToSequence = true) |
27
|
|
|
{ |
28
|
|
|
if (is_array($argument)) { |
29
|
|
|
if (empty($argument)) { |
30
|
|
|
throw new \InvalidArgumentException('Empty array argument'); |
31
|
|
|
} elseif (count($argument) === 1) { |
32
|
|
|
return self::getArgument(reset($argument)); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
return $arrayToSequence ? new Sequence(...$argument) : new Choice(...$argument); |
36
|
|
|
} elseif (is_string($argument)) { |
37
|
|
|
switch (strlen($argument)) { |
38
|
|
|
case 0: |
39
|
|
|
throw new \InvalidArgumentException('Empty argument'); |
40
|
|
|
case 1: |
41
|
|
|
return new Char($argument); |
42
|
|
|
default: |
43
|
|
|
return new Text($argument); |
44
|
|
|
} |
45
|
|
|
} elseif (is_int($argument)) { |
46
|
|
|
return new Char($argument); |
47
|
|
|
} elseif ($argument instanceof Parser) { |
48
|
|
|
return $argument; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
throw new \InvalidArgumentException(sprintf('Invalid argument type `%1$s`', |
52
|
|
|
is_object($argument) ? get_class($argument) : gettype($argument))); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
protected static function getArguments($arguments, $arrayToSequence = true) |
56
|
|
|
{ |
57
|
|
|
return array_map(function ($argument) use ($arrayToSequence) { |
58
|
|
|
return self::getArgument($argument, $arrayToSequence); |
59
|
|
|
}, $arguments); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|