Passed
Push — master ( d3a94c...76e109 )
by Valentin
05:50
created

UpdateConstructor::makeParentConstructorCall()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Cycle\ORM\Promise\Visitor;
5
6
use PhpParser\Node;
7
use PhpParser\NodeVisitorAbstract;
8
9
/**
10
 * Add constructor
11
 */
12
class UpdateConstructor extends NodeVisitorAbstract
13
{
14
    /** @var bool */
15
    private $hasConstructor;
16
17
    /** @var string */
18
    private $property;
19
20
    /** @var string */
21
    private $type;
22
23
    /** @var array */
24
    private $dependencies = [];
25
26
    public function __construct(bool $hasConstructor, string $property, string $propertyType, array $dependencies)
27
    {
28
        $this->hasConstructor = $hasConstructor;
29
        $this->property = $property;
30
        $this->type = $propertyType;
31
        $this->dependencies = $dependencies;
32
    }
33
34
    /**
35
     * {@inheritdoc}
36
     */
37
    public function leaveNode(Node $node)
38
    {
39
        if ($node instanceof Node\Stmt\ClassMethod && $node->name->name === '__construct') {
40
            $node->stmts[] = $this->makeResolverPropertyAssignment();
41
            if ($this->hasConstructor) {
42
                $node->stmts[] = $this->makeParentConstructorCall();
43
            }
44
        }
45
46
        return null;
47
    }
48
49
    private function makeResolverPropertyAssignment(): Node\Stmt\Expression
50
    {
51
        $prop = new Node\Expr\PropertyFetch(new Node\Expr\Variable("this"), $this->property);
52
        $instance = new Node\Expr\New_(new Node\Name($this->type), $this->makeResolverPropertyInstantiationArgs());
53
54
        return new Node\Stmt\Expression(new Node\Expr\Assign($prop, $instance));
55
    }
56
57
    private function makeResolverPropertyInstantiationArgs(): array
58
    {
59
        $args = [];
60
        foreach ($this->dependencies as $name => $type) {
61
            $args[] = new Node\Arg(new Node\Expr\Variable($name));
62
        }
63
64
        return $args;
65
    }
66
67
    private function makeParentConstructorCall(): Node\Stmt\Expression
68
    {
69
        return new Node\Stmt\Expression(new Node\Expr\StaticCall(new Node\Name('parent'), '__construct'));
70
    }
71
}