Completed
Pull Request — master (#221)
by personal
04:09
created

ArgumentsParser::parse()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 40
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 7
eloc 22
nc 6
nop 1
dl 0
loc 40
rs 6.7272
c 1
b 0
f 0
1
<?php
2
3
/*
4
 * (c) Jean-François Lépine <https://twitter.com/Halleck45>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace Hal\Component\Parser\CodeParser;
11
12
use Hal\Component\Parser\Exception\IncorrectSyntaxException;
13
use Hal\Component\Reflected\Argument;
14
use Hal\Component\Parser\Resolver\NamespaceResolver;
15
use Hal\Component\Parser\Searcher;
16
use Hal\Component\Token\Token;
17
18
19
class ArgumentsParser
20
{
21
22
    /**
23
     * @var Searcher
24
     */
25
    private $searcher;
26
27
    /**
28
     * @var NamespaceResolver
29
     */
30
    private $namespaceResolver;
31
32
    /**
33
     * CodeParser constructor.
34
     * @param Searcher $searcher
35
     * @param NamespaceResolver $namespaceResolver
36
     */
37
    public function __construct(Searcher $searcher, NamespaceResolver $namespaceResolver)
38
    {
39
        $this->searcher = $searcher;
40
        $this->namespaceResolver = $namespaceResolver;
41
    }
42
43
    /**
44
     * @param $tokens
45
     * @return array
46
     */
47
    public function parse($tokens)
48
    {
49
        $arguments = array();
50
        $len = sizeof($tokens);
51
52
        // default values
53
        $type = null;
54
55
        for ($i = 0; $i < $len; $i++) {
56
            $token = $tokens[$i];
57
58
            // type
59
            if ('$' !== $token[0]) {
60
                $type = $token;
61
                continue;
62
            }
63
64
            $argument = new Argument($token);
65
            $argument->setType($type);
66
            $type = null;
67
68
            // default value
69
            if ($i < $len - 1) {
70
                $next = $tokens[$i + 1];
71
                if (Token::T_EQUAL === $next) {
72
                    $i = $i + 2;
73
                    // look for default value
74
                    if (!isset($tokens[$i]) || Token::T_PARENTHESIS_CLOSE == $tokens[$i]) {
75
                        throw new IncorrectSyntaxException('not default value found for parameter ' . $token);
76
                    }
77
                    $value = $tokens[$i];
78
79
                    $argument->setDefaultValue($value);
80
                }
81
            }
82
            array_push($arguments, $argument);
83
        }
84
85
        return $arguments;
86
    }
87
}