Completed
Push — master ( c80620...0cd8d9 )
by Martijn
03:25
created

ArgumentsTrait::getArgument()   B

Complexity

Conditions 11
Paths 10

Size

Total Lines 27
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 20
nc 10
nop 2
dl 0
loc 27
rs 7.3166
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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