Passed
Push — master ( 327a11...1a5769 )
by Valentin
58s
created

AddUnsetPropertiesConst::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
declare(strict_types=1);
3
4
namespace Cycle\ORM\Promise\Visitor;
5
6
use Cycle\ORM\Promise\Utils;
7
use PhpParser\Node;
8
use PhpParser\NodeVisitorAbstract;
9
10
/**
11
 * Add "unset properties" property
12
 */
13
class AddUnsetPropertiesConst extends NodeVisitorAbstract
14
{
15
    /** @var string */
16
    private $unsetPropertyConst;
17
18
    /** @var array */
19
    private $unsetPropertiesValues;
20
21
    public function __construct(string $unsetPropertiesConst, array $unsetPropertiesValues)
22
    {
23
        $this->unsetPropertyConst = $unsetPropertiesConst;
24
        $this->unsetPropertiesValues = $unsetPropertiesValues;
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30 View Code Duplication
    public function leaveNode(Node $node)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
31
    {
32
        if ($node instanceof Node\Stmt\Class_) {
33
            $node->stmts = Utils::injectValues($node->stmts, $this->definePlacementID($node), [$this->buildProperty()]);
34
        }
35
36
        return null;
37
    }
38
39
    private function definePlacementID(Node\Stmt\Class_ $node): int
40
    {
41
        foreach ($node->stmts as $index => $child) {
42
            if ($child instanceof Node\Stmt\ClassMethod) {
43
                return $index;
44
            }
45
        }
46
47
        return 0;
48
    }
49
50
    private function buildProperty(): Node\Stmt\ClassConst
51
    {
52
        $array = [];
53
        foreach ($this->unsetPropertiesValues as $value) {
54
            $array[] = new Node\Expr\ArrayItem(new Node\Scalar\String_($value));
55
        }
56
57
        $const = new Node\Stmt\ClassConst([
58
            new Node\Const_($this->unsetPropertyConst, new Node\Expr\Array_($array, ['kind' => Node\Expr\Array_::KIND_SHORT]))
59
        ], Node\Stmt\Class_::MODIFIER_PRIVATE);
60
61
        return $const;
62
    }
63
}