|
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
|
115 |
|
protected static function getArgument($argument, $arrayToSequence = true) |
|
27
|
|
|
{ |
|
28
|
115 |
|
if (is_array($argument)) { |
|
29
|
7 |
|
if (empty($argument)) { |
|
30
|
1 |
|
throw new \InvalidArgumentException('Empty array argument'); |
|
31
|
6 |
|
} elseif (count($argument) === 1) { |
|
32
|
2 |
|
return self::getArgument(reset($argument)); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
6 |
|
return $arrayToSequence |
|
36
|
6 |
|
? new Sequence(...$argument) |
|
37
|
6 |
|
: new Choice(...$argument); |
|
38
|
114 |
|
} elseif (is_string($argument)) { |
|
39
|
74 |
|
switch (strlen($argument)) { |
|
40
|
74 |
|
case 0: |
|
41
|
2 |
|
throw new \InvalidArgumentException('Empty argument'); |
|
42
|
73 |
|
case 1: |
|
43
|
64 |
|
return new Char($argument); |
|
44
|
|
|
default: |
|
45
|
22 |
|
return new Text($argument); |
|
46
|
|
|
} |
|
47
|
69 |
|
} elseif (is_int($argument)) { |
|
48
|
2 |
|
return new Char($argument); |
|
49
|
69 |
|
} elseif ($argument instanceof Parser) { |
|
50
|
67 |
|
return $argument; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
2 |
|
throw new \InvalidArgumentException(sprintf('Invalid argument type `%1$s`', |
|
54
|
2 |
|
is_object($argument) |
|
55
|
|
|
? get_class($argument) |
|
56
|
2 |
|
: gettype($argument))); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
protected static function getArguments($arguments, $arrayToSequence = true) |
|
60
|
|
|
{ |
|
61
|
53 |
|
return array_map(function ($argument) use ($arrayToSequence) { |
|
62
|
53 |
|
return self::getArgument($argument, $arrayToSequence); |
|
63
|
53 |
|
}, $arguments); |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|