Completed
Pull Request — master (#1620)
by Maciej
09:05
created

YamlDriver   D

Complexity

Total Complexity 111

Size/Duplication

Total Lines 353
Duplicated Lines 15.86 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 88.56%

Importance

Changes 0
Metric Value
wmc 111
lcom 1
cbo 4
dl 56
loc 353
ccs 178
cts 201
cp 0.8856
rs 4.8717
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
F loadMetadataForClass() 32 125 48
F addFieldMapping() 24 78 21
F addMappingFromEmbed() 0 25 9
F addMappingFromReference() 0 41 21
B parseDiscriminatorField() 0 20 5
A loadMappingFile() 0 10 2
A setShardKey() 0 17 4

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 YamlDriver 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 YamlDriver, and based on these observations, apply Extract Interface, too.

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\Driver;
21
22
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
23
use Doctrine\Common\Persistence\Mapping\Driver\FileDriver;
24
use Doctrine\ODM\MongoDB\Mapping\ClassMetadata as MappingClassMetadata;
25
use Doctrine\ODM\MongoDB\Utility\CollectionHelper;
26
use Doctrine\ODM\MongoDB\Mapping\ClassMetadataInfo;
27
use Symfony\Component\Yaml\Yaml;
28
use Symfony\Component\Yaml\Exception\ParseException;
29
30
/**
31
 * The YamlDriver reads the mapping metadata from yaml schema files.
32
 *
33
 * @since       1.0
34
 */
35
class YamlDriver extends FileDriver
36
{
37
    const DEFAULT_FILE_EXTENSION = '.dcm.yml';
38
39
    /**
40
     * {@inheritDoc}
41
     */
42 14
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
43
    {
44 14
        parent::__construct($locator, $fileExtension);
45 14
    }
46
47
    /**
48
     * {@inheritDoc}
49
     */
50 10
    public function loadMetadataForClass($className, ClassMetadata $class)
51
    {
52
        /* @var $class ClassMetadataInfo */
53 10
        $element = $this->getElement($className);
54 10
        if ( ! $element) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $element 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...
55
            return;
56
        }
57 10
        $element['type'] = isset($element['type']) ? $element['type'] : 'document';
58
59 10
        if (isset($element['db'])) {
60 3
            $class->setDatabase($element['db']);
61
        }
62 10
        if (isset($element['collection'])) {
63 10
            $class->setCollection($element['collection']);
64
        }
65 10
        if (isset($element['readPreference'])) {
66 2
            if (! isset($element['readPreference']['mode'])) {
67
                throw new \InvalidArgumentException('"mode" is a required key for the readPreference setting.');
68
            }
69 2
            $class->setReadPreference(
70 2
                $element['readPreference']['mode'],
71 2
                isset($element['readPreference']['tagSets']) ? $element['readPreference']['tagSets'] : null
72
            );
73
        }
74 10
        if (isset($element['writeConcern'])) {
75 2
            $class->setWriteConcern($element['writeConcern']);
76
        }
77 10
        if ($element['type'] == 'document') {
78 10
            if (isset($element['repositoryClass'])) {
79 10
                $class->setCustomRepositoryClass($element['repositoryClass']);
80
            }
81 1 View Code Duplication
        } elseif ($element['type'] === 'mappedSuperclass') {
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...
82
            $class->setCustomRepositoryClass(
83
                isset($element['repositoryClass']) ? $element['repositoryClass'] : null
84
            );
85
            $class->isMappedSuperclass = true;
86 1
        } elseif ($element['type'] === 'embeddedDocument') {
87 1
            $class->isEmbeddedDocument = true;
88 1
        } elseif ($element['type'] === 'queryResultDocument') {
89 1
            $class->isQueryResultDocument = true;
90
        }
91 10
        if (isset($element['indexes'])) {
92 3
            foreach($element['indexes'] as $index) {
93 3
                $class->addIndex($index['keys'], isset($index['options']) ? $index['options'] : array());
94
            }
95
        }
96 10
        if (isset($element['shardKey'])) {
97 2
            $this->setShardKey($class, $element['shardKey']);
98
        }
99 10 View Code Duplication
        if (isset($element['inheritanceType'])) {
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...
100
            $class->setInheritanceType(constant(MappingClassMetadata::class . '::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType'])));
101
        }
102 10
        if (isset($element['discriminatorField'])) {
103 2
            $class->setDiscriminatorField($this->parseDiscriminatorField($element['discriminatorField']));
104
        }
105 10
        if (isset($element['discriminatorMap'])) {
106 2
            $class->setDiscriminatorMap($element['discriminatorMap']);
107
        }
108 10
        if (isset($element['defaultDiscriminatorValue'])) {
109 2
            $class->setDefaultDiscriminatorValue($element['defaultDiscriminatorValue']);
110
        }
111 10 View Code Duplication
        if (isset($element['changeTrackingPolicy'])) {
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...
112
            $class->setChangeTrackingPolicy(constant(MappingClassMetadata::class . '::CHANGETRACKING_' . strtoupper($element['changeTrackingPolicy'])));
113
        }
114 10
        if (isset($element['requireIndexes'])) {
115
            $class->setRequireIndexes($element['requireIndexes']);
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\ODM\MongoDB\Map...fo::setRequireIndexes() has been deprecated with message: method was deprecated in 1.2 and will be removed in 2.0

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
116
        }
117 10
        if (isset($element['slaveOkay'])) {
118
            $class->setSlaveOkay($element['slaveOkay']);
0 ignored issues
show
Deprecated Code introduced by
The method Doctrine\ODM\MongoDB\Map...ataInfo::setSlaveOkay() has been deprecated with message: in version 1.2 and will be removed in 2.0.

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
119
        }
120 10
        if (! empty($element['readOnly'])) {
121 2
            $class->markReadOnly();
122
        }
123 10
        if (isset($element['fields'])) {
124 10
            foreach ($element['fields'] as $fieldName => $mapping) {
125 10
                if (is_string($mapping)) {
126 1
                    $type = $mapping;
127 1
                    $mapping = array();
128 1
                    $mapping['type'] = $type;
129
                }
130 10
                if ( ! isset($mapping['fieldName'])) {
131 8
                    $mapping['fieldName'] = $fieldName;
132
                }
133 10
                if (isset($mapping['type']) && ! empty($mapping['embedded'])) {
134 2
                    $this->addMappingFromEmbed($class, $fieldName, $mapping, $mapping['type']);
135 10
                } elseif (isset($mapping['type']) && ! empty($mapping['reference'])) {
136 2
                    $this->addMappingFromReference($class, $fieldName, $mapping, $mapping['type']);
137
                } else {
138 10
                    $this->addFieldMapping($class, $mapping);
139
                }
140
            }
141
        }
142 10 View Code Duplication
        if (isset($element['embedOne'])) {
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...
143 3
            foreach ($element['embedOne'] as $fieldName => $embed) {
144 3
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'one');
145
            }
146
        }
147 10 View Code Duplication
        if (isset($element['embedMany'])) {
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...
148 3
            foreach ($element['embedMany'] as $fieldName => $embed) {
149 3
                $this->addMappingFromEmbed($class, $fieldName, $embed, 'many');
150
            }
151
        }
152 10 View Code Duplication
        if (isset($element['referenceOne'])) {
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...
153 3
            foreach ($element['referenceOne'] as $fieldName => $reference) {
154 3
                $this->addMappingFromReference($class, $fieldName, $reference, 'one');
155
            }
156
        }
157 10 View Code Duplication
        if (isset($element['referenceMany'])) {
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...
158 4
            foreach ($element['referenceMany'] as $fieldName => $reference) {
159 4
                $this->addMappingFromReference($class, $fieldName, $reference, 'many');
160
            }
161
        }
162 10
        if (isset($element['lifecycleCallbacks'])) {
163 3
            foreach ($element['lifecycleCallbacks'] as $type => $methods) {
164 3
                foreach ($methods as $method) {
165 3
                    $class->addLifecycleCallback($method, constant('Doctrine\ODM\MongoDB\Events::' . $type));
166
                }
167
            }
168
        }
169 10
        if (isset($element['alsoLoadMethods'])) {
170 1
            foreach ($element['alsoLoadMethods'] as $methodName => $fieldName) {
171 1
                $class->registerAlsoLoadMethod($methodName, $fieldName);
172
            }
173
        }
174 10
    }
175
176 10
    private function addFieldMapping(ClassMetadataInfo $class, $mapping)
177
    {
178 10 View Code Duplication
        if (isset($mapping['name'])) {
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...
179 2
            $name = $mapping['name'];
180 10
        } elseif (isset($mapping['fieldName'])) {
181 10
            $name = $mapping['fieldName'];
182
        } else {
183
            throw new \InvalidArgumentException('Cannot infer a MongoDB name from the mapping');
184
        }
185
186 10
        $class->mapField($mapping);
187
188 10 View Code Duplication
        if ( ! (isset($mapping['index']) || isset($mapping['unique']) || isset($mapping['sparse']))) {
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...
189 10
            return;
190
        }
191
192
        // Multiple index specifications in one field mapping is ambiguous
193 5
        if ((isset($mapping['index']) && is_array($mapping['index'])) +
194 5
            (isset($mapping['unique']) && is_array($mapping['unique'])) +
195 5
            (isset($mapping['sparse']) && is_array($mapping['sparse'])) > 1) {
196
            throw new \InvalidArgumentException('Multiple index specifications found among index, unique, and/or sparse fields');
197
        }
198
199
        // Index this field if either "index", "unique", or "sparse" are set
200 5
        $keys = array($name => 'asc');
201
202
        /* The "order" option is only used in the index specification and should
203
         * not be passed along as an index option.
204
         */
205 5
        if (isset($mapping['index']['order'])) {
206 2
            $keys[$name] = $mapping['index']['order'];
207 2
            unset($mapping['index']['order']);
208 5
        } elseif (isset($mapping['unique']['order'])) {
209 2
            $keys[$name] = $mapping['unique']['order'];
210 2
            unset($mapping['unique']['order']);
211 3
        } elseif (isset($mapping['sparse']['order'])) {
212
            $keys[$name] = $mapping['sparse']['order'];
213
            unset($mapping['sparse']['order']);
214
        }
215
216
        /* Initialize $options from any array value among index, unique, and
217
         * sparse. Any boolean values for unique or sparse should be merged into
218
         * the options afterwards to ensure consistent parsing.
219
         */
220 5
        $options = array();
221 5
        $unique = null;
222 5
        $sparse = null;
223
224 5
        if (isset($mapping['index']) && is_array($mapping['index'])) {
225 2
            $options = $mapping['index'];
226
        }
227
228 5 View Code Duplication
        if (isset($mapping['unique'])) {
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...
229 5
            if (is_array($mapping['unique'])) {
230 2
                $options = $mapping['unique'] + array('unique' => true);
231
            } else {
232 3
                $unique = (boolean) $mapping['unique'];
233
            }
234
        }
235
236 5 View Code Duplication
        if (isset($mapping['sparse'])) {
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...
237 3
            if (is_array($mapping['sparse'])) {
238
                $options = $mapping['sparse'] + array('sparse' => true);
239
            } else {
240 3
                $sparse = (boolean) $mapping['sparse'];
241
            }
242
        }
243
244 5
        if (isset($unique)) {
245 3
            $options['unique'] = $unique;
246
        }
247
248 5
        if (isset($sparse)) {
249 3
            $options['sparse'] = $sparse;
250
        }
251
252 5
        $class->addIndex($keys, $options);
253 5
    }
254
255 5
    private function addMappingFromEmbed(ClassMetadataInfo $class, $fieldName, $embed, $type)
256
    {
257 5
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
258
        $mapping = array(
259 5
            'type'            => $type,
260
            'embedded'        => true,
261 5
            'targetDocument'  => isset($embed['targetDocument']) ? $embed['targetDocument'] : null,
262 5
            'collectionClass' => isset($embed['collectionClass']) ? $embed['collectionClass'] : null,
263 5
            'fieldName'       => $fieldName,
264 5
            'strategy'        => isset($embed['strategy']) ? (string) $embed['strategy'] : $defaultStrategy,
265
        );
266 5
        if (isset($embed['name'])) {
267 2
            $mapping['name'] = $embed['name'];
268
        }
269 5
        if (isset($embed['discriminatorField'])) {
270 2
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($embed['discriminatorField']);
271
        }
272 5
        if (isset($embed['discriminatorMap'])) {
273 2
            $mapping['discriminatorMap'] = $embed['discriminatorMap'];
274
        }
275 5
        if (isset($embed['defaultDiscriminatorValue'])) {
276 2
            $mapping['defaultDiscriminatorValue'] = $embed['defaultDiscriminatorValue'];
277
        }
278 5
        $this->addFieldMapping($class, $mapping);
279 5
    }
280
281 6
    private function addMappingFromReference(ClassMetadataInfo $class, $fieldName, $reference, $type)
282
    {
283 6
        $defaultStrategy = $type == 'one' ? ClassMetadataInfo::STORAGE_STRATEGY_SET : CollectionHelper::DEFAULT_STRATEGY;
284
        $mapping = array(
285 6
            'cascade'          => isset($reference['cascade']) ? $reference['cascade'] : [],
286 6
            'orphanRemoval'    => isset($reference['orphanRemoval']) ? $reference['orphanRemoval'] : false,
287 6
            'type'             => $type,
288
            'reference'        => true,
289 6
            'simple'           => isset($reference['simple']) ? (boolean) $reference['simple'] : false, // deprecated
290 6
            'storeAs'          => isset($reference['storeAs']) ? (string) $reference['storeAs'] : ClassMetadataInfo::REFERENCE_STORE_AS_DB_REF_WITH_DB,
291 6
            'targetDocument'   => isset($reference['targetDocument']) ? $reference['targetDocument'] : null,
292 6
            'collectionClass'  => isset($reference['collectionClass']) ? $reference['collectionClass'] : null,
293 6
            'fieldName'        => $fieldName,
294 6
            'strategy'         => isset($reference['strategy']) ? (string) $reference['strategy'] : $defaultStrategy,
295 6
            'inversedBy'       => isset($reference['inversedBy']) ? (string) $reference['inversedBy'] : null,
296 6
            'mappedBy'         => isset($reference['mappedBy']) ? (string) $reference['mappedBy'] : null,
297 6
            'repositoryMethod' => isset($reference['repositoryMethod']) ? (string) $reference['repositoryMethod'] : null,
298 6
            'limit'            => isset($reference['limit']) ? (integer) $reference['limit'] : null,
299 6
            'skip'             => isset($reference['skip']) ? (integer) $reference['skip'] : null,
300 6
            'prime'            => isset($reference['prime']) ? $reference['prime'] : [],
301
        );
302 6
        if (isset($reference['name'])) {
303 2
            $mapping['name'] = $reference['name'];
304
        }
305 6
        if (isset($reference['discriminatorField'])) {
306 2
            $mapping['discriminatorField'] = $this->parseDiscriminatorField($reference['discriminatorField']);
307
        }
308 6
        if (isset($reference['discriminatorMap'])) {
309 2
            $mapping['discriminatorMap'] = $reference['discriminatorMap'];
310
        }
311 6
        if (isset($reference['defaultDiscriminatorValue'])) {
312 2
            $mapping['defaultDiscriminatorValue'] = $reference['defaultDiscriminatorValue'];
313
        }
314 6
        if (isset($reference['sort'])) {
315
            $mapping['sort'] = $reference['sort'];
316
        }
317 6
        if (isset($reference['criteria'])) {
318
            $mapping['criteria'] = $reference['criteria'];
319
        }
320 6
        $this->addFieldMapping($class, $mapping);
321 6
    }
322
323
    /**
324
     * Parses the class or field-level "discriminatorField" option.
325
     *
326
     * If the value is an array, check the "name" option before falling back to
327
     * the deprecated "fieldName" option (for BC). Otherwise, the value must be
328
     * a string.
329
     *
330
     * @param array|string $discriminatorField
331
     * @return string
332
     * @throws \InvalidArgumentException if the value is neither a string nor an
333
     *                                   array with a "name" or "fieldName" key.
334
     */
335 2
    private function parseDiscriminatorField($discriminatorField)
336
    {
337 2
        if (is_string($discriminatorField)) {
338 2
            return $discriminatorField;
339
        }
340
341 2
        if ( ! is_array($discriminatorField)) {
342
            throw new \InvalidArgumentException('Expected array or string for discriminatorField; found: ' . gettype($discriminatorField));
343
        }
344
345 2
        if (isset($discriminatorField['name'])) {
346
            return (string) $discriminatorField['name'];
347
        }
348
349 2
        if (isset($discriminatorField['fieldName'])) {
350 2
            return (string) $discriminatorField['fieldName'];
351
        }
352
353
        throw new \InvalidArgumentException('Expected "name" or "fieldName" key in discriminatorField array; found neither.');
354
    }
355
356
    /**
357
     * {@inheritDoc}
358
     */
359 10
    protected function loadMappingFile($file)
360
    {
361
        try {
362 10
            return Yaml::parse(file_get_contents($file));
0 ignored issues
show
Bug Best Practice introduced by
The return type of return \Symfony\Componen...e_get_contents($file)); (null|Symfony\Component\Y...e|string|array|stdClass) is incompatible with the return type declared by the abstract method Doctrine\Common\Persiste...Driver::loadMappingFile of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
363
        }
364
        catch (ParseException $e) {
365
            $e->setParsedFile($file);
366
            throw $e;
367
        }
368
    }
369
370 2
    private function setShardKey(ClassMetadataInfo $class, array $shardKey)
371
    {
372 2
        $keys = $shardKey['keys'];
373 2
        $options = array();
374
375 2
        if (isset($shardKey['options'])) {
376 2
            $allowed = array('unique', 'numInitialChunks');
377 2
            foreach ($shardKey['options'] as $name => $value) {
378 2
                if ( ! in_array($name, $allowed, true)) {
379
                    continue;
380
                }
381 2
                $options[$name] = $value;
382
            }
383
        }
384
385 2
        $class->setShardKey($keys, $options);
386 2
    }
387
}
388