Completed
Pull Request — 2.x (#349)
by Alexander
02:20
created

FunctionCallArgumentListGenerator::__construct()   B

Complexity

Conditions 6
Paths 18

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 9
cts 9
cp 1
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 8
nc 18
nop 1
crap 6
1
<?php
2
declare(strict_types=1);
3
/*
4
 * Go! AOP framework
5
 *
6
 * @copyright Copyright 2018, Lisachenko Alexander <[email protected]>
7
 *
8
 * This source file is subject to the license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Go\Proxy\Part;
13
14
use ReflectionFunctionAbstract;
15
use Zend\Code\Generator\AbstractGenerator;
16
17
/**
18
 * Prepares the function call argument list
19
 */
20
final class FunctionCallArgumentListGenerator extends AbstractGenerator
21
{
22
    /**
23
     * List of function arguments
24
     *
25
     * @var string[]
26
     */
27
    private $arguments;
28
29
    /**
30
     * If function contains optional arguments
31
     *
32
     * @var bool
33
     */
34
    private $hasOptionals = false;
35
36
    /**
37
     * Definition of variadic argument or null if function is not variadic
38
     *
39
     * @var mixed|null
40
     */
41
    private $variadicArgument = null;
42
43
    /**
44
     * FunctionCallArgumentList constructor.
45
     *
46
     * @param ReflectionFunctionAbstract $functionLike Instance of function or method to call
47
     */
48 16
    public function __construct(ReflectionFunctionAbstract $functionLike)
49
    {
50 16
        parent::__construct();
51
52 16
        foreach ($functionLike->getParameters() as $parameter) {
53 12
            $byReference  = ($parameter->isPassedByReference() && !$parameter->isVariadic()) ? '&' : '';
54 12
            $this->hasOptionals = $this->hasOptionals || $parameter->isOptional();
55 12
            $this->arguments[]  = $byReference . '$' . $parameter->name;
56
        }
57 16
        if ($functionLike->isVariadic()) {
58
            // Variadic argument is last and should be handled separately
59 3
            $this->variadicArgument = array_pop($this->arguments);
60
        }
61 16
    }
62
63
    /**
64
     * @inheritDoc
65
     */
66 16
    public function generate()
67
    {
68 16
        $argumentsPart = [];
69 16
        if ($this->variadicArgument !== null) {
70 3
            $argumentsPart[] = $this->variadicArgument;
71
        }
72 16
        if (!empty($this->arguments)) {
73 11
            $argumentLine = '[' . implode(', ', $this->arguments) . ']';
74 11
            if ($this->hasOptionals) {
75 5
                $argumentLine = "\\array_slice($argumentLine, 0, \\func_num_args())";
76
            }
77 11
            array_unshift($argumentsPart, $argumentLine);
78
        }
79
80 16
        return implode(', ', $argumentsPart);
81
    }
82
}
83