Completed
Pull Request — master (#59)
by
unknown
36:10
created

HydratorMethodsVisitor   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 177
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Test Coverage

Coverage 97.06%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 16
c 1
b 0
f 0
lcom 1
cbo 9
dl 0
loc 177
ccs 66
cts 68
cp 0.9706
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 2
A leaveNode() 0 17 2
A recursiveFindNonStaticProperties() 0 17 4
B replaceConstructor() 0 29 4
A replaceHydrate() 0 18 1
A replaceExtract() 0 16 1
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 $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) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
126
127
            // Hydrate closures
128 2
            $bodyParts[] = "\$this->hydrateCallbacks[] = \\Closure::bind(function (\$object, \$values) {";
129 2
            foreach ($propertyNames as $propertyName) {
130 2
                $bodyParts[] = "    if (isset(\$values['" . $propertyName . "'])) {";
131 2
                $bodyParts[] = "        \$object->" . $propertyName . " = \$values['" . $propertyName . "'];";
132 2
                $bodyParts[] = "    }";
133
            }
134 2
            $bodyParts[] = '}, null, ' . var_export($className, true) . ');' . "\n";
135
136
            // Extract closures
137 2
            $bodyParts[] = "\$this->extractCallbacks[] = \\Closure::bind(function (\$object, &\$values) {";
138 2
            foreach ($propertyNames as $propertyName) {
139 2
                $bodyParts[] = "    \$values['" . $propertyName . "'] = \$object->" . $propertyName . ";";
140
            }
141 2
            $bodyParts[] = '}, null, ' . var_export($className, true) . ');' . "\n";
142
        }
143
144 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...
145 2
            ->create(ParserFactory::ONLY_PHP7)
146 2
            ->parse('<?php ' . implode("\n", $bodyParts));
147 2
    }
148
149
    /**
150
     * @param ClassMethod $method
151
     */
152 2
    private function replaceHydrate(ClassMethod $method)
153
    {
154 2
        $method->params = array(
155 2
            new Param('data', null, 'array'),
156 2
            new Param('object'),
157
        );
158
159
        $body = <<<EOT
160
foreach (\$this->hydrateCallbacks as \$callback) {
161
    \$callback->__invoke(\$object, \$data);
162
}
163 2
return \$object;
164
EOT;
165
166 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...
167 2
            ->create(ParserFactory::ONLY_PHP7)
168 2
            ->parse('<?php ' . $body);
169 2
    }
170
171
    /**
172
     * @param ClassMethod $method
173
     *
174
     * @return void
175
     */
176 2
    private function replaceExtract(ClassMethod $method)
177
    {
178 2
        $method->params = array(new Param('object'));
179
180
        $body = <<<EOT
181
\$ret = [];
182
foreach (\$this->extractCallbacks as \$callback) {
183
    \$callback->__invoke(\$object, \$ret);
184
}
185 2
return \$ret;
186
EOT;
187
188 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...
189 2
            ->create(ParserFactory::ONLY_PHP7)
190 2
            ->parse('<?php ' . $body);
191 2
    }
192
193
    /**
194
     * Finds or creates a class method (and eventually attaches it to the class itself)
195
     *
196
     * @param Class_ $class
197
     * @param string                    $name  name of the method
198
     *
199
     * @return ClassMethod
200
     */
201 2
    private function findOrCreateMethod(Class_ $class, string $name) : ClassMethod
202
    {
203 2
        $foundMethods = array_filter(
204 2
            $class->getMethods(),
205 2
            function (ClassMethod $method) use ($name) : bool {
206 2
                return $name === $method->name;
207 2
            }
208
        );
209
210 2
        $method = reset($foundMethods);
211
212 2
        if (!$method) {
213 2
            $class->stmts[] = $method = new ClassMethod($name);
214
        }
215
216 2
        return $method;
217
    }
218
}
219