Completed
Pull Request — master (#59)
by
unknown
05:04 queued 01:55
created

HydratorMethodsVisitor   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 197
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 97.59%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 22
c 4
b 0
f 0
lcom 1
cbo 9
dl 0
loc 197
ccs 81
cts 83
cp 0.9759
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 14 4
A leaveNode() 0 17 2
A recursiveFindNonStaticProperties() 0 17 4
B replaceConstructor() 0 31 4
A replaceHydrate() 0 22 3
A replaceExtract() 0 20 3
A findOrCreateMethod() 0 17 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[] = "\$object->" . $propertyName . " = \$data['" . $propertyName . "'];";
174
        }
175 2
        $index = 0;
176 2
        foreach ($this->hiddenPropertyMap as $className => $propertyNames) {
177 2
            $bodyParts[] = "\$this->hydrateCallbacks[" . ($index++) . "]->__invoke(\$object, \$data);";
178
        }
179
180 2
        $bodyParts[] = "return \$object;";
181
182 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...
183 2
            ->create(ParserFactory::ONLY_PHP7)
184 2
            ->parse('<?php ' . implode("\n", $bodyParts));
185 2
    }
186
187
    /**
188
     * @param ClassMethod $method
189
     *
190
     * @return void
191
     */
192 2
    private function replaceExtract(ClassMethod $method)
193
    {
194 2
        $method->params = array(new Param('object'));
195
196 2
        $bodyParts = array();
197 2
        $bodyParts[] = "\$ret = array();";
198 2
        foreach ($this->visiblePropertyMap as $propertyName) {
199 1
            $bodyParts[] = "\$ret['" . $propertyName . "'] = \$object->" . $propertyName . ";";
200
        }
201 2
        $index = 0;
202 2
        foreach ($this->hiddenPropertyMap as $className => $propertyNames) {
203 2
            $bodyParts[] = "\$this->extractCallbacks[" . ($index++) . "]->__invoke(\$object, \$ret);";
204
        }
205
206 2
        $bodyParts[] = "return \$ret;";
207
208 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...
209 2
            ->create(ParserFactory::ONLY_PHP7)
210 2
            ->parse('<?php ' . implode("\n", $bodyParts));
211 2
    }
212
213
    /**
214
     * Finds or creates a class method (and eventually attaches it to the class itself)
215
     *
216
     * @param Class_ $class
217
     * @param string                    $name  name of the method
218
     *
219
     * @return ClassMethod
220
     */
221 2
    private function findOrCreateMethod(Class_ $class, string $name) : ClassMethod
222
    {
223 2
        $foundMethods = array_filter(
224 2
            $class->getMethods(),
225 2
            function (ClassMethod $method) use ($name) : bool {
226 2
                return $name === $method->name;
227 2
            }
228
        );
229
230 2
        $method = reset($foundMethods);
231
232 2
        if (!$method) {
233 2
            $class->stmts[] = $method = new ClassMethod($name);
234
        }
235
236 2
        return $method;
237
    }
238
}
239