Completed
Pull Request — master (#59)
by
unknown
04:19
created

HydratorMethodsVisitor::replaceExtract()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 3

Importance

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