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

src/Visitor/AddMagicIssetMethod.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\Expressions;
13
use PhpParser\Builder;
14
use PhpParser\Node;
15
use PhpParser\NodeVisitorAbstract;
16
17 View Code Duplication
final class AddMagicIssetMethod extends NodeVisitorAbstract
0 ignored issues
show
This class 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...
18
{
19
    /** @var string */
20
    private $resolverProperty;
21
22
    /** @var string */
23
    private $resolveMethod;
24
25
    /** @var string */
26
    private $unsetPropertiesProperty;
27
28
    /**
29
     * @param string $resolverProperty
30
     * @param string $resolveMethod
31
     * @param string $unsetPropertiesProperty
32
     */
33
    public function __construct(string $resolverProperty, string $resolveMethod, string $unsetPropertiesProperty)
34
    {
35
        $this->unsetPropertiesProperty = $unsetPropertiesProperty;
36
        $this->resolveMethod = $resolveMethod;
37
        $this->resolverProperty = $resolverProperty;
38
    }
39
40
    /**
41
     * @param Node $node
42
     * @return int|Node|Node[]|null
43
     */
44
    public function leaveNode(Node $node)
45
    {
46
        if ($node instanceof Node\Stmt\Class_) {
47
            $method = new Builder\Method('__isset');
48
            $method->makePublic();
49
            $method->addParam(new Builder\Param('name'));
50
            $method->addStmt($this->buildIssetExpression());
51
52
            $node->stmts[] = $method->getNode();
53
        }
54
55
        return null;
56
    }
57
58
    /**
59
     * @return Node\Stmt\If_
60
     */
61
    private function buildIssetExpression(): Node\Stmt\If_
62
    {
63
        $if = new Node\Stmt\If_(Expressions::inConstArrayFunc('name', 'self', $this->unsetPropertiesProperty));
64
        $if->stmts[] = Expressions::resolveIntoVar('entity', 'this', $this->resolverProperty, $this->resolveMethod);
65
        $if->stmts[] = Expressions::throwExceptionOnNull(
66
            new Node\Expr\Variable('entity'),
67
            new Node\Stmt\Return_(Expressions::issetFunc('entity', '{$name}'))
68
        );
69
        $if->else = new Node\Stmt\Else_([
70
            new Node\Stmt\Return_(Expressions::issetFunc('this', '{$name}'))
71
        ]);
72
73
        return $if;
74
    }
75
}