Passed
Push — master ( 3a32ec...04e24a )
by Martijn
02:33
created

ArgumentsTrait   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Test Coverage

Coverage 96.3%

Importance

Changes 0
Metric Value
eloc 28
dl 0
loc 48
ccs 26
cts 27
cp 0.963
rs 10
c 0
b 0
f 0
wmc 12

2 Methods

Rating   Name   Duplication   Size   Complexity  
B getArgument() 0 31 11
A getArguments() 0 5 1
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