Completed
Pull Request — master (#1385)
by Andreas
08:02
created

ClassMetadataFactory::doLoadMetadata()   C

Complexity

Conditions 13
Paths 111

Size

Total Lines 61
Code Lines 41

Duplication

Lines 4
Ratio 6.56 %

Code Coverage

Tests 38
CRAP Score 13.0211

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 4
loc 61
ccs 38
cts 40
cp 0.95
rs 5.9278
cc 13
eloc 41
nc 111
nop 4
crap 13.0211

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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. For more information, see
17
 * <http://www.doctrine-project.org>.
18
 */
19
20
namespace Doctrine\ODM\MongoDB\Mapping;
21
22
use Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory;
23
use Doctrine\Common\Persistence\Mapping\ClassMetadata as ClassMetadataInterface;
24
use Doctrine\Common\Persistence\Mapping\ReflectionService;
25
use Doctrine\ODM\MongoDB\Configuration;
26
use Doctrine\ODM\MongoDB\DocumentManager;
27
use Doctrine\ODM\MongoDB\Event\LoadClassMetadataEventArgs;
28
use Doctrine\ODM\MongoDB\Events;
29
use Doctrine\ODM\MongoDB\Id\AbstractIdGenerator;
30
use Doctrine\ODM\MongoDB\Id\AlnumGenerator;
31
use Doctrine\ODM\MongoDB\Id\AutoGenerator;
32
use Doctrine\ODM\MongoDB\Id\IncrementGenerator;
33
use Doctrine\ODM\MongoDB\Id\UuidGenerator;
34
35
/**
36
 * The ClassMetadataFactory is used to create ClassMetadata objects that contain all the
37
 * metadata mapping informations of a class which describes how a class should be mapped
38
 * to a document database.
39
 *
40
 * @since       1.0
41
 */
42
class ClassMetadataFactory extends AbstractClassMetadataFactory
43
{
44
    protected $cacheSalt = "\$MONGODBODMCLASSMETADATA";
45
46
    /** @var DocumentManager The DocumentManager instance */
47
    private $dm;
48
49
    /** @var Configuration The Configuration instance */
50
    private $config;
51
52
    /** @var \Doctrine\Common\Persistence\Mapping\Driver\MappingDriver The used metadata driver. */
53
    private $driver;
54
55
    /** @var \Doctrine\Common\EventManager The event manager instance */
56
    private $evm;
57
58
    /**
59
     * Sets the DocumentManager instance for this class.
60
     *
61
     * @param DocumentManager $dm The DocumentManager instance
62
     */
63 1042
    public function setDocumentManager(DocumentManager $dm)
64
    {
65 1042
        $this->dm = $dm;
66 1042
    }
67
68
    /**
69
     * Sets the Configuration instance
70
     *
71
     * @param Configuration $config
72
     */
73 1042
    public function setConfiguration(Configuration $config)
74
    {
75 1042
        $this->config = $config;
76 1042
    }
77
78
    /**
79
     * Lazy initialization of this stuff, especially the metadata driver,
80
     * since these are not needed at all when a metadata cache is active.
81
     */
82 839
    protected function initialize()
83
    {
84 839
        $this->driver = $this->config->getMetadataDriverImpl();
85 839
        $this->evm = $this->dm->getEventManager();
86 839
        $this->initialized = true;
87 839
    }
88
89
    /**
90
     * {@inheritDoc}
91
     */
92
    protected function getFqcnFromAlias($namespaceAlias, $simpleClassName)
93
    {
94
        return $this->config->getDocumentNamespace($namespaceAlias) . '\\' . $simpleClassName;
95
    }
96
97
    /**
98
     * {@inheritDoc}
99
     */
100 349
    protected function getDriver()
101
    {
102 349
        return $this->driver;
103
    }
104
105
    /**
106
     * {@inheritDoc}
107
     */
108 824
    protected function wakeupReflection(ClassMetadataInterface $class, ReflectionService $reflService)
109
    {
110 824
    }
111
112
    /**
113
     * {@inheritDoc}
114
     */
115 839
    protected function initializeReflection(ClassMetadataInterface $class, ReflectionService $reflService)
116
    {
117 839
    }
118
119
    /**
120
     * {@inheritDoc}
121
     */
122 824
    protected function isEntity(ClassMetadataInterface $class)
123
    {
124 824
        return ! $class->isMappedSuperclass && ! $class->isEmbeddedDocument;
0 ignored issues
show
Bug introduced by
Accessing isMappedSuperclass on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
Bug introduced by
Accessing isEmbeddedDocument on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
125
    }
126
127
    /**
128
     * {@inheritDoc}
129
     */
130 839
    protected function doLoadMetadata($class, $parent, $rootEntityFound, array $nonSuperclassParents = array())
131
    {
132
        /** @var $class ClassMetadata */
133
        /** @var $parent ClassMetadata */
134 839
        if ($parent) {
135 346
            $class->setInheritanceType($parent->inheritanceType);
136 346
            $class->setDiscriminatorField($parent->discriminatorField);
137 346
            $class->setDiscriminatorMap($parent->discriminatorMap);
138 346
            $class->setDefaultDiscriminatorValue($parent->defaultDiscriminatorValue);
139 346
            $class->setIdGeneratorType($parent->generatorType);
140 346
            $this->addInheritedFields($class, $parent);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...\Mapping\ClassMetadata>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
141 346
            $this->addInheritedRelations($class, $parent);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...\Mapping\ClassMetadata>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
142 346
            $this->addInheritedIndexes($class, $parent);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...\Mapping\ClassMetadata>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
143 346
            $this->setInheritedShardKey($class, $parent);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...\Mapping\ClassMetadata>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
144 346
            $class->setIdentifier($parent->identifier);
145 346
            $class->setVersioned($parent->isVersioned);
146 346
            $class->setVersionField($parent->versionField);
147 346
            $class->setLifecycleCallbacks($parent->lifecycleCallbacks);
148 346
            $class->setAlsoLoadMethods($parent->alsoLoadMethods);
149 346
            $class->setChangeTrackingPolicy($parent->changeTrackingPolicy);
150 346
            $class->setFile($parent->getFile());
151 346
            if ($parent->isMappedSuperclass) {
152 284
                $class->setCustomRepositoryClass($parent->customRepositoryClassName);
153
            }
154
        }
155
156
        // Invoke driver
157
        try {
158 839
            $this->driver->loadMetadataForClass($class->getName(), $class);
159 68
        } catch (\ReflectionException $e) {
160
            throw MappingException::reflectionFailure($class->getName(), $e);
161
        }
162
163 824
        $this->validateIdentifier($class);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...\Mapping\ClassMetadata>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
164
165 824
        if ($parent && $rootEntityFound && $parent->generatorType === $class->generatorType) {
0 ignored issues
show
Bug introduced by
Accessing generatorType on the interface Doctrine\Common\Persistence\Mapping\ClassMetadata suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
166 108
            if ($parent->generatorType) {
167 108
                $class->setIdGeneratorType($parent->generatorType);
168
            }
169 108
            if ($parent->generatorOptions) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $parent->generatorOptions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
170
                $class->setIdGeneratorOptions($parent->generatorOptions);
171
            }
172 108
            if ($parent->idGenerator) {
173 108
                $class->setIdGenerator($parent->idGenerator);
174
            }
175
        } else {
176 824
            $this->completeIdGeneratorMapping($class);
0 ignored issues
show
Compatibility introduced by
$class of type object<Doctrine\Common\P...\Mapping\ClassMetadata> is not a sub-type of object<Doctrine\ODM\Mong...ping\ClassMetadataInfo>. It seems like you assume a concrete implementation of the interface Doctrine\Common\Persistence\Mapping\ClassMetadata to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
177
        }
178
179 824
        if ($parent && $parent->isInheritanceTypeSingleCollection()) {
180 93
            $class->setDatabase($parent->getDatabase());
181 93
            $class->setCollection($parent->getCollection());
182
        }
183
184 824
        $class->setParentClasses($nonSuperclassParents);
185
186 824 View Code Duplication
        if ($this->evm->hasListeners(Events::loadClassMetadata)) {
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...
187 2
            $eventArgs = new LoadClassMetadataEventArgs($class, $this->dm);
188 2
            $this->evm->dispatchEvent(Events::loadClassMetadata, $eventArgs);
189
        }
190 824
    }
191
192
    /**
193
     * Validates the identifier mapping.
194
     *
195
     * @param ClassMetadata $class
196
     * @throws MappingException
197
     */
198 824
    protected function validateIdentifier($class)
199
    {
200 824
        if ( ! $class->identifier && ! $class->isMappedSuperclass && ! $class->isEmbeddedDocument) {
201
            throw MappingException::identifierRequired($class->name);
202
        }
203 824
    }
204
205
    /**
206
     * Creates a new ClassMetadata instance for the given class name.
207
     *
208
     * @param string $className
209
     * @return \Doctrine\ODM\MongoDB\Mapping\ClassMetadata
210
     */
211 839
    protected function newClassMetadataInstance($className)
212
    {
213 839
        return new ClassMetadata($className);
214
    }
215
216 824
    private function completeIdGeneratorMapping(ClassMetadataInfo $class)
217
    {
218 824
        $idGenOptions = $class->generatorOptions;
219 824
        switch ($class->generatorType) {
220 824
            case ClassMetadata::GENERATOR_TYPE_AUTO:
221 759
                $class->setIdGenerator(new AutoGenerator());
222 759
                break;
223 152
            case ClassMetadata::GENERATOR_TYPE_INCREMENT:
224 6
                $incrementGenerator = new IncrementGenerator();
225 6
                if (isset($idGenOptions['key'])) {
226
                    $incrementGenerator->setKey($idGenOptions['key']);
227
                }
228 6
                if (isset($idGenOptions['collection'])) {
229
                    $incrementGenerator->setCollection($idGenOptions['collection']);
230
                }
231 6
                $class->setIdGenerator($incrementGenerator);
232 6
                break;
233 146
            case ClassMetadata::GENERATOR_TYPE_UUID:
234 4
                $uuidGenerator = new UuidGenerator();
235 4
                isset($idGenOptions['salt']) && $uuidGenerator->setSalt($idGenOptions['salt']);
236 4
                $class->setIdGenerator($uuidGenerator);
237 4
                break;
238 142
            case ClassMetadata::GENERATOR_TYPE_ALNUM:
239 1
                $alnumGenerator = new AlnumGenerator();
240 1
                if (isset($idGenOptions['pad'])) {
241
                    $alnumGenerator->setPad($idGenOptions['pad']);
242
                }
243 1
                if (isset($idGenOptions['chars'])) {
244 1
                    $alnumGenerator->setChars($idGenOptions['chars']);
245
                } elseif (isset($idGenOptions['awkwardSafe'])) {
246
                    $alnumGenerator->setAwkwardSafeMode($idGenOptions['awkwardSafe']);
247
                }
248
249 1
                $class->setIdGenerator($alnumGenerator);
250 1
                break;
251 141
            case ClassMetadata::GENERATOR_TYPE_CUSTOM:
252
                if (empty($idGenOptions['class'])) {
253
                    throw MappingException::missingIdGeneratorClass($class->name);
254
                }
255
256
                $customGenerator = new $idGenOptions['class'];
257
                unset($idGenOptions['class']);
258
                if ( ! $customGenerator instanceof AbstractIdGenerator) {
259
                    throw MappingException::classIsNotAValidGenerator(get_class($customGenerator));
260
                }
261
262
                $methods = get_class_methods($customGenerator);
263
                foreach ($idGenOptions as $name => $value) {
264
                    $method = 'set' . ucfirst($name);
265
                    if ( ! in_array($method, $methods)) {
266
                        throw MappingException::missingGeneratorSetter(get_class($customGenerator), $name);
267
                    }
268
269
                    $customGenerator->$method($value);
270
                }
271
                $class->setIdGenerator($customGenerator);
272
                break;
273 141
            case ClassMetadata::GENERATOR_TYPE_NONE;
274 141
                break;
275
            default:
276
                throw new MappingException('Unknown generator type: ' . $class->generatorType);
277
        }
278 824
    }
279
280
    /**
281
     * Adds inherited fields to the subclass mapping.
282
     *
283
     * @param ClassMetadata $subClass
284
     * @param ClassMetadata $parentClass
285
     */
286 346
    private function addInheritedFields(ClassMetadata $subClass, ClassMetadata $parentClass)
287
    {
288 346
        foreach ($parentClass->fieldMappings as $fieldName => $mapping) {
289 125 View Code Duplication
            if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) {
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...
290 120
                $mapping['inherited'] = $parentClass->name;
291
            }
292 125
            if ( ! isset($mapping['declared'])) {
293 125
                $mapping['declared'] = $parentClass->name;
294
            }
295 125
            $subClass->addInheritedFieldMapping($mapping);
296
        }
297 346
        foreach ($parentClass->reflFields as $name => $field) {
298 125
            $subClass->reflFields[$name] = $field;
299
        }
300 346
    }
301
302
303
    /**
304
     * Adds inherited association mappings to the subclass mapping.
305
     *
306
     * @param \Doctrine\ODM\MongoDB\Mapping\ClassMetadata $subClass
307
     * @param \Doctrine\ODM\MongoDB\Mapping\ClassMetadata $parentClass
308
     *
309
     * @return void
310
     *
311
     * @throws MappingException
312
     */
313 346
    private function addInheritedRelations(ClassMetadata $subClass, ClassMetadata $parentClass)
314
    {
315 346
        foreach ($parentClass->associationMappings as $field => $mapping) {
316 82
            if ($parentClass->isMappedSuperclass) {
317 3
                $mapping['sourceDocument'] = $subClass->name;
318
            }
319
320 82 View Code Duplication
            if ( ! isset($mapping['inherited']) && ! $parentClass->isMappedSuperclass) {
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...
321 79
                $mapping['inherited'] = $parentClass->name;
322
            }
323 82
            if ( ! isset($mapping['declared'])) {
324 82
                $mapping['declared'] = $parentClass->name;
325
            }
326 82
            $subClass->addInheritedAssociationMapping($mapping);
327
        }
328 346
    }
329
330
    /**
331
     * Adds inherited indexes to the subclass mapping.
332
     *
333
     * @param ClassMetadata $subClass
334
     * @param ClassMetadata $parentClass
335
     */
336 346
    private function addInheritedIndexes(ClassMetadata $subClass, ClassMetadata $parentClass)
337
    {
338 346
        foreach ($parentClass->indexes as $index) {
339 2
            $subClass->addIndex($index['keys'], $index['options']);
340
        }
341 346
    }
342
343
    /**
344
     * Adds inherited shard key to the subclass mapping.
345
     *
346
     * @param ClassMetadata $subClass
347
     * @param ClassMetadata $parentClass
348
     */
349 346
    private function setInheritedShardKey(ClassMetadata $subClass, ClassMetadata $parentClass)
350
    {
351 346
        if ($parentClass->isSharded()) {
352 4
            $subClass->setShardKey(
353 4
                $parentClass->shardKey['keys'],
354 4
                $parentClass->shardKey['options']
355
            );
356
        }
357 346
    }
358
}
359