Passed
Pull Request — master (#129)
by Alexander
04:42 queued 02:13
created

ParameterDefinition::getCallable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 11
ccs 7
cts 7
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Factory\Definition;
6
7
use ReflectionParameter;
8
use Yiisoft\Factory\DependencyResolverInterface;
9
use Yiisoft\Factory\Exception\NotInstantiableException;
10
11
final class ParameterDefinition implements DefinitionInterface
12
{
13
    private ReflectionParameter $parameter;
14
15 17
    public function __construct(ReflectionParameter $parameter)
16
    {
17 17
        $this->parameter = $parameter;
18 17
    }
19
20 63
    public function isVariadic(): bool
21
    {
22 63
        return $this->parameter->isVariadic();
23
    }
24
25 45
    public function isOptional(): bool
26
    {
27 45
        return $this->parameter->isOptional();
28
    }
29
30 41
    public function hasValue(): bool
31
    {
32 41
        return $this->parameter->isDefaultValueAvailable() || $this->parameter->allowsNull();
33
    }
34
35 46
    public function resolve(DependencyResolverInterface $container)
36
    {
37 46
        if ($this->parameter->isDefaultValueAvailable()) {
38 42
            return $this->parameter->getDefaultValue();
39
        }
40
41 4
        if ($this->parameter->allowsNull()) {
42 2
            return null;
43
        }
44
45 2
        if ($this->isOptional()) {
46 1
            throw new NotInstantiableException(
47 1
                sprintf(
48
                    'Can not determine default value of parameter "%s" when instantinate "%s" ' .
49 1
                    'because it is PHP internal. Please specify argument explicitly.',
50 1
                    $this->parameter->getName(),
51 1
                    $this->getCallable(),
52
                )
53
            );
54
        }
55
56 1
        throw new NotInstantiableException('Parameter definition does not contain a value.');
57
    }
58
59 1
    private function getCallable(): string
60
    {
61 1
        $callable = [];
62
63 1
        $class = $this->parameter->getDeclaringClass();
64 1
        if ($class !== null) {
65 1
            $callable[] = $class->getName();
66
        }
67 1
        $callable[] = $this->parameter->getDeclaringFunction()->getName() . '()';
68
69 1
        return implode('::', $callable);
70
    }
71
}
72