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

ParameterDefinition   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 24
c 1
b 0
f 0
dl 0
loc 59
ccs 28
cts 28
cp 1
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getCallable() 0 11 2
A isVariadic() 0 3 1
A __construct() 0 3 1
A resolve() 0 22 4
A isOptional() 0 3 1
A hasValue() 0 3 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