Completed
Pull Request — master (#59)
by
unknown
37:33 queued 28:46
created

HydratorMethodsVisitor::getPrivateProperties()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 9.6666
cc 2
eloc 5
nc 1
nop 1
crap 2
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 *
15
 * This software consists of voluntary contributions made by many individuals
16
 * and is licensed under the MIT license.
17
 */
18
19
declare(strict_types=1);
20
21
namespace GeneratedHydrator\CodeGenerator\Visitor;
22
23
use PhpParser\Node;
24
use PhpParser\Node\Expr\Array_;
25
use PhpParser\Node\Param;
26
use PhpParser\Node\Stmt\Class_;
27
use PhpParser\Node\Stmt\ClassMethod;
28
use PhpParser\Node\Stmt\Property;
29
use PhpParser\Node\Stmt\PropertyProperty;
30
use PhpParser\NodeVisitorAbstract;
31
use PhpParser\ParserFactory;
32
use ReflectionClass;
33
use ReflectionProperty;
34
35
/**
36
 * Replaces methods `__construct`, `hydrate` and `extract` in the classes of the given AST
37
 *
38
 * @author Marco Pivetta <[email protected]>
39
 * @author Pierre Rineau <[email protected]>
40
 * @license MIT
41
 */
42
class HydratorMethodsVisitor extends NodeVisitorAbstract
43
{
44
    /**
45
     * @var ReflectionClass
46
     */
47
    private $reflectedClass;
48
49
    /**
50
     * @var string[][]
51
     */
52
    private $classPropertyMap = array();
53
54
    /**
55
     * @param ReflectionClass $reflectedClass
56
     */
57 2
    public function __construct(ReflectionClass $reflectedClass)
58
    {
59 2
        $this->reflectedClass = $reflectedClass;
60
61 2
        foreach ($this->recursiveFindNonStaticProperties($reflectedClass) as $property) {
62 2
            $className = $property->getDeclaringClass()->getName();
0 ignored issues
show
introduced by
Consider using $property->class. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
63 2
            $this->classPropertyMap[$className][] = $property->getName();
64
        }
65 2
    }
66
67
    /**
68
     * @param Node $node
69
     *
70
     * @return null|Class_
71
     */
72 2
    public function leaveNode(Node $node)
73
    {
74 2
        if (!$node instanceof Class_) {
75
            return null;
76
        }
77
78 2
        $node->stmts[] = new Property(Class_::MODIFIER_PRIVATE, array(
79 2
            new PropertyProperty('hydrateCallbacks', new Array_()),
80 2
            new PropertyProperty('extractCallbacks', new Array_()),
81
        ));
82
83 2
        $this->replaceConstructor($this->findOrCreateMethod($node, '__construct'));
84 2
        $this->replaceHydrate($this->findOrCreateMethod($node, 'hydrate'));
85 2
        $this->replaceExtract($this->findOrCreateMethod($node, 'extract'));
86
87 2
        return $node;
88
    }
89
90
    /**
91
     * Find all class properties recursively using class hierarchy without
92
     * removing name redefinitions
93
     *
94
     * @param \ReflectionClass $class
95
     *
96
     * @return \ReflectionProperty[]
97
     */
98 2
    private function recursiveFindNonStaticProperties(\ReflectionClass $class)
99
    {
100 2
        $ret = [];
101
102 2
        if ($parentClass = $class->getParentClass()) {
103
            $ret = $this->recursiveFindProperties($parentClass);
0 ignored issues
show
Bug introduced by
The method recursiveFindProperties() does not seem to exist on object<GeneratedHydrator...HydratorMethodsVisitor>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
104
        }
105
106
        // We cannot filter with NOT static
107 2
        foreach ($class->getProperties() as $property) {
108 2
            if (!$property->isStatic()) {
109 2
                $ret[] = $property;
110
            }
111
        }
112
113 2
        return $ret;
114
    }
115
116
    /**
117
     * @param ClassMethod $method
118
     */
119 2
    private function replaceConstructor(ClassMethod $method)
120
    {
121 2
        $method->params = array();
122
123 2
        $bodyParts = array();
124
125 2
        foreach ($this->classPropertyMap as $className => $propertyNames) {
126
            // Hydrate closures
127 2
            $bodyParts[] = "\$this->hydrateCallbacks[] = \\Closure::bind(function (\$object, \$values) {";
128 2
            foreach ($propertyNames as $propertyName) {
129 2
                $bodyParts[] = "    if (isset(\$values['" . $propertyName . "'])) {";
130 2
                $bodyParts[] = "        \$object->" . $propertyName . " = \$values['" . $propertyName . "'];";
131 2
                $bodyParts[] = "    }";
132
            }
133 2
            $bodyParts[] = '}, null, ' . var_export($className, true) . ');' . "\n";
134
135
            // Extract closures
136 2
            $bodyParts[] = "\$this->extractCallbacks[] = \\Closure::bind(function (\$object, &\$values) {";
137 2
            foreach ($propertyNames as $propertyName) {
138 2
                $bodyParts[] = "    \$values['" . $propertyName . "'] = \$object->" . $propertyName . ";";
139
            }
140 2
            $bodyParts[] = '}, null, ' . var_export($className, true) . ');' . "\n";
141
        }
142
143 2
        $method->stmts = (new ParserFactory)
0 ignored issues
show
Documentation Bug introduced by
It seems like (new \PhpParser\ParserFa...plode(' ', $bodyParts)) can be null. However, the property $stmts is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
144 2
            ->create(ParserFactory::ONLY_PHP7)
145 2
            ->parse('<?php ' . implode("\n", $bodyParts));
146 2
    }
147
148
    /**
149
     * @param ClassMethod $method
150
     */
151 2
    private function replaceHydrate(ClassMethod $method)
152
    {
153 2
        $method->params = array(
154 2
            new Param('data', null, 'array'),
155 2
            new Param('object'),
156
        );
157
158
        $body = <<<EOT
159
foreach (\$this->hydrateCallbacks as \$callback) {
160
    \$callback->__invoke(\$object, \$data);
161
}
162 2
return \$object;
163
EOT;
164
165 2
        $method->stmts = (new ParserFactory())
0 ignored issues
show
Documentation Bug introduced by
It seems like (new \PhpParser\ParserFa...parse('<?php ' . $body) can be null. However, the property $stmts is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
166 2
            ->create(ParserFactory::ONLY_PHP7)
167 2
            ->parse('<?php ' . $body);
168 2
    }
169
170
    /**
171
     * @param ClassMethod $method
172
     *
173
     * @return void
174
     */
175 2
    private function replaceExtract(ClassMethod $method)
176
    {
177 2
        $method->params = array(new Param('object'));
178
179
        $body = <<<EOT
180
\$ret = [];
181
foreach (\$this->extractCallbacks as \$callback) {
182
    \$callback->__invoke(\$object, \$ret);
183
}
184 2
return \$ret;
185
EOT;
186
187 2
        $method->stmts = (new ParserFactory())
0 ignored issues
show
Documentation Bug introduced by
It seems like (new \PhpParser\ParserFa...parse('<?php ' . $body) can be null. However, the property $stmts is declared as array. Maybe change the type of the property to array|null or add a type check?

Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.

To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.

function aContainsB(array $needle = null, array  $haystack) {
    if (!$needle) {
        return false;
    }

    return array_intersect($haystack, $needle) == $haystack;
}

The function can be called with either null or an array for the parameter $needle but will only accept an array as $haystack.

Loading history...
188 2
            ->create(ParserFactory::ONLY_PHP7)
189 2
            ->parse('<?php ' . $body);
190 2
    }
191
192
    /**
193
     * Finds or creates a class method (and eventually attaches it to the class itself)
194
     *
195
     * @param Class_ $class
196
     * @param string                    $name  name of the method
197
     *
198
     * @return ClassMethod
199
     */
200 2
    private function findOrCreateMethod(Class_ $class, string $name) : ClassMethod
201
    {
202 2
        $foundMethods = array_filter(
203 2
            $class->getMethods(),
204 2
            function (ClassMethod $method) use ($name) : bool {
205 2
                return $name === $method->name;
206 2
            }
207
        );
208
209 2
        $method = reset($foundMethods);
210
211 2
        if (!$method) {
212 2
            $class->stmts[] = $method = new ClassMethod($name);
213
        }
214
215 2
        return $method;
216
    }
217
}
218