Completed
Push — master ( 707688...6da863 )
by Mike
04:47 queued 02:08
created

YamlDriver::getCascadeMode()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 8

Duplication

Lines 13
Ratio 100 %

Importance

Changes 0
Metric Value
dl 13
loc 13
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
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\CouchDB\Mapping\Driver;
21
22
use Doctrine\Common\Persistence\Mapping\Driver\FileDriver,
23
    Doctrine\Common\Persistence\Mapping\ClassMetadata,
24
    Doctrine\ODM\CouchDB\Mapping\MappingException,
25
    Doctrine\Common\Persistence\Mapping\MappingException as DoctrineMappingException,
26
    Symfony\Component\Yaml\Yaml;
27
28
/**
29
 * The YamlDriver reads the mapping metadata from yaml schema files.
30
 *
31
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
32
 * @link        www.doctrine-project.org
33
 * @since       1.0
34
 * @author      Jonathan H. Wage <[email protected]>
35
 * @author      Roman Borschel <[email protected]>
36
 */
37
class YamlDriver extends FileDriver
38
{
39
    const DEFAULT_FILE_EXTENSION = '.dcm.yml';
40
41
    /**
42
     * {@inheritDoc}
43
     */
44
    public function __construct($locator, $fileExtension = self::DEFAULT_FILE_EXTENSION)
45
    {
46
        parent::__construct($locator, $fileExtension);
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function loadMetadataForClass($className, ClassMetadata $class)
53
    {
54
        /** @var $class \Doctrine\ODM\CouchDB\Mapping\ClassMetadata */
55
        try {
56
            $element = $this->getElement($className);
57
        } catch (DoctrineMappingException $e) {
58
            // Convert Exception type for consistency with other drivers
59
            throw new MappingException($e->getMessage(), $e->getCode(), $e);
60
        }
61
62
        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...
63
            return;
64
        }
65
66
        if ($element['type'] == 'document') {
67
            $class->setCustomRepositoryClass(
68
                (isset($element['repositoryClass'])) ? $element['repositoryClass'] : null
69
            );
70
71
            if (isset($element['indexed']) && $element['indexed'] == true) {
72
                $class->indexed = true;
73
            }
74
75
            if (isset($element['inheritanceRoot']) && $element['inheritanceRoot']) {
76
                $class->markInheritanceRoot();
77
            }
78
        } else if ($element['type'] == 'embedded') {
79
            $class->isEmbeddedDocument = true;
80
81
            if (isset($element['inheritanceRoot']) && $element['inheritanceRoot']) {
82
                $class->markInheritanceRoot();
83
            }
84
        } else if (strtolower($element['type']) == "mappedsuperclass") {
85
            $class->isMappedSuperclass = true;
86
        } else {
87
            throw MappingException::classIsNotAValidDocument($className);
88
        }
89
90 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...
91
            foreach ($element['id'] AS $fieldName => $idElement) {
92
                $class->mapField(array(
93
                    'fieldName' => $fieldName,
94
                    'indexed'   => (isset($idElement['index'])) ? (bool)$idElement['index'] : false,
95
                    'type'      => (isset($idElement['type'])) ? $idElement['type'] : null,
96
                    'id'        => true,
97
                    'strategy'  => (isset($idElement['strategy'])) ? $idElement['strategy'] :  null,
98
                ));
99
            }
100
        }
101
102 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...
103
            foreach ($element['fields'] AS $fieldName => $fieldElement) {
104
                $class->mapField(array(
105
                    'fieldName' => $fieldName,
106
                    'jsonName'  => (isset($fieldElement['jsonName'])) ? $fieldElement['jsonName'] : null,
107
                    'indexed'   => (isset($fieldElement['index'])) ? (bool)$fieldElement['index'] : false,
108
                    'type'      => (isset($fieldElement['type'])) ? $fieldElement['type'] : null,
109
                    'isVersionField' => (isset($fieldElement['version'])) ? true : null,
110
                ));
111
            }
112
        }
113
114
115 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...
116
            foreach ($element['referenceOne'] AS $field => $referenceOneElement) {
117
                $class->mapManyToOne(array(
118
                    'cascade'           => (isset($referenceOneElement['cascade'])) ? $this->getCascadeMode($referenceOneElement['cascade']) : 0,
119
                    'targetDocument'    => (string)$referenceOneElement['targetDocument'],
120
                    'fieldName'         => $field,
121
                    'jsonName'          => (isset($referenceOneElement['jsonName'])) ? (string)$referenceOneElement['jsonName'] : null,
122
                    'indexed'           => (isset($referenceOneElement['index'])) ? (bool)$referenceOneElement['index'] : false,
123
                ));
124
            }
125
        }
126
127 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...
128
            foreach ($element['referenceMany'] AS $field => $referenceManyElement) {
129
                $class->mapManyToMany(array(
130
                    'cascade'           => (isset($referenceManyElement['cascade'])) ? $this->getCascadeMode($referenceManyElement['cascade']) : 0,
131
                    'targetDocument'    => (string)$referenceManyElement['targetDocument'],
132
                    'fieldName'         => $field,
133
                    'jsonName'          => (isset($referenceManyElement['jsonName'])) ? (string)$referenceManyElement['jsonName'] : null,
134
                    'mappedBy'          => (isset($referenceManyElement['mappedBy'])) ? (string)$referenceManyElement['mappedBy'] : null,
135
                ));
136
            }
137
        }
138
139
        if (isset($element['attachments'])) {
140
            $class->mapAttachments($element['attachments']);
141
        }
142
143 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...
144
            foreach ($element['embedOne'] AS $field => $embedOneElement) {
145
                $class->mapEmbedded(array(
146
                    'targetDocument'    => (string)$embedOneElement['targetDocument'],
147
                    'fieldName'         => $field,
148
                    'jsonName'          => (isset($embedOneElement['jsonName'])) ? (string)$embedOneElement['jsonName'] : null,
149
                    'embedded'          => 'one',
150
                ));
151
            }
152
        }
153
154 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...
155
            foreach ($element['embedMany'] AS $field => $embedManyElement) {
156
                $class->mapEmbedded(array(
157
                    'targetDocument'    => (string)$embedManyElement['targetDocument'],
158
                    'fieldName'         => $field,
159
                    'jsonName'          => (isset($embedManyElement['jsonName'])) ? (string)$embedManyElement['jsonName'] : null,
160
                    'embedded'          => 'many',
161
                ));
162
            }
163
        }
164
    }
165
166
    protected function loadMappingFile($file)
167
    {
168
        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)); (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...
169
    }
170
171
    /**
172
     * Gathers a list of cascade options found in the given cascade element.
173
     *
174
     * @param array $cascadeElement The cascade element.
175
     * @return integer a bitmask of cascade options.
176
     * @throws MappingException
177
     */
178 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...
179
    {
180
        $cascade = 0;
181
        foreach ($cascadeElement as $cascadeMode) {
182
            $constantName = 'Doctrine\ODM\CouchDB\Mapping\ClassMetadata::CASCADE_' . strtoupper($cascadeMode);
183
            if (!defined($constantName)) {
184
                throw new MappingException("Cascade mode '$cascadeMode' not supported.");
185
            }
186
            $cascade |= constant($constantName);
187
        }
188
189
        return $cascade;
190
    }
191
}
192