source: pro-violet-viettel/sourcecode/application/libraries/Doctrine/ORM/Tools/SchemaValidator.php @ 345

Last change on this file since 345 was 345, checked in by quyenla, 11 years ago

collaborator page

File size: 14.2 KB
Line 
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 LGPL. For more information, see
17 * <http://www.doctrine-project.org>.
18*/
19
20namespace Doctrine\ORM\Tools;
21
22use Doctrine\ORM\EntityManager;
23use Doctrine\ORM\Mapping\ClassMetadataInfo;
24use Doctrine\DBAL\Types\Type;
25
26/**
27 * Performs strict validation of the mapping schema
28 *
29 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
30 * @link        www.doctrine-project.com
31 * @since       1.0
32 * @author      Benjamin Eberlei <kontakt@beberlei.de>
33 * @author      Guilherme Blanco <guilhermeblanco@hotmail.com>
34 * @author      Jonathan Wage <jonwage@gmail.com>
35 * @author      Roman Borschel <roman@code-factory.org>
36 */
37class SchemaValidator
38{
39    /**
40     * @var EntityManager
41     */
42    private $em;
43
44    /**
45     * @param EntityManager $em
46     */
47    public function __construct(EntityManager $em)
48    {
49        $this->em = $em;
50    }
51
52    /**
53     * Checks the internal consistency of all mapping files.
54     *
55     * There are several checks that can't be done at runtime or are too expensive, which can be verified
56     * with this command. For example:
57     *
58     * 1. Check if a relation with "mappedBy" is actually connected to that specified field.
59     * 2. Check if "mappedBy" and "inversedBy" are consistent to each other.
60     * 3. Check if "referencedColumnName" attributes are really pointing to primary key columns.
61     * 4. Check if there are public properties that might cause problems with lazy loading.
62     *
63     * @return array
64     */
65    public function validateMapping()
66    {
67        $errors = array();
68        $cmf = $this->em->getMetadataFactory();
69        $classes = $cmf->getAllMetadata();
70
71        foreach ($classes AS $class) {
72            if ($ce = $this->validateClass($class)) {
73                $errors[$class->name] = $ce;
74            }
75        }
76
77        return $errors;
78    }
79
80    /**
81     * Validate a single class of the current
82     *
83     * @param ClassMetadataInfo $class
84     * @return array
85     */
86    public function validateClass(ClassMetadataInfo $class)
87    {
88        $ce = array();
89        $cmf = $this->em->getMetadataFactory();
90
91        foreach ($class->fieldMappings as $fieldName => $mapping) {
92            if (!Type::hasType($mapping['type'])) {
93                $ce[] = "The field '" . $class->name . "#" . $fieldName."' uses a non-existant type '" . $mapping['type'] . "'.";
94            }
95        }
96
97        foreach ($class->associationMappings AS $fieldName => $assoc) {
98            if (!class_exists($assoc['targetEntity']) || $cmf->isTransient($assoc['targetEntity'])) {
99                $ce[] = "The target entity '" . $assoc['targetEntity'] . "' specified on " . $class->name . '#' . $fieldName . ' is unknown or not an entity.';
100                return $ce;
101            }
102
103            if ($assoc['mappedBy'] && $assoc['inversedBy']) {
104                $ce[] = "The association " . $class . "#" . $fieldName . " cannot be defined as both inverse and owning.";
105            }
106
107            $targetMetadata = $cmf->getMetadataFor($assoc['targetEntity']);
108
109            if (isset($assoc['id']) && $targetMetadata->containsForeignIdentifier) {
110                $ce[] = "Cannot map association '" . $class->name. "#". $fieldName ." as identifier, because " .
111                        "the target entity '". $targetMetadata->name . "' also maps an association as identifier.";
112            }
113
114            /* @var $assoc AssociationMapping */
115            if ($assoc['mappedBy']) {
116                if ($targetMetadata->hasField($assoc['mappedBy'])) {
117                    $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the owning side ".
118                            "field " . $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " which is not defined as association.";
119                }
120                if (!$targetMetadata->hasAssociation($assoc['mappedBy'])) {
121                    $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the owning side ".
122                            "field " . $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " which does not exist.";
123                } else if ($targetMetadata->associationMappings[$assoc['mappedBy']]['inversedBy'] == null) {
124                    $ce[] = "The field " . $class->name . "#" . $fieldName . " is on the inverse side of a ".
125                            "bi-directional relationship, but the specified mappedBy association on the target-entity ".
126                            $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " does not contain the required ".
127                            "'inversedBy=".$fieldName."' attribute.";
128                } else  if ($targetMetadata->associationMappings[$assoc['mappedBy']]['inversedBy'] != $fieldName) {
129                    $ce[] = "The mappings " . $class->name . "#" . $fieldName . " and " .
130                            $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " are ".
131                            "incosistent with each other.";
132                }
133            }
134
135            if ($assoc['inversedBy']) {
136                if ($targetMetadata->hasField($assoc['inversedBy'])) {
137                    $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the inverse side ".
138                            "field " . $assoc['targetEntity'] . "#" . $assoc['inversedBy'] . " which is not defined as association.";
139                }
140                if (!$targetMetadata->hasAssociation($assoc['inversedBy'])) {
141                    $ce[] = "The association " . $class->name . "#" . $fieldName . " refers to the inverse side ".
142                            "field " . $assoc['targetEntity'] . "#" . $assoc['inversedBy'] . " which does not exist.";
143                } else if ($targetMetadata->associationMappings[$assoc['inversedBy']]['mappedBy'] == null) {
144                    $ce[] = "The field " . $class->name . "#" . $fieldName . " is on the owning side of a ".
145                            "bi-directional relationship, but the specified mappedBy association on the target-entity ".
146                            $assoc['targetEntity'] . "#" . $assoc['mappedBy'] . " does not contain the required ".
147                            "'inversedBy' attribute.";
148                } else  if ($targetMetadata->associationMappings[$assoc['inversedBy']]['mappedBy'] != $fieldName) {
149                    $ce[] = "The mappings " . $class->name . "#" . $fieldName . " and " .
150                            $assoc['targetEntity'] . "#" . $assoc['inversedBy'] . " are ".
151                            "incosistent with each other.";
152                }
153
154                // Verify inverse side/owning side match each other
155                if (array_key_exists($assoc['inversedBy'], $targetMetadata->associationMappings)) {
156                    $targetAssoc = $targetMetadata->associationMappings[$assoc['inversedBy']];
157                    if ($assoc['type'] == ClassMetadataInfo::ONE_TO_ONE && $targetAssoc['type'] !== ClassMetadataInfo::ONE_TO_ONE){
158                        $ce[] = "If association " . $class->name . "#" . $fieldName . " is one-to-one, then the inversed " .
159                                "side " . $targetMetadata->name . "#" . $assoc['inversedBy'] . " has to be one-to-one as well.";
160                    } else if ($assoc['type'] == ClassMetadataInfo::MANY_TO_ONE && $targetAssoc['type'] !== ClassMetadataInfo::ONE_TO_MANY){
161                        $ce[] = "If association " . $class->name . "#" . $fieldName . " is many-to-one, then the inversed " .
162                                "side " . $targetMetadata->name . "#" . $assoc['inversedBy'] . " has to be one-to-many.";
163                    } else if ($assoc['type'] == ClassMetadataInfo::MANY_TO_MANY && $targetAssoc['type'] !== ClassMetadataInfo::MANY_TO_MANY){
164                        $ce[] = "If association " . $class->name . "#" . $fieldName . " is many-to-many, then the inversed " .
165                                "side " . $targetMetadata->name . "#" . $assoc['inversedBy'] . " has to be many-to-many as well.";
166                    }
167                }
168            }
169
170            if ($assoc['isOwningSide']) {
171                if ($assoc['type'] == ClassMetadataInfo::MANY_TO_MANY) {
172                    $identifierColumns = $class->getIdentifierColumnNames();
173                    foreach ($assoc['joinTable']['joinColumns'] AS $joinColumn) {
174                        if (!in_array($joinColumn['referencedColumnName'], $identifierColumns)) {
175                            $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' " .
176                                "has to be a primary key column on the target entity class '".$class->name."'.";
177                            break;
178                        }
179                    }
180
181                    $identifierColumns = $targetMetadata->getIdentifierColumnNames();
182                    foreach ($assoc['joinTable']['inverseJoinColumns'] AS $inverseJoinColumn) {
183                        if (!in_array($inverseJoinColumn['referencedColumnName'], $identifierColumns)) {
184                            $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' " .
185                                "has to be a primary key column on the target entity class '".$targetMetadata->name."'.";
186                            break;
187                        }
188                    }
189
190                    if (count($targetMetadata->getIdentifierColumnNames()) != count($assoc['joinTable']['inverseJoinColumns'])) {
191                        $ce[] = "The inverse join columns of the many-to-many table '" . $assoc['joinTable']['name'] . "' " .
192                                "have to contain to ALL identifier columns of the target entity '". $targetMetadata->name . "', " .
193                                "however '" . implode(", ", array_diff($targetMetadata->getIdentifierColumnNames(), array_values($assoc['relationToTargetKeyColumns']))) .
194                                "' are missing.";
195                    }
196
197                    if (count($class->getIdentifierColumnNames()) != count($assoc['joinTable']['joinColumns'])) {
198                        $ce[] = "The join columns of the many-to-many table '" . $assoc['joinTable']['name'] . "' " .
199                                "have to contain to ALL identifier columns of the source entity '". $class->name . "', " .
200                                "however '" . implode(", ", array_diff($class->getIdentifierColumnNames(), array_values($assoc['relationToSourceKeyColumns']))) .
201                                "' are missing.";
202                    }
203
204                } else if ($assoc['type'] & ClassMetadataInfo::TO_ONE) {
205                    $identifierColumns = $targetMetadata->getIdentifierColumnNames();
206                    foreach ($assoc['joinColumns'] AS $joinColumn) {
207                        if (!in_array($joinColumn['referencedColumnName'], $identifierColumns)) {
208                            $ce[] = "The referenced column name '" . $joinColumn['referencedColumnName'] . "' " .
209                                    "has to be a primary key column on the target entity class '".$targetMetadata->name."'.";
210                        }
211                    }
212
213                    if (count($identifierColumns) != count($assoc['joinColumns'])) {
214                        $ids = array();
215                        foreach ($assoc['joinColumns'] AS $joinColumn) {
216                            $ids[] = $joinColumn['name'];
217                        }
218
219                        $ce[] = "The join columns of the association '" . $assoc['fieldName'] . "' " .
220                                "have to match to ALL identifier columns of the target entity '". $class->name . "', " .
221                                "however '" . implode(", ", array_diff($targetMetadata->getIdentifierColumnNames(), $ids)) .
222                                "' are missing.";
223                    }
224                }
225            }
226
227            if (isset($assoc['orderBy']) && $assoc['orderBy'] !== null) {
228                foreach ($assoc['orderBy'] AS $orderField => $orientation) {
229                    if (!$targetMetadata->hasField($orderField)) {
230                        $ce[] = "The association " . $class->name."#".$fieldName." is ordered by a foreign field " .
231                                $orderField . " that is not a field on the target entity " . $targetMetadata->name;
232                    }
233                }
234            }
235        }
236
237        foreach ($class->reflClass->getProperties(\ReflectionProperty::IS_PUBLIC) as $publicAttr) {
238            if ($publicAttr->isStatic()) {
239                continue;
240            }
241            $ce[] = "Field '".$publicAttr->getName()."' in class '".$class->name."' must be private ".
242                    "or protected. Public fields may break lazy-loading.";
243        }
244
245        foreach ($class->subClasses AS $subClass) {
246            if (!in_array($class->name, class_parents($subClass))) {
247                $ce[] = "According to the discriminator map class '" . $subClass . "' has to be a child ".
248                        "of '" . $class->name . "' but these entities are not related through inheritance.";
249            }
250        }
251
252        return $ce;
253    }
254
255    /**
256     * Check if the Database Schema is in sync with the current metadata state.
257     *
258     * @return bool
259     */
260    public function schemaInSyncWithMetadata()
261    {
262        $schemaTool = new SchemaTool($this->em);
263
264        $allMetadata = $this->em->getMetadataFactory()->getAllMetadata();
265        return (count($schemaTool->getUpdateSchemaSql($allMetadata, true)) == 0);
266    }
267}
Note: See TracBrowser for help on using the repository browser.