Completed
Pull Request — master (#59)
by
unknown
04:53
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 $visiblePropertyMap = array();
53
54
    /**
55
     * @var string[][]
56
     */
57
    private $hiddenPropertyMap = array();
58
59
    /**
60
     * @param ReflectionClass $reflectedClass
61
     */
62 2
    public function __construct(ReflectionClass $reflectedClass)
63
    {
64 2
        $this->reflectedClass = $reflectedClass;
65
66 2
        foreach ($this->recursiveFindNonStaticProperties($reflectedClass) as $property) {
67 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...
68
69 2
            if ($property->isPrivate() || $property->isProtected()) {
70 2
                $this->hiddenPropertyMap[$className][] = $property->getName();
71
            } else {
72 2
                $this->visiblePropertyMap[] = $property->getName();
73
            }
74
        }
75 2
    }
76
77
    /**
78
     * @param Node $node
79
     *
80
     * @return null|Class_
81
     */
82 2
    public function leaveNode(Node $node)
83
    {
84 2
        if (!$node instanceof Class_) {
85
            return null;
86
        }
87
88 2
        $node->stmts[] = new Property(Class_::MODIFIER_PRIVATE, array(
89 2
            new PropertyProperty('hydrateCallbacks', new Array_()),
90 2
            new PropertyProperty('extractCallbacks', new Array_()),
91
        ));
92
93 2
        $this->replaceConstructor($this->findOrCreateMethod($node, '__construct'));
94 2
        $this->replaceHydrate($this->findOrCreateMethod($node, 'hydrate'));
95 2
        $this->replaceExtract($this->findOrCreateMethod($node, 'extract'));
96
97 2
        return $node;
98
    }
99
100
    /**
101
     * Find all class properties recursively using class hierarchy without
102
     * removing name redefinitions
103
     *
104
     * @param \ReflectionClass $class
105
     *
106
     * @return \ReflectionProperty[]
107
     */
108 2
    private function recursiveFindNonStaticProperties(\ReflectionClass $class)
109
    {
110 2
        $ret = [];
111
112 2
        if ($parentClass = $class->getParentClass()) {
113
            $ret = $this->recursiveFindNonStaticProperties($parentClass);
114
        }
115
116
        // We cannot filter with NOT static
117 2
        foreach ($class->getProperties() as $property) {
118 2
            if (!$property->isStatic()) {
119 2
                $ret[] = $property;
120
            }
121
        }
122
123 2
        return $ret;
124
    }
125
126
    /**
127
     * @param ClassMethod $method
128
     */
129 2
    private function replaceConstructor(ClassMethod $method)
130
    {
131 2
        $method->params = array();
132
133 2
        $bodyParts = array();
134
135
        // Create a set of closures that will be called to hydrate the object.
136
        // Array of closures in a naturally indexed array, ordered, which will
137
        // then be called in order in the hydrate() and extract() methods.
138 2
        foreach ($this->hiddenPropertyMap as $className => $propertyNames) {
139
            // Hydrate closures
140 2
            $bodyParts[] = "\$this->hydrateCallbacks[] = \\Closure::bind(function (\$object, \$values) {";
141 2
            foreach ($propertyNames as $propertyName) {
142 2
                $bodyParts[] = "    if (isset(\$values['" . $propertyName . "'])) {";
143 2
                $bodyParts[] = "        \$object->" . $propertyName . " = \$values['" . $propertyName . "'];";
144 2
                $bodyParts[] = "    }";
145
            }
146 2
            $bodyParts[] = '}, null, ' . var_export($className, true) . ');' . "\n";
147
148
            // Extract closures
149 2
            $bodyParts[] = "\$this->extractCallbacks[] = \\Closure::bind(function (\$object, &\$values) {";
150 2
            foreach ($propertyNames as $propertyName) {
151 2
                $bodyParts[] = "    \$values['" . $propertyName . "'] = \$object->" . $propertyName . ";";
152
            }
153 2
            $bodyParts[] = '}, null, ' . var_export($className, true) . ');' . "\n";
154
        }
155
156 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...
157 2
            ->create(ParserFactory::ONLY_PHP7)
158 2
            ->parse('<?php ' . implode("\n", $bodyParts));
159 2
    }
160
161
    /**
162
     * @param ClassMethod $method
163
     */
164 2
    private function replaceHydrate(ClassMethod $method)
165
    {
166 2
        $method->params = array(
167 2
            new Param('data', null, 'array'),
168 2
            new Param('object'),
169
        );
170
171 2
        $bodyParts = array();
172 2
        foreach ($this->visiblePropertyMap as $propertyName) {
173 1
            $bodyParts[] = "if (isset(\$data['" . $propertyName . "'])) {";
174 1
            $bodyParts[] = "    \$object->" . $propertyName . " = \$data['" . $propertyName . "'];";
175 1
            $bodyParts[] = "}";
176
        }
177 2
        $index = 0;
178 2
        foreach ($this->hiddenPropertyMap as $className => $propertyNames) {
179 2
            $bodyParts[] = "\$this->hydrateCallbacks[" . ($index++) . "]->__invoke(\$object, \$data);";
180
        }
181
182 2
        $bodyParts[] = "return \$object;";
183
184 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...
185 2
            ->create(ParserFactory::ONLY_PHP7)
186 2
            ->parse('<?php ' . implode("\n", $bodyParts));
187 2
    }
188
189
    /**
190
     * @param ClassMethod $method
191
     *
192
     * @return void
193
     */
194 2
    private function replaceExtract(ClassMethod $method)
195
    {
196 2
        $method->params = array(new Param('object'));
197
198 2
        $bodyParts = array();
199 2
        $bodyParts[] = "\$ret = array();";
200 2
        foreach ($this->visiblePropertyMap as $propertyName) {
201 1
            $bodyParts[] = "\$ret['" . $propertyName . "'] = \$object->" . $propertyName . ";";
202
        }
203 2
        $index = 0;
204 2
        foreach ($this->hiddenPropertyMap as $className => $propertyNames) {
205 2
            $bodyParts[] = "\$this->extractCallbacks[" . ($index++) . "]->__invoke(\$object, \$ret);";
206
        }
207
208 2
        $bodyParts[] = "return \$ret;";
209
210 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...
211 2
            ->create(ParserFactory::ONLY_PHP7)
212 2
            ->parse('<?php ' . implode("\n", $bodyParts));
213 2
    }
214
215
    /**
216
     * Finds or creates a class method (and eventually attaches it to the class itself)
217
     *
218
     * @param Class_ $class
219
     * @param string                    $name  name of the method
220
     *
221
     * @return ClassMethod
222
     */
223 2
    private function findOrCreateMethod(Class_ $class, string $name) : ClassMethod
224
    {
225 2
        $foundMethods = array_filter(
226 2
            $class->getMethods(),
227 2
            function (ClassMethod $method) use ($name) : bool {
228 2
                return $name === $method->name;
229 2
            }
230
        );
231
232 2
        $method = reset($foundMethods);
233
234 2
        if (!$method) {
235 2
            $class->stmts[] = $method = new ClassMethod($name);
236
        }
237
238 2
        return $method;
239
    }
240
}
241