Passed
Pull Request — master (#13)
by Aleksei
01:24
created

ArgumentException::__construct()   A

Complexity

Conditions 5
Paths 6

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 14
nc 6
nop 2
dl 0
loc 23
ccs 14
cts 14
cp 1
crap 5
rs 9.4888
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Injector;
6
7
abstract class ArgumentException extends \InvalidArgumentException
8
{
9
    protected const EXCEPTION_MESSAGE = 'Something is wrong with argument "%s" when calling "%s"%s.';
10
11 33
    public function __construct(\ReflectionFunctionAbstract $reflection, string $parameter)
12
    {
13 33
        $function = $reflection->getName();
14 33
        $class = $reflection->class ?? null;
15
16 33
        if ($class === null) {
17 26
            $method = $function;
18 26
            if (substr($method, -9) === '{closure}') {
19 26
                $method = $this->getClosureSignature($reflection);
20
            }
21
        } else {
22 7
            $method = "{$class}::{$function}";
23
        }
24
25 33
        $fileName = $reflection->getFileName();
26 33
        $line = $reflection->getStartLine();
27
28 33
        $fileAndLine = '';
29 33
        if (!empty($fileName) && !empty($line)) {
30 23
            $fileAndLine = " in \"$fileName\" at line $line";
31
        }
32
33 33
        parent::__construct(sprintf(static::EXCEPTION_MESSAGE, $parameter, $method, $fileAndLine));
34
    }
35
36 14
    private function getClosureSignature(\ReflectionFunctionAbstract $reflection): string
37
    {
38 14
        $result = 'function (';
39 14
        $closureParameters = [];
40 14
        foreach ($reflection->getParameters() as $parameter) {
41 13
            $parameterString = '';
42 13
            if ($parameter->getType() instanceof \ReflectionNamedType) {
43 13
                $parameterString .= $parameter->getType()->getName() . ' ';
44 13
                if ($parameter->allowsNull()) {
45 3
                    $parameterString = '?' . $parameterString;
46
                }
47
            }
48 13
            if ($parameter->isPassedByReference()) {
49 3
                $parameterString .= '&';
50
            }
51 13
            if ($parameter->isVariadic()) {
52 4
                $parameterString .= '...';
53
            }
54 13
            $parameterString .= '$' . $parameter->name;
55 13
            if ($parameter->isDefaultValueAvailable()) {
56 3
                $parameterString .= ' = ' . var_export($parameter->getDefaultValue(), true);
57
            }
58 13
            $closureParameters[] = $parameterString;
59
        }
60 14
        $result .= implode(', ', $closureParameters);
61 14
        $result .= ')';
62 14
        return $result;
63
    }
64
}
65