AnnotationDriver.php 19.3 KB
Newer Older
1
<?php
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
 * <http://www.doctrine-project.org>.
 */
21

22 23
namespace Doctrine\ORM\Mapping\Driver;

24
use Doctrine\Common\Cache\ArrayCache,
25
    Doctrine\Common\Annotations\AnnotationReader,
26
    Doctrine\ORM\Mapping\ClassMetadataInfo,
27
    Doctrine\ORM\Mapping\MappingException;
28

29
require __DIR__ . '/DoctrineAnnotations.php';
30 31

/**
32
 * The AnnotationDriver reads the mapping metadata from docblock annotations.
33
 *
34 35 36 37 38 39 40 41
 * @license 	http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @link    	www.doctrine-project.org
 * @since   	2.0
 * @version     $Revision$
 * @author		Benjamin Eberlei <kontakt@beberlei.de>
 * @author		Guilherme Blanco <guilhermeblanco@hotmail.com>
 * @author      Jonathan H. Wage <jonwage@gmail.com>
 * @author      Roman Borschel <roman@code-factory.org>
42
 */
43
class AnnotationDriver implements Driver
44
{
45 46 47 48 49
    /** 
     * The AnnotationReader.
     *
     * @var AnnotationReader
     */
50
    private $_reader;
51
    
52 53 54 55 56 57 58 59 60 61 62 63 64 65
    /**
     * The paths where to look for mapping files.
     *
     * @var array
     */
    protected $_paths = array();

    /**
     * The file extension of mapping documents.
     *
     * @var string
     */
    protected $_fileExtension = '.php';
    
66
    /**
67 68 69
     * Initializes a new AnnotationDriver that uses the given AnnotationReader for reading
     * docblock annotations.
     * 
70
     * @param $reader The AnnotationReader to use.
71
     * @param string|array $paths One or multiple paths where mapping classes can be found. 
72
     */
73
    public function __construct(AnnotationReader $reader, $paths = null)
74 75
    {
        $this->_reader = $reader;
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        
        if ($paths) {
            $this->addPaths((array) $paths);
        }
    }
    
    /**
     * Append lookup paths to metadata driver.
     *
     * @param array $paths
     */
    public function addPaths(array $paths)
    {
        $this->_paths = array_unique(array_merge($this->_paths, $paths));
    }
    
    /**
     * Retrieve the defined metadata lookup paths.
     *
     * @return array
     */
    public function getPaths()
    {
        return $this->_paths;
    }

    /**
     * Get the file extension used to look for mapping files under
     *
     * @return void
     */
    public function getFileExtension()
    {
        return $this->_fileExtension;
    }

    /**
     * Set the file extension used to look for mapping files under
     *
     * @param string $fileExtension The file extension to set
     * @return void
     */
    public function setFileExtension($fileExtension)
    {
        $this->_fileExtension = $fileExtension;
121 122
    }

123 124
    /**
     * {@inheritdoc}
125
     */
126
    public function loadMetadataForClass($className, ClassMetadataInfo $metadata)
127
    {
128
        $class = $metadata->getReflectionClass();
romanb's avatar
romanb committed
129 130
        
        $classAnnotations = $this->_reader->getClassAnnotations($class);
131

132 133 134 135 136 137 138
        // Evaluate Entity annotation
        if (isset($classAnnotations['Doctrine\ORM\Mapping\Entity'])) {
            $entityAnnot = $classAnnotations['Doctrine\ORM\Mapping\Entity'];
            $metadata->setCustomRepositoryClass($entityAnnot->repositoryClass);
        } else if (isset($classAnnotations['Doctrine\ORM\Mapping\MappedSuperclass'])) {
            $metadata->isMappedSuperclass = true;
        } else {
139
            throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className);
140 141
        }

142
        // Evaluate DoctrineTable annotation
romanb's avatar
romanb committed
143 144
        if (isset($classAnnotations['Doctrine\ORM\Mapping\Table'])) {
            $tableAnnot = $classAnnotations['Doctrine\ORM\Mapping\Table'];
145
            $primaryTable = array(
146
                'name' => $tableAnnot->name,
147
                'schema' => $tableAnnot->schema
148
            );
149
            
150 151
            if ($tableAnnot->indexes !== null) {
                foreach ($tableAnnot->indexes as $indexAnnot) {
152 153 154
                    $primaryTable['indexes'][$indexAnnot->name] = array(
                        'columns' => $indexAnnot->columns
                    );
155 156
                }
            }
157
            
158 159
            if ($tableAnnot->uniqueConstraints !== null) {
                foreach ($tableAnnot->uniqueConstraints as $uniqueConstraint) {
160 161 162
                    $primaryTable['uniqueConstraints'][$uniqueConstraint->name] = array(
                        'columns' => $uniqueConstraint->columns
                    );
163 164
                }
            }
165
            
166
            $metadata->setPrimaryTable($primaryTable);
romanb's avatar
romanb committed
167
        }
168

169
        // Evaluate InheritanceType annotation
romanb's avatar
romanb committed
170 171
        if (isset($classAnnotations['Doctrine\ORM\Mapping\InheritanceType'])) {
            $inheritanceTypeAnnot = $classAnnotations['Doctrine\ORM\Mapping\InheritanceType'];
172
            $metadata->setInheritanceType(constant('\Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceTypeAnnot->value));
173 174
        }

175
        // Evaluate DiscriminatorColumn annotation
romanb's avatar
romanb committed
176 177
        if (isset($classAnnotations['Doctrine\ORM\Mapping\DiscriminatorColumn'])) {
            $discrColumnAnnot = $classAnnotations['Doctrine\ORM\Mapping\DiscriminatorColumn'];
178 179 180 181 182 183
            $metadata->setDiscriminatorColumn(array(
                'name' => $discrColumnAnnot->name,
                'type' => $discrColumnAnnot->type,
                'length' => $discrColumnAnnot->length
            ));
        }
184

185 186 187 188
        // Evaluate DiscriminatorMap annotation
        if (isset($classAnnotations['Doctrine\ORM\Mapping\DiscriminatorMap'])) {
            $discrMapAnnot = $classAnnotations['Doctrine\ORM\Mapping\DiscriminatorMap'];
            $metadata->setDiscriminatorMap($discrMapAnnot->value);
189
        }
190

191
        // Evaluate DoctrineChangeTrackingPolicy annotation
romanb's avatar
romanb committed
192 193
        if (isset($classAnnotations['Doctrine\ORM\Mapping\ChangeTrackingPolicy'])) {
            $changeTrackingAnnot = $classAnnotations['Doctrine\ORM\Mapping\ChangeTrackingPolicy'];
194 195 196
            $metadata->setChangeTrackingPolicy($changeTrackingAnnot->value);
        }

197
        // Evaluate annotations on properties/fields
198
        foreach ($class->getProperties() as $property) {
199 200 201 202 203
            if ($metadata->isMappedSuperclass && ! $property->isPrivate()
                ||
                $metadata->isInheritedField($property->name)
                ||
                $metadata->isInheritedAssociation($property->name)) {
204 205 206
                continue;
            }

207 208
            $mapping = array();
            $mapping['fieldName'] = $property->getName();
209

210
            // Check for JoinColummn/JoinColumns annotations
211
            $joinColumns = array();
212
            
213
            if ($joinColumnAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\JoinColumn')) {
214
                $joinColumns[] = array(
215 216 217 218 219
                    'name' => $joinColumnAnnot->name,
                    'referencedColumnName' => $joinColumnAnnot->referencedColumnName,
                    'unique' => $joinColumnAnnot->unique,
                    'nullable' => $joinColumnAnnot->nullable,
                    'onDelete' => $joinColumnAnnot->onDelete,
220 221
                    'onUpdate' => $joinColumnAnnot->onUpdate,
                    'columnDefinition' => $joinColumnAnnot->columnDefinition,
222
                );
223
            } else if ($joinColumnsAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\JoinColumns')) {
224 225 226 227 228 229 230
                foreach ($joinColumnsAnnot->value as $joinColumn) {
                    $joinColumns[] = array(
                        'name' => $joinColumn->name,
                        'referencedColumnName' => $joinColumn->referencedColumnName,
                        'unique' => $joinColumn->unique,
                        'nullable' => $joinColumn->nullable,
                        'onDelete' => $joinColumn->onDelete,
231 232
                        'onUpdate' => $joinColumn->onUpdate,
                        'columnDefinition' => $joinColumn->columnDefinition,
233 234
                    );
                }
235 236
            }

237 238
            // Field can only be annotated with one of:
            // @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany
239
            if ($columnAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Column')) {
240
                if ($columnAnnot->type == null) {
241
                    throw MappingException::propertyTypeIsRequired($className, $property->getName());
242
                }
243
                
244 245
                $mapping['type'] = $columnAnnot->type;
                $mapping['length'] = $columnAnnot->length;
246 247
                $mapping['precision'] = $columnAnnot->precision;
                $mapping['scale'] = $columnAnnot->scale;
248
                $mapping['nullable'] = $columnAnnot->nullable;
249
                $mapping['unique'] = $columnAnnot->unique;
250 251 252
                if ($columnAnnot->options) {
                    $mapping['options'] = $columnAnnot->options;
                }
253
                
254 255 256
                if (isset($columnAnnot->name)) {
                    $mapping['columnName'] = $columnAnnot->name;
                }
257
                
258 259 260 261
                if (isset($columnAnnot->columnDefinition)) {
                    $mapping['columnDefinition'] = $columnAnnot->columnDefinition;
                }
                
262
                if ($idAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Id')) {
263 264
                    $mapping['id'] = true;
                }
265
                
266
                if ($generatedValueAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\GeneratedValue')) {
267
                    $metadata->setIdGeneratorType(constant('Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy));
268
                }
269
                
270
                if ($versionAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\Version')) {
271
                    $metadata->setVersionMapping($mapping);
272
                }
273
                
274
                $metadata->mapField($mapping);
275 276

                // Check for SequenceGenerator/TableGenerator definition
277
                if ($seqGeneratorAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\SequenceGenerator')) {
278 279 280 281 282
                    $metadata->setSequenceGeneratorDefinition(array(
                        'sequenceName' => $seqGeneratorAnnot->sequenceName,
                        'allocationSize' => $seqGeneratorAnnot->allocationSize,
                        'initialValue' => $seqGeneratorAnnot->initialValue
                    ));
283
                } else if ($tblGeneratorAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\TableGenerator')) {
284
                    throw MappingException::tableIdGeneratorNotImplemented($className);
285
                }
286
            } else if ($oneToOneAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\OneToOne')) {
287
                $mapping['targetEntity'] = $oneToOneAnnot->targetEntity;
288
                $mapping['joinColumns'] = $joinColumns;
289 290
                $mapping['mappedBy'] = $oneToOneAnnot->mappedBy;
                $mapping['cascade'] = $oneToOneAnnot->cascade;
291
                $mapping['orphanRemoval'] = $oneToOneAnnot->orphanRemoval;
292
                $mapping['fetch'] = constant('Doctrine\ORM\Mapping\AssociationMapping::FETCH_' . $oneToOneAnnot->fetch);
293
                $metadata->mapOneToOne($mapping);
294
            } else if ($oneToManyAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\OneToMany')) {
295 296
                $mapping['mappedBy'] = $oneToManyAnnot->mappedBy;
                $mapping['targetEntity'] = $oneToManyAnnot->targetEntity;
297
                $mapping['cascade'] = $oneToManyAnnot->cascade;
298
                $mapping['orphanRemoval'] = $oneToManyAnnot->orphanRemoval;
299
                $mapping['fetch'] = constant('Doctrine\ORM\Mapping\AssociationMapping::FETCH_' . $oneToManyAnnot->fetch);
300
                $metadata->mapOneToMany($mapping);
301
            } else if ($manyToOneAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\ManyToOne')) {
302
                $mapping['joinColumns'] = $joinColumns;
303
                $mapping['cascade'] = $manyToOneAnnot->cascade;
304
                $mapping['targetEntity'] = $manyToOneAnnot->targetEntity;
305
                $mapping['fetch'] = constant('Doctrine\ORM\Mapping\AssociationMapping::FETCH_' . $manyToOneAnnot->fetch);
306
                $metadata->mapManyToOne($mapping);
307
            } else if ($manyToManyAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\ManyToMany')) {
308
                $joinTable = array();
309
                
310
                if ($joinTableAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\ORM\Mapping\JoinTable')) {
311 312
                    $joinTable = array(
                        'name' => $joinTableAnnot->name,
313
                        'schema' => $joinTableAnnot->schema
314
                    );
315 316 317 318 319 320 321 322
                    
                    foreach ($joinTableAnnot->joinColumns as $joinColumn) {
                        $joinTable['joinColumns'][] = array(
                            'name' => $joinColumn->name,
                            'referencedColumnName' => $joinColumn->referencedColumnName,
                            'unique' => $joinColumn->unique,
                            'nullable' => $joinColumn->nullable,
                            'onDelete' => $joinColumn->onDelete,
323 324
                            'onUpdate' => $joinColumn->onUpdate,
                            'columnDefinition' => $joinColumn->columnDefinition,
325 326 327 328 329 330 331 332 333 334
                        );
                    }

                    foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) {
                        $joinTable['inverseJoinColumns'][] = array(
                            'name' => $joinColumn->name,
                            'referencedColumnName' => $joinColumn->referencedColumnName,
                            'unique' => $joinColumn->unique,
                            'nullable' => $joinColumn->nullable,
                            'onDelete' => $joinColumn->onDelete,
335 336
                            'onUpdate' => $joinColumn->onUpdate,
                            'columnDefinition' => $joinColumn->columnDefinition,
337 338
                        );
                    }
339
                }
340
                
341
                $mapping['joinTable'] = $joinTable;
342 343
                $mapping['targetEntity'] = $manyToManyAnnot->targetEntity;
                $mapping['mappedBy'] = $manyToManyAnnot->mappedBy;
344
                $mapping['cascade'] = $manyToManyAnnot->cascade;
345
                $mapping['fetch'] = constant('Doctrine\ORM\Mapping\AssociationMapping::FETCH_' . $manyToManyAnnot->fetch);
346
                $metadata->mapManyToMany($mapping);
romanb's avatar
romanb committed
347
            }
348 349
        }
        
350 351
        // Evaluate HasLifecycleCallbacks annotation
        if (isset($classAnnotations['Doctrine\ORM\Mapping\HasLifecycleCallbacks'])) {
352 353 354
            foreach ($class->getMethods() as $method) {
                if ($method->isPublic()) {
                    $annotations = $this->_reader->getMethodAnnotations($method);
355
                    
romanb's avatar
romanb committed
356 357
                    if (isset($annotations['Doctrine\ORM\Mapping\PrePersist'])) {
                        $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::prePersist);
358
                    }
359
                    
romanb's avatar
romanb committed
360 361
                    if (isset($annotations['Doctrine\ORM\Mapping\PostPersist'])) {
                        $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postPersist);
362
                    }
363
                    
364 365 366
                    if (isset($annotations['Doctrine\ORM\Mapping\PreUpdate'])) {
                        $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preUpdate);
                    }
367
                    
368 369 370
                    if (isset($annotations['Doctrine\ORM\Mapping\PostUpdate'])) {
                        $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postUpdate);
                    }
371
                    
romanb's avatar
romanb committed
372 373
                    if (isset($annotations['Doctrine\ORM\Mapping\PreRemove'])) {
                        $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preRemove);
374
                    }
375
                    
romanb's avatar
romanb committed
376 377
                    if (isset($annotations['Doctrine\ORM\Mapping\PostRemove'])) {
                        $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postRemove);
378
                    }
379
                    
380 381 382 383
                    if (isset($annotations['Doctrine\ORM\Mapping\PostLoad'])) {
                        $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postLoad);
                    }
                }
384 385 386
            }
        }
    }
387 388

    /**
romanb's avatar
romanb committed
389 390 391
     * Whether the class with the specified name is transient. Only non-transient
     * classes, that is entities and mapped superclasses, should have their metadata loaded.
     * A class is non-transient if it is annotated with either @Entity or
392
     * @MappedSuperclass in the class doc block.
393 394 395 396 397 398
     *
     * @param string $className
     * @return boolean
     */
    public function isTransient($className)
    {
romanb's avatar
romanb committed
399
        $classAnnotations = $this->_reader->getClassAnnotations(new \ReflectionClass($className));
400
        
romanb's avatar
romanb committed
401
        return ! isset($classAnnotations['Doctrine\ORM\Mapping\Entity']) &&
402
               ! isset($classAnnotations['Doctrine\ORM\Mapping\MappedSuperclass']);
403
    }
404
    
405 406 407 408
    /**
     * {@inheritDoc}
     */
    public function getAllClassNames()
409
    {
410 411 412 413 414 415 416 417 418
        $classes = array();
    
        if ($this->_paths) {
            $declared = get_declared_classes();
            
            foreach ((array) $this->_paths as $path) {
                if ( ! is_dir($path)) {
                    throw MappingException::annotationDriverRequiresConfiguredDirectoryPath();
                }
419
            
420 421
                $iterator = new \RecursiveIteratorIterator(
                    new \RecursiveDirectoryIterator($path),
422 423
                    \RecursiveIteratorIterator::LEAVES_ONLY
                );
424
        
425
                foreach ($iterator as $file) {
426
                    if (($fileName = $file->getBasename($this->_fileExtension)) == $file->getBasename()) {
427 428 429
                        continue;
                    }
                    
430
                    require_once $file->getPathName();
431
                }
432 433 434
            }
            
            $declared = array_diff(get_declared_classes(), $declared);
435

436 437 438
            foreach ($declared as $className) {                 
                if ( ! $this->isTransient($className)) {
                    $classes[] = $className;
439
                }
440
            }
441
        }
442 443
        
        return $classes;
444
    }
445
    
446
}