Completed
Push — master ( f04f52...152406 )
by Anton
03:17
created

src/Visitor/AddUnsetPropertiesConst.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license MIT
6
 * @author  Valentin V (Vvval)
7
 */
8
declare(strict_types=1);
9
10
namespace Cycle\ORM\Promise\Visitor;
11
12
use Cycle\ORM\Promise\Utils;
13
use PhpParser\Node;
14
use PhpParser\NodeVisitorAbstract;
15
16
/**
17
 * Add "unset properties" property
18
 */
19
final class AddUnsetPropertiesConst extends NodeVisitorAbstract
20
{
21
    /** @var string */
22
    private $unsetPropertyConst;
23
24
    /** @var array */
25
    private $unsetPropertiesValues;
26
27
    /**
28
     * @param string $unsetPropertiesConst
29
     * @param array  $unsetPropertiesValues
30
     */
31
    public function __construct(string $unsetPropertiesConst, array $unsetPropertiesValues)
32
    {
33
        $this->unsetPropertyConst = $unsetPropertiesConst;
34
        $this->unsetPropertiesValues = $unsetPropertiesValues;
35
    }
36
37
    /**
38
     * {@inheritdoc}
39
     */
40 View Code Duplication
    public function leaveNode(Node $node)
0 ignored issues
show
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...
41
    {
42
        if ($node instanceof Node\Stmt\Class_) {
43
            $node->stmts = Utils::injectValues($node->stmts, $this->definePlacementID($node), [$this->buildProperty()]);
44
        }
45
46
        return null;
47
    }
48
49
    /**
50
     * @param Node\Stmt\Class_ $node
51
     * @return int
52
     */
53
    private function definePlacementID(Node\Stmt\Class_ $node): int
54
    {
55
        foreach ($node->stmts as $index => $child) {
56
            if ($child instanceof Node\Stmt\ClassMethod) {
57
                return $index;
58
            }
59
        }
60
61
        return 0;
62
    }
63
64
    /**
65
     * @return Node\Stmt\ClassConst
66
     */
67
    private function buildProperty(): Node\Stmt\ClassConst
68
    {
69
        $array = [];
70
        foreach ($this->unsetPropertiesValues as $value) {
71
            $array[] = new Node\Expr\ArrayItem(new Node\Scalar\String_($value));
72
        }
73
74
        $const = new Node\Stmt\ClassConst([
75
            new Node\Const_(
76
                $this->unsetPropertyConst,
77
                new Node\Expr\Array_($array, ['kind' => Node\Expr\Array_::KIND_SHORT])
78
            )
79
        ], Node\Stmt\Class_::MODIFIER_PRIVATE);
80
81
        return $const;
82
    }
83
}