Completed
Pull Request — master (#1709)
by Andreas
16:45 queued 14:38
created

DefaultPersistentCollectionGenerator   C

Complexity

Total Complexity 55

Size/Duplication

Total Lines 333
Duplicated Lines 11.71 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 74.23%

Importance

Changes 0
Metric Value
wmc 55
c 0
b 0
f 0
lcom 1
cbo 1
dl 39
loc 333
ccs 98
cts 132
cp 0.7423
rs 6.8

10 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A generateClass() 0 7 1
C generateCollectionClass() 15 72 11
A generateMethod() 0 22 1
C buildParametersString() 0 35 7
B getParameterType() 0 24 6
A getParameterNamesForDecoratedCall() 0 19 3
A getMethodReturnType() 0 7 3
C formatType() 0 36 13
D loadClass() 24 39 9

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like DefaultPersistentCollectionGenerator often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use DefaultPersistentCollectionGenerator, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Doctrine\ODM\MongoDB\PersistentCollection;
4
5
use Doctrine\ODM\MongoDB\Configuration;
6
7
/**
8
 * Default generator for custom PersistentCollection classes.
9
 *
10
 * @since 1.1
11
 */
12
final class DefaultPersistentCollectionGenerator implements PersistentCollectionGenerator
13
{
14
    /**
15
     * The namespace that contains all persistent collection classes.
16
     *
17
     * @var string
18
     */
19
    private $collectionNamespace;
20
21
    /**
22
     * The directory that contains all persistent collection classes.
23
     *
24
     * @var string
25
     */
26
    private $collectionDir;
27
28
    /**
29
     * @param string $collectionDir
30
     * @param string $collectionNs
31
     */
32 11
    public function __construct($collectionDir, $collectionNs)
33
    {
34 11
        $this->collectionDir = $collectionDir;
35 11
        $this->collectionNamespace = $collectionNs;
36 11
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function generateClass($class, $dir)
42
    {
43
        $collClassName = str_replace('\\', '', $class) . 'Persistent';
44
        $className = $this->collectionNamespace . '\\' . $collClassName;
45
        $fileName = $dir . DIRECTORY_SEPARATOR . $collClassName . '.php';
46
        $this->generateCollectionClass($class, $className, $fileName);
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52 10
    public function loadClass($collectionClass, $autoGenerate)
53
    {
54
        // These checks are not in __construct() because of BC and should be moved for 2.0
55 10
        if ( ! $this->collectionDir) {
56
            throw PersistentCollectionException::directoryRequired();
57
        }
58 10
        if ( ! $this->collectionNamespace) {
59
            throw PersistentCollectionException::namespaceRequired();
60
        }
61
62 10
        $collClassName = str_replace('\\', '', $collectionClass) . 'Persistent';
63 10
        $className = $this->collectionNamespace . '\\' . $collClassName;
64 10 View Code Duplication
        if ( ! class_exists($className, false)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
65 6
            $fileName = $this->collectionDir . DIRECTORY_SEPARATOR . $collClassName . '.php';
66 6
            switch ($autoGenerate) {
67
                case Configuration::AUTOGENERATE_NEVER:
68
                    require $fileName;
69
                    break;
70
71
                case Configuration::AUTOGENERATE_ALWAYS:
72 3
                    $this->generateCollectionClass($collectionClass, $className, $fileName);
73 3
                    require $fileName;
74 3
                    break;
75
76
                case Configuration::AUTOGENERATE_FILE_NOT_EXISTS:
77
                    if ( ! file_exists($fileName)) {
78
                        $this->generateCollectionClass($collectionClass, $className, $fileName);
79
                    }
80
                    require $fileName;
81
                    break;
82
83
                case Configuration::AUTOGENERATE_EVAL:
84 3
                    $this->generateCollectionClass($collectionClass, $className, false);
85 3
                    break;
86
            }
87
        }
88
89 10
        return $className;
90
    }
91
92 6
    private function generateCollectionClass($for, $targetFqcn, $fileName)
93
    {
94 6
        $exploded = explode('\\', $targetFqcn);
95 6
        $class = array_pop($exploded);
96 6
        $namespace = join('\\', $exploded);
97
        $code = <<<CODE
98
<?php
99
100 6
namespace $namespace;
101
102
use Doctrine\Common\Collections\Collection as BaseCollection;
103
use Doctrine\ODM\MongoDB\DocumentManager;
104
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata;
105
use Doctrine\ODM\MongoDB\MongoDBException;
106
use Doctrine\ODM\MongoDB\UnitOfWork;
107
use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
108
109
/**
110
 * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE\'S PERSISTENT COLLECTION GENERATOR
111
 */
112 6
class $class extends \\$for implements \\Doctrine\\ODM\\MongoDB\\PersistentCollection\\PersistentCollectionInterface
113
{
114
    use \\Doctrine\\ODM\\MongoDB\\PersistentCollection\\PersistentCollectionTrait;
115
116
    /**
117
     * @param BaseCollection \$coll
118
     * @param DocumentManager \$dm
119
     * @param UnitOfWork \$uow
120
     */
121
    public function __construct(BaseCollection \$coll, DocumentManager \$dm, UnitOfWork \$uow)
122
    {
123
        \$this->coll = \$coll;
124
        \$this->dm = \$dm;
125
        \$this->uow = \$uow;
126
    }
127
128
CODE;
129 6
        $rc = new \ReflectionClass($for);
130 6
        $rt = new \ReflectionClass('Doctrine\\ODM\\MongoDB\\PersistentCollection\\PersistentCollectionTrait');
131 6
        foreach ($rc->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) {
132
            if (
133 6
                $rt->hasMethod($method->name) ||
134 6
                $method->isConstructor() ||
135 6
                $method->isFinal() ||
136 6
                $method->isStatic()
137
            ) {
138 6
                continue;
139
            }
140 6
            $code .= $this->generateMethod($method);
141
        }
142 6
        $code .= "}\n";
143
144 6
        if ($fileName === false) {
145 3
            if ( ! class_exists($targetFqcn)) {
146 3
                eval(substr($code, 5));
147
            }
148 View Code Duplication
        } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
149 3
            $parentDirectory = dirname($fileName);
150
151 3
            if ( ! is_dir($parentDirectory) && (false === @mkdir($parentDirectory, 0775, true))) {
152
                throw PersistentCollectionException::directoryNotWritable();
153
            }
154
155 3
            if ( ! is_writable($parentDirectory)) {
156
                throw PersistentCollectionException::directoryNotWritable();
157
            }
158
159 3
            $tmpFileName = $fileName . '.' . uniqid('', true);
160 3
            file_put_contents($tmpFileName, $code);
161 3
            rename($tmpFileName, $fileName);
162
        }
163 6
    }
164
165 6
    private function generateMethod(\ReflectionMethod $method)
166
    {
167 6
        $parametersString = $this->buildParametersString($method);
168 6
        $callParamsString = implode(', ', $this->getParameterNamesForDecoratedCall($method->getParameters()));
169
170
        $method = <<<CODE
171
172
    /**
173
     * {@inheritDoc}
174
     */
175 6
    public function {$method->name}($parametersString){$this->getMethodReturnType($method)}
176
    {
177
        \$this->initialize();
178
        if (\$this->needsSchedulingForDirtyCheck()) {
179
            \$this->changed();
180
        }
181 6
        return \$this->coll->{$method->name}($callParamsString);
182
    }
183
184
CODE;
185 6
        return $method;
186
    }
187
188
    /**
189
     * @param \ReflectionMethod $method
190
     *
191
     * @return string
192
     */
193 6
    private function buildParametersString(\ReflectionMethod $method)
194
    {
195 6
        $parameters = $method->getParameters();
196 6
        $parameterDefinitions = array();
197
198
        /* @var $param \ReflectionParameter */
199 6
        foreach ($parameters as $param) {
200 6
            $parameterDefinition = '';
201
202 6
            if ($parameterType = $this->getParameterType($param)) {
0 ignored issues
show
Bug introduced by
It seems like $param defined by $param on line 199 can also be of type string; however, Doctrine\ODM\MongoDB\Per...tor::getParameterType() does only seem to accept object<ReflectionParameter>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
203 6
                $parameterDefinition .= $parameterType . ' ';
204
            }
205
206 6
            if ($param->isPassedByReference()) {
207
                $parameterDefinition .= '&';
208
            }
209
210 6
            if (method_exists($param, 'isVariadic')) {
211 6
                if ($param->isVariadic()) {
212
                    $parameterDefinition .= '...';
213
                }
214
            }
215
216 6
            $parameters[]     = '$' . $param->name;
217 6
            $parameterDefinition .= '$' . $param->name;
218
219 6
            if ($param->isDefaultValueAvailable()) {
220
                $parameterDefinition .= ' = ' . var_export($param->getDefaultValue(), true);
221
            }
222
223 6
            $parameterDefinitions[] = $parameterDefinition;
224
        }
225
226 6
        return implode(', ', $parameterDefinitions);
227
    }
228
229
    /**
230
     * @param \ReflectionParameter $parameter
231
     *
232
     * @return string|null
233
     */
234 6
    private function getParameterType(\ReflectionParameter $parameter)
235
    {
236
        // We need to pick the type hint class too
237 6
        if ($parameter->isArray()) {
238
            return 'array';
239
        }
240
241 6
        if (method_exists($parameter, 'isCallable') && $parameter->isCallable()) {
242
            return 'callable';
243
        }
244
245
        try {
246 6
            $parameterClass = $parameter->getClass();
247
248 6
            if ($parameterClass) {
249 6
                return '\\' . $parameterClass->name;
250
            }
251
        } catch (\ReflectionException $previous) {
252
            // @todo ProxyGenerator throws specialized exceptions
253
            throw $previous;
254
        }
255
256 2
        return null;
257
    }
258
259
    /**
260
     * @param \ReflectionParameter[] $parameters
261
     *
262
     * @return string[]
263
     */
264 6
    private function getParameterNamesForDecoratedCall(array $parameters)
265
    {
266 6
        return array_map(
267 6
            function (\ReflectionParameter $parameter) {
268 6
                $name = '';
269
270 6
                if (method_exists($parameter, 'isVariadic')) {
271 6
                    if ($parameter->isVariadic()) {
272
                        $name .= '...';
273
                    }
274
                }
275
276 6
                $name .= '$' . $parameter->name;
277
278 6
                return $name;
279 6
            },
280 6
            $parameters
281
        );
282
    }
283
284
    /**
285
     * @param \ReflectionMethod $method
286
     *
287
     * @return string
288
     *
289
     * @see \Doctrine\Common\Proxy\ProxyGenerator::getMethodReturnType()
290
     */
291 6
    private function getMethodReturnType(\ReflectionMethod $method)
292
    {
293 6
        if ( ! method_exists($method, 'hasReturnType') || ! $method->hasReturnType()) {
294 6
            return '';
295
        }
296 2
        return ': ' . $this->formatType($method->getReturnType(), $method);
297
    }
298
299
    /**
300
     * @param \ReflectionType $type
301
     * @param \ReflectionMethod $method
302
     * @param \ReflectionParameter|null $parameter
303
     *
304
     * @return string
305
     *
306
     * @see \Doctrine\Common\Proxy\ProxyGenerator::formatType()
307
     */
308 2
    private function formatType(
309
        \ReflectionType $type,
310
        \ReflectionMethod $method,
311
        \ReflectionParameter $parameter = null
312
    ) {
313 2
        $name = method_exists($type, 'getName') ? $type->getName() : (string) $type;
314 2
        $nameLower = strtolower($name);
315 2
        if ('self' === $nameLower) {
316
            $name = $method->getDeclaringClass()->getName();
0 ignored issues
show
introduced by
Consider using $method->class. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
317
        }
318 2
        if ('parent' === $nameLower) {
319
            $name = $method->getDeclaringClass()->getParentClass()->getName();
320
        }
321 2
        if ( ! $type->isBuiltin() && ! class_exists($name) && ! interface_exists($name)) {
322
            if (null !== $parameter) {
323
                throw PersistentCollectionException::invalidParameterTypeHint(
324
                    $method->getDeclaringClass()->getName(),
0 ignored issues
show
introduced by
Consider using $method->class. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
325
                    $method->getName(),
0 ignored issues
show
Bug introduced by
Consider using $method->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
326
                    $parameter->getName()
0 ignored issues
show
Bug introduced by
Consider using $parameter->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
327
                );
328
            }
329
            throw PersistentCollectionException::invalidReturnTypeHint(
330
                $method->getDeclaringClass()->getName(),
0 ignored issues
show
introduced by
Consider using $method->class. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
331
                $method->getName()
0 ignored issues
show
Bug introduced by
Consider using $method->name. There is an issue with getName() and APC-enabled PHP versions.
Loading history...
332
            );
333
        }
334 2
        if ( ! $type->isBuiltin()) {
335 2
            $name = '\\' . $name;
336
        }
337 2
        if ($type->allowsNull()
338 2
            && (null === $parameter || ! $parameter->isDefaultValueAvailable() || null !== $parameter->getDefaultValue())
339
        ) {
340 1
            $name = '?' . $name;
341
        }
342 2
        return $name;
343
    }
344
}
345