YamlDriver   B
last analyzed

Complexity

Total Complexity 46

Size/Duplication

Total Lines 155
Duplicated Lines 49.68 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
wmc 46
lcom 0
cbo 4
dl 77
loc 155
rs 8.72
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
F loadMetadataForClass() 64 113 41
A loadMappingFile() 0 4 1
A getCascadeMode() 13 13 3

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
namespace Doctrine\ODM\CouchDB\Mapping\Driver;
4
5
use Doctrine\Common\Persistence\Mapping\Driver\FileDriver,
6
    Doctrine\Common\Persistence\Mapping\ClassMetadata,
7
    Doctrine\ODM\CouchDB\Mapping\MappingException,
8
    Doctrine\Common\Persistence\Mapping\MappingException as DoctrineMappingException,
9
    Symfony\Component\Yaml\Yaml;
10
11
/**
12
 * The YamlDriver reads the mapping metadata from yaml schema files.
13
 *
14
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
15
 * @link        www.doctrine-project.org
16
 * @since       1.0
17
 * @author      Jonathan H. Wage <[email protected]>
18
 * @author      Roman Borschel <[email protected]>
19
 */
20
class YamlDriver extends FileDriver
21
{
22
    const DEFAULT_FILE_EXTENSION = '.dcm.yml';
23
24
    /**
25
     * {@inheritDoc}
26
     */
27
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
28
    {
29
        parent::__construct($locator, $fileExtension);
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35
    public function loadMetadataForClass($className, ClassMetadata $class)
36
    {
37
        /** @var $class \Doctrine\ODM\CouchDB\Mapping\ClassMetadata */
38
        try {
39
            $element = $this->getElement($className);
40
        } catch (DoctrineMappingException $e) {
41
            // Convert Exception type for consistency with other drivers
42
            throw new MappingException($e->getMessage(), $e->getCode(), $e);
43
        }
44
45
        if (!$element) {
46
            return;
47
        }
48
49
        if ($element['type'] == 'document') {
50
            $class->setCustomRepositoryClass(
51
                (isset($element['repositoryClass'])) ? $element['repositoryClass'] : null
52
            );
53
54
            if (isset($element['indexed']) && $element['indexed'] == true) {
55
                $class->indexed = true;
56
            }
57
58
            if (isset($element['inheritanceRoot']) && $element['inheritanceRoot']) {
59
                $class->markInheritanceRoot();
60
            }
61
        } else if ($element['type'] == 'embedded') {
62
            $class->isEmbeddedDocument = true;
63
64
            if (isset($element['inheritanceRoot']) && $element['inheritanceRoot']) {
65
                $class->markInheritanceRoot();
66
            }
67
        } else if (strtolower($element['type']) == "mappedsuperclass") {
68
            $class->isMappedSuperclass = true;
69
        } else {
70
            throw MappingException::classIsNotAValidDocument($className);
71
        }
72
73 View Code Duplication
        if (isset($element['id'])) {
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...
74
            foreach ($element['id'] AS $fieldName => $idElement) {
75
                $class->mapField(array(
76
                    'fieldName' => $fieldName,
77
                    'indexed'   => (isset($idElement['index'])) ? (bool)$idElement['index'] : false,
78
                    'type'      => (isset($idElement['type'])) ? $idElement['type'] : null,
79
                    'id'        => true,
80
                    'strategy'  => (isset($idElement['strategy'])) ? $idElement['strategy'] :  null,
81
                ));
82
            }
83
        }
84
85 View Code Duplication
        if (isset($element['fields'])) {
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...
86
            foreach ($element['fields'] AS $fieldName => $fieldElement) {
87
                $class->mapField(array(
88
                    'fieldName' => $fieldName,
89
                    'jsonName'  => (isset($fieldElement['jsonName'])) ? $fieldElement['jsonName'] : null,
90
                    'indexed'   => (isset($fieldElement['index'])) ? (bool)$fieldElement['index'] : false,
91
                    'type'      => (isset($fieldElement['type'])) ? $fieldElement['type'] : null,
92
                    'isVersionField' => (isset($fieldElement['version'])) ? true : null,
93
                ));
94
            }
95
        }
96
97
98 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...
99
            foreach ($element['referenceOne'] AS $field => $referenceOneElement) {
100
                $class->mapManyToOne(array(
101
                    'cascade'           => (isset($referenceOneElement['cascade'])) ? $this->getCascadeMode($referenceOneElement['cascade']) : 0,
102
                    'targetDocument'    => (string)$referenceOneElement['targetDocument'],
103
                    'fieldName'         => $field,
104
                    'jsonName'          => (isset($referenceOneElement['jsonName'])) ? (string)$referenceOneElement['jsonName'] : null,
105
                    'indexed'           => (isset($referenceOneElement['index'])) ? (bool)$referenceOneElement['index'] : false,
106
                ));
107
            }
108
        }
109
110 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...
111
            foreach ($element['referenceMany'] AS $field => $referenceManyElement) {
112
                $class->mapManyToMany(array(
113
                    'cascade'           => (isset($referenceManyElement['cascade'])) ? $this->getCascadeMode($referenceManyElement['cascade']) : 0,
114
                    'targetDocument'    => (string)$referenceManyElement['targetDocument'],
115
                    'fieldName'         => $field,
116
                    'jsonName'          => (isset($referenceManyElement['jsonName'])) ? (string)$referenceManyElement['jsonName'] : null,
117
                    'mappedBy'          => (isset($referenceManyElement['mappedBy'])) ? (string)$referenceManyElement['mappedBy'] : null,
118
                ));
119
            }
120
        }
121
122
        if (isset($element['attachments'])) {
123
            $class->mapAttachments($element['attachments']);
124
        }
125
126 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...
127
            foreach ($element['embedOne'] AS $field => $embedOneElement) {
128
                $class->mapEmbedded(array(
129
                    'targetDocument'    => (string)$embedOneElement['targetDocument'],
130
                    'fieldName'         => $field,
131
                    'jsonName'          => (isset($embedOneElement['jsonName'])) ? (string)$embedOneElement['jsonName'] : null,
132
                    'embedded'          => 'one',
133
                ));
134
            }
135
        }
136
137 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...
138
            foreach ($element['embedMany'] AS $field => $embedManyElement) {
139
                $class->mapEmbedded(array(
140
                    'targetDocument'    => (string)$embedManyElement['targetDocument'],
141
                    'fieldName'         => $field,
142
                    'jsonName'          => (isset($embedManyElement['jsonName'])) ? (string)$embedManyElement['jsonName'] : null,
143
                    'embedded'          => 'many',
144
                ));
145
            }
146
        }
147
    }
148
149
    protected function loadMappingFile($file)
150
    {
151
        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 Doctrine\Common\Persiste...Mapping\ClassMetadata[].

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...
152
    }
153
154
    /**
155
     * Gathers a list of cascade options found in the given cascade element.
156
     *
157
     * @param array $cascadeElement The cascade element.
158
     * @return integer a bitmask of cascade options.
159
     * @throws MappingException
160
     */
161 View Code Duplication
    private function getCascadeMode(array $cascadeElement)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
162
    {
163
        $cascade = 0;
164
        foreach ($cascadeElement as $cascadeMode) {
165
            $constantName = 'Doctrine\ODM\CouchDB\Mapping\ClassMetadata::CASCADE_' . strtoupper($cascadeMode);
166
            if (!defined($constantName)) {
167
                throw new MappingException("Cascade mode '$cascadeMode' not supported.");
168
            }
169
            $cascade |= constant($constantName);
170
        }
171
172
        return $cascade;
173
    }
174
}
175