Completed
Pull Request — 1.x (#203)
by
unknown
01:44
created

ClassParam::getProps()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Resource;
6
7
use function class_exists;
8
use Ray\Di\InjectorInterface;
9
use ReflectionClass;
10
11
final class ClassParam implements ParamInterface
12
{
13
    /**
14
     * @var string
15
     */
16
    private $class;
17
18
    /**
19
     * @var bool
20
     */
21
    private $isDefaultAvailable;
22
23
    /**
24
     * @var mixed
25
     */
26
    private $defaultValue;
27
28
    public function __construct(ReflectionClass $class, \ReflectionParameter $parameter)
29
    {
30
        $this->class = $class->name;
31
        $this->isDefaultAvailable = $parameter->isDefaultValueAvailable();
32
        if ($this->isDefaultAvailable) {
33
            $this->defaultValue = $parameter->getDefaultValue();
34
        }
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40
    public function __invoke(string $varName, array $query, InjectorInterface $injector)
41
    {
42
        assert(class_exists($this->class));
43
        $obj = new $this->class;
44
        foreach ($query as $queryName => $queryValue) {
45
            if (property_exists($obj, $queryName)) {
46
                $obj->{$queryName} = $queryValue;
47
48
                continue;
49
            }
50
            $camelName = lcfirst(strtr(ucwords(strtr($queryName, ['_' => ' '])), [' ' => '']));
51
            if (property_exists($obj, $camelName)) {
52
                $obj->{$camelName} = $queryValue;
53
54
                continue;
55
            }
56
        }
57
58
        return $obj;
59
    }
60
}
61