vendor/doctrine/lib/Doctrine/ORM/PersistentCollection.php
changeset 0 7f95f8617b0b
equal deleted inserted replaced
-1:000000000000 0:7f95f8617b0b
       
     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 
       
    20 namespace Doctrine\ORM;
       
    21 
       
    22 use Doctrine\ORM\Mapping\ClassMetadata,
       
    23     Doctrine\Common\Collections\Collection,
       
    24     Closure;
       
    25 
       
    26 /**
       
    27  * A PersistentCollection represents a collection of elements that have persistent state.
       
    28  *
       
    29  * Collections of entities represent only the associations (links) to those entities.
       
    30  * That means, if the collection is part of a many-many mapping and you remove
       
    31  * entities from the collection, only the links in the relation table are removed (on flush).
       
    32  * Similarly, if you remove entities from a collection that is part of a one-many
       
    33  * mapping this will only result in the nulling out of the foreign keys on flush.
       
    34  *
       
    35  * @since     2.0
       
    36  * @author    Konsta Vesterinen <kvesteri@cc.hut.fi>
       
    37  * @author    Roman Borschel <roman@code-factory.org>
       
    38  * @author    Giorgio Sironi <piccoloprincipeazzurro@gmail.com>
       
    39  * @todo Design for inheritance to allow custom implementations?
       
    40  */
       
    41 final class PersistentCollection implements Collection
       
    42 {
       
    43     /**
       
    44      * A snapshot of the collection at the moment it was fetched from the database.
       
    45      * This is used to create a diff of the collection at commit time.
       
    46      *
       
    47      * @var array
       
    48      */
       
    49     private $snapshot = array();
       
    50 
       
    51     /**
       
    52      * The entity that owns this collection.
       
    53      *
       
    54      * @var object
       
    55      */
       
    56     private $owner;
       
    57 
       
    58     /**
       
    59      * The association mapping the collection belongs to.
       
    60      * This is currently either a OneToManyMapping or a ManyToManyMapping.
       
    61      *
       
    62      * @var array
       
    63      */
       
    64     private $association;
       
    65 
       
    66     /**
       
    67      * The EntityManager that manages the persistence of the collection.
       
    68      *
       
    69      * @var Doctrine\ORM\EntityManager
       
    70      */
       
    71     private $em;
       
    72 
       
    73     /**
       
    74      * The name of the field on the target entities that points to the owner
       
    75      * of the collection. This is only set if the association is bi-directional.
       
    76      *
       
    77      * @var string
       
    78      */
       
    79     private $backRefFieldName;
       
    80 
       
    81     /**
       
    82      * The class descriptor of the collection's entity type.
       
    83      */
       
    84     private $typeClass;
       
    85 
       
    86     /**
       
    87      * Whether the collection is dirty and needs to be synchronized with the database
       
    88      * when the UnitOfWork that manages its persistent state commits.
       
    89      *
       
    90      * @var boolean
       
    91      */
       
    92     private $isDirty = false;
       
    93 
       
    94     /**
       
    95      * Whether the collection has already been initialized.
       
    96      * 
       
    97      * @var boolean
       
    98      */
       
    99     private $initialized = true;
       
   100     
       
   101     /**
       
   102      * The wrapped Collection instance.
       
   103      * 
       
   104      * @var Collection
       
   105      */
       
   106     private $coll;
       
   107 
       
   108     /**
       
   109      * Creates a new persistent collection.
       
   110      * 
       
   111      * @param EntityManager $em The EntityManager the collection will be associated with.
       
   112      * @param ClassMetadata $class The class descriptor of the entity type of this collection.
       
   113      * @param array The collection elements.
       
   114      */
       
   115     public function __construct(EntityManager $em, $class, $coll)
       
   116     {
       
   117         $this->coll = $coll;
       
   118         $this->em = $em;
       
   119         $this->typeClass = $class;
       
   120     }
       
   121 
       
   122     /**
       
   123      * INTERNAL:
       
   124      * Sets the collection's owning entity together with the AssociationMapping that
       
   125      * describes the association between the owner and the elements of the collection.
       
   126      *
       
   127      * @param object $entity
       
   128      * @param AssociationMapping $assoc
       
   129      */
       
   130     public function setOwner($entity, array $assoc)
       
   131     {
       
   132         $this->owner = $entity;
       
   133         $this->association = $assoc;
       
   134         $this->backRefFieldName = $assoc['inversedBy'] ?: $assoc['mappedBy'];
       
   135     }
       
   136 
       
   137     /**
       
   138      * INTERNAL:
       
   139      * Gets the collection owner.
       
   140      *
       
   141      * @return object
       
   142      */
       
   143     public function getOwner()
       
   144     {
       
   145         return $this->owner;
       
   146     }
       
   147     
       
   148     public function getTypeClass()
       
   149     {
       
   150         return $this->typeClass;
       
   151     }
       
   152 
       
   153     /**
       
   154      * INTERNAL:
       
   155      * Adds an element to a collection during hydration. This will automatically
       
   156      * complete bidirectional associations in the case of a one-to-many association.
       
   157      * 
       
   158      * @param mixed $element The element to add.
       
   159      */
       
   160     public function hydrateAdd($element)
       
   161     {
       
   162         $this->coll->add($element);
       
   163         // If _backRefFieldName is set and its a one-to-many association,
       
   164         // we need to set the back reference.
       
   165         if ($this->backRefFieldName && $this->association['type'] == ClassMetadata::ONE_TO_MANY) {
       
   166             // Set back reference to owner
       
   167             $this->typeClass->reflFields[$this->backRefFieldName]
       
   168                     ->setValue($element, $this->owner);
       
   169             $this->em->getUnitOfWork()->setOriginalEntityProperty(
       
   170                     spl_object_hash($element),
       
   171                     $this->backRefFieldName,
       
   172                     $this->owner);
       
   173         }
       
   174     }
       
   175     
       
   176     /**
       
   177      * INTERNAL:
       
   178      * Sets a keyed element in the collection during hydration.
       
   179      *
       
   180      * @param mixed $key The key to set.
       
   181      * $param mixed $value The element to set.
       
   182      */
       
   183     public function hydrateSet($key, $element)
       
   184     {
       
   185         $this->coll->set($key, $element);
       
   186         // If _backRefFieldName is set, then the association is bidirectional
       
   187         // and we need to set the back reference.
       
   188         if ($this->backRefFieldName && $this->association['type'] == ClassMetadata::ONE_TO_MANY) {
       
   189             // Set back reference to owner
       
   190             $this->typeClass->reflFields[$this->backRefFieldName]
       
   191                     ->setValue($element, $this->owner);
       
   192         }
       
   193     }
       
   194 
       
   195     /**
       
   196      * Initializes the collection by loading its contents from the database
       
   197      * if the collection is not yet initialized.
       
   198      */
       
   199     public function initialize()
       
   200     {
       
   201         if ( ! $this->initialized && $this->association) {
       
   202             if ($this->isDirty) {
       
   203                 // Has NEW objects added through add(). Remember them.
       
   204                 $newObjects = $this->coll->toArray();
       
   205             }
       
   206             $this->coll->clear();
       
   207             $this->em->getUnitOfWork()->loadCollection($this);
       
   208             $this->takeSnapshot();
       
   209             // Reattach NEW objects added through add(), if any.
       
   210             if (isset($newObjects)) {
       
   211                 foreach ($newObjects as $obj) {
       
   212                     $this->coll->add($obj);
       
   213                 }
       
   214                 $this->isDirty = true;
       
   215             }
       
   216             $this->initialized = true;
       
   217         }
       
   218     }
       
   219 
       
   220     /**
       
   221      * INTERNAL:
       
   222      * Tells this collection to take a snapshot of its current state.
       
   223      */
       
   224     public function takeSnapshot()
       
   225     {
       
   226         $this->snapshot = $this->coll->toArray();
       
   227         $this->isDirty = false;
       
   228     }
       
   229 
       
   230     /**
       
   231      * INTERNAL:
       
   232      * Returns the last snapshot of the elements in the collection.
       
   233      *
       
   234      * @return array The last snapshot of the elements.
       
   235      */
       
   236     public function getSnapshot()
       
   237     {
       
   238         return $this->snapshot;
       
   239     }
       
   240 
       
   241     /**
       
   242      * INTERNAL:
       
   243      * getDeleteDiff
       
   244      *
       
   245      * @return array
       
   246      */
       
   247     public function getDeleteDiff()
       
   248     {
       
   249         return array_udiff_assoc($this->snapshot, $this->coll->toArray(),
       
   250                 function($a, $b) {return $a === $b ? 0 : 1;});
       
   251     }
       
   252 
       
   253     /**
       
   254      * INTERNAL:
       
   255      * getInsertDiff
       
   256      *
       
   257      * @return array
       
   258      */
       
   259     public function getInsertDiff()
       
   260     {
       
   261         return array_udiff_assoc($this->coll->toArray(), $this->snapshot,
       
   262                 function($a, $b) {return $a === $b ? 0 : 1;});
       
   263     }
       
   264 
       
   265     /**
       
   266      * INTERNAL: Gets the association mapping of the collection.
       
   267      *
       
   268      * @return Doctrine\ORM\Mapping\AssociationMapping
       
   269      */
       
   270     public function getMapping()
       
   271     {
       
   272         return $this->association;
       
   273     }
       
   274    
       
   275     /**
       
   276      * Marks this collection as changed/dirty.
       
   277      */
       
   278     private function changed()
       
   279     {
       
   280         if ( ! $this->isDirty) {
       
   281             $this->isDirty = true;
       
   282             if ($this->association !== null && $this->association['isOwningSide'] && $this->association['type'] == ClassMetadata::MANY_TO_MANY &&
       
   283                     $this->em->getClassMetadata(get_class($this->owner))->isChangeTrackingNotify()) {
       
   284                 $this->em->getUnitOfWork()->scheduleForDirtyCheck($this->owner);
       
   285             }
       
   286         }
       
   287     }
       
   288 
       
   289     /**
       
   290      * Gets a boolean flag indicating whether this collection is dirty which means
       
   291      * its state needs to be synchronized with the database.
       
   292      *
       
   293      * @return boolean TRUE if the collection is dirty, FALSE otherwise.
       
   294      */
       
   295     public function isDirty()
       
   296     {
       
   297         return $this->isDirty;
       
   298     }
       
   299 
       
   300     /**
       
   301      * Sets a boolean flag, indicating whether this collection is dirty.
       
   302      *
       
   303      * @param boolean $dirty Whether the collection should be marked dirty or not.
       
   304      */
       
   305     public function setDirty($dirty)
       
   306     {
       
   307         $this->isDirty = $dirty;
       
   308     }
       
   309     
       
   310     /**
       
   311      * Sets the initialized flag of the collection, forcing it into that state.
       
   312      * 
       
   313      * @param boolean $bool
       
   314      */
       
   315     public function setInitialized($bool)
       
   316     {
       
   317         $this->initialized = $bool;
       
   318     }
       
   319     
       
   320     /**
       
   321      * Checks whether this collection has been initialized.
       
   322      *
       
   323      * @return boolean
       
   324      */
       
   325     public function isInitialized()
       
   326     {
       
   327         return $this->initialized;
       
   328     }
       
   329 
       
   330     /** {@inheritdoc} */
       
   331     public function first()
       
   332     {
       
   333         $this->initialize();
       
   334         return $this->coll->first();
       
   335     }
       
   336 
       
   337     /** {@inheritdoc} */
       
   338     public function last()
       
   339     {
       
   340         $this->initialize();
       
   341         return $this->coll->last();
       
   342     }
       
   343 
       
   344     /**
       
   345      * {@inheritdoc}
       
   346      */
       
   347     public function remove($key)
       
   348     {
       
   349         // TODO: If the keys are persistent as well (not yet implemented)
       
   350         //       and the collection is not initialized and orphanRemoval is
       
   351         //       not used we can issue a straight SQL delete/update on the
       
   352         //       association (table). Without initializing the collection.
       
   353         $this->initialize();
       
   354         $removed = $this->coll->remove($key);
       
   355         if ($removed) {
       
   356             $this->changed();
       
   357             if ($this->association !== null && $this->association['type'] == ClassMetadata::ONE_TO_MANY &&
       
   358                     $this->association['orphanRemoval']) {
       
   359                 $this->em->getUnitOfWork()->scheduleOrphanRemoval($removed);
       
   360             }
       
   361         }
       
   362 
       
   363         return $removed;
       
   364     }
       
   365 
       
   366     /**
       
   367      * {@inheritdoc}
       
   368      */
       
   369     public function removeElement($element)
       
   370     {
       
   371         // TODO: Assuming the identity of entities in a collection is always based
       
   372         //       on their primary key (there is no equals/hashCode in PHP),
       
   373         //       if the collection is not initialized, we could issue a straight
       
   374         //       SQL DELETE/UPDATE on the association (table) without initializing
       
   375         //       the collection.
       
   376         /*if ( ! $this->initialized) {
       
   377             $this->em->getUnitOfWork()->getCollectionPersister($this->association)
       
   378                 ->deleteRows($this, $element);
       
   379         }*/
       
   380         
       
   381         $this->initialize();
       
   382         $removed = $this->coll->removeElement($element);
       
   383         if ($removed) {
       
   384             $this->changed();
       
   385             if ($this->association !== null && $this->association['type'] == ClassMetadata::ONE_TO_MANY &&
       
   386                     $this->association['orphanRemoval']) {
       
   387                 $this->em->getUnitOfWork()->scheduleOrphanRemoval($element);
       
   388             }
       
   389         }
       
   390         return $removed;
       
   391     }
       
   392 
       
   393     /**
       
   394      * {@inheritdoc}
       
   395      */
       
   396     public function containsKey($key)
       
   397     {
       
   398         $this->initialize();
       
   399         return $this->coll->containsKey($key);
       
   400     }
       
   401 
       
   402     /**
       
   403      * {@inheritdoc}
       
   404      */
       
   405     public function contains($element)
       
   406     {
       
   407         if (!$this->initialized && $this->association['fetch'] == Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
       
   408             return $this->coll->contains($element) ||
       
   409                    $this->em->getUnitOfWork()
       
   410                             ->getCollectionPersister($this->association)
       
   411                             ->contains($this, $element);
       
   412         }
       
   413         
       
   414         $this->initialize();
       
   415         return $this->coll->contains($element);
       
   416     }
       
   417 
       
   418     /**
       
   419      * {@inheritdoc}
       
   420      */
       
   421     public function exists(Closure $p)
       
   422     {
       
   423         $this->initialize();
       
   424         return $this->coll->exists($p);
       
   425     }
       
   426 
       
   427     /**
       
   428      * {@inheritdoc}
       
   429      */
       
   430     public function indexOf($element)
       
   431     {
       
   432         $this->initialize();
       
   433         return $this->coll->indexOf($element);
       
   434     }
       
   435 
       
   436     /**
       
   437      * {@inheritdoc}
       
   438      */
       
   439     public function get($key)
       
   440     {
       
   441         $this->initialize();
       
   442         return $this->coll->get($key);
       
   443     }
       
   444 
       
   445     /**
       
   446      * {@inheritdoc}
       
   447      */
       
   448     public function getKeys()
       
   449     {
       
   450         $this->initialize();
       
   451         return $this->coll->getKeys();
       
   452     }
       
   453 
       
   454     /**
       
   455      * {@inheritdoc}
       
   456      */
       
   457     public function getValues()
       
   458     {
       
   459         $this->initialize();
       
   460         return $this->coll->getValues();
       
   461     }
       
   462 
       
   463     /**
       
   464      * {@inheritdoc}
       
   465      */
       
   466     public function count()
       
   467     {
       
   468         if (!$this->initialized && $this->association['fetch'] == Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
       
   469             return $this->em->getUnitOfWork()
       
   470                         ->getCollectionPersister($this->association)
       
   471                         ->count($this) + $this->coll->count();
       
   472         }
       
   473 
       
   474         $this->initialize();
       
   475         return $this->coll->count();
       
   476     }
       
   477 
       
   478     /**
       
   479      * {@inheritdoc}
       
   480      */
       
   481     public function set($key, $value)
       
   482     {
       
   483         $this->initialize();
       
   484         $this->coll->set($key, $value);
       
   485         $this->changed();
       
   486     }
       
   487 
       
   488     /**
       
   489      * {@inheritdoc}
       
   490      */
       
   491     public function add($value)
       
   492     {
       
   493         $this->coll->add($value);
       
   494         $this->changed();
       
   495         return true;
       
   496     }
       
   497 
       
   498     /**
       
   499      * {@inheritdoc}
       
   500      */
       
   501     public function isEmpty()
       
   502     {
       
   503         $this->initialize();
       
   504         return $this->coll->isEmpty();
       
   505     }
       
   506     
       
   507     /**
       
   508      * {@inheritdoc}
       
   509      */
       
   510     public function getIterator()
       
   511     {
       
   512         $this->initialize();
       
   513         return $this->coll->getIterator();
       
   514     }
       
   515 
       
   516     /**
       
   517      * {@inheritdoc}
       
   518      */
       
   519     public function map(Closure $func)
       
   520     {
       
   521         $this->initialize();
       
   522         return $this->coll->map($func);
       
   523     }
       
   524 
       
   525     /**
       
   526      * {@inheritdoc}
       
   527      */
       
   528     public function filter(Closure $p)
       
   529     {
       
   530         $this->initialize();
       
   531         return $this->coll->filter($p);
       
   532     }
       
   533     
       
   534     /**
       
   535      * {@inheritdoc}
       
   536      */
       
   537     public function forAll(Closure $p)
       
   538     {
       
   539         $this->initialize();
       
   540         return $this->coll->forAll($p);
       
   541     }
       
   542 
       
   543     /**
       
   544      * {@inheritdoc}
       
   545      */
       
   546     public function partition(Closure $p)
       
   547     {
       
   548         $this->initialize();
       
   549         return $this->coll->partition($p);
       
   550     }
       
   551     
       
   552     /**
       
   553      * {@inheritdoc}
       
   554      */
       
   555     public function toArray()
       
   556     {
       
   557         $this->initialize();
       
   558         return $this->coll->toArray();
       
   559     }
       
   560 
       
   561     /**
       
   562      * {@inheritdoc}
       
   563      */
       
   564     public function clear()
       
   565     {
       
   566         if ($this->initialized && $this->isEmpty()) {
       
   567             return;
       
   568         }
       
   569         if ($this->association['type'] == ClassMetadata::ONE_TO_MANY && $this->association['orphanRemoval']) {
       
   570             foreach ($this->coll as $element) {
       
   571                 $this->em->getUnitOfWork()->scheduleOrphanRemoval($element);
       
   572             }
       
   573         }
       
   574         $this->coll->clear();
       
   575         $this->initialized = true; // direct call, {@link initialize()} is too expensive
       
   576         if ($this->association['isOwningSide']) {
       
   577             $this->changed();
       
   578             $this->em->getUnitOfWork()->scheduleCollectionDeletion($this);
       
   579             $this->takeSnapshot();
       
   580         }
       
   581     }
       
   582     
       
   583     /**
       
   584      * Called by PHP when this collection is serialized. Ensures that only the
       
   585      * elements are properly serialized.
       
   586      *
       
   587      * @internal Tried to implement Serializable first but that did not work well
       
   588      *           with circular references. This solution seems simpler and works well.
       
   589      */
       
   590     public function __sleep()
       
   591     {
       
   592         return array('coll', 'initialized');
       
   593     }
       
   594     
       
   595     /* ArrayAccess implementation */
       
   596 
       
   597     /**
       
   598      * @see containsKey()
       
   599      */
       
   600     public function offsetExists($offset)
       
   601     {
       
   602         return $this->containsKey($offset);
       
   603     }
       
   604 
       
   605     /**
       
   606      * @see get()
       
   607      */
       
   608     public function offsetGet($offset)
       
   609     {
       
   610         return $this->get($offset);
       
   611     }
       
   612 
       
   613     /**
       
   614      * @see add()
       
   615      * @see set()
       
   616      */
       
   617     public function offsetSet($offset, $value)
       
   618     {
       
   619         if ( ! isset($offset)) {
       
   620             return $this->add($value);
       
   621         }
       
   622         return $this->set($offset, $value);
       
   623     }
       
   624 
       
   625     /**
       
   626      * @see remove()
       
   627      */
       
   628     public function offsetUnset($offset)
       
   629     {
       
   630         return $this->remove($offset);
       
   631     }
       
   632     
       
   633     public function key()
       
   634     {
       
   635         return $this->coll->key();
       
   636     }
       
   637     
       
   638     /**
       
   639      * Gets the element of the collection at the current iterator position.
       
   640      */
       
   641     public function current()
       
   642     {
       
   643         return $this->coll->current();
       
   644     }
       
   645     
       
   646     /**
       
   647      * Moves the internal iterator position to the next element.
       
   648      */
       
   649     public function next()
       
   650     {
       
   651         return $this->coll->next();
       
   652     }
       
   653     
       
   654     /**
       
   655      * Retrieves the wrapped Collection instance.
       
   656      */
       
   657     public function unwrap()
       
   658     {
       
   659         return $this->coll;
       
   660     }
       
   661 
       
   662     /**
       
   663      * Extract a slice of $length elements starting at position $offset from the Collection.
       
   664      *
       
   665      * If $length is null it returns all elements from $offset to the end of the Collection.
       
   666      * Keys have to be preserved by this method. Calling this method will only return the
       
   667      * selected slice and NOT change the elements contained in the collection slice is called on.
       
   668      *
       
   669      * @param int $offset
       
   670      * @param int $length
       
   671      * @return array
       
   672      */
       
   673     public function slice($offset, $length = null)
       
   674     {
       
   675         if (!$this->initialized && $this->association['fetch'] == Mapping\ClassMetadataInfo::FETCH_EXTRA_LAZY) {
       
   676             return $this->em->getUnitOfWork()
       
   677                             ->getCollectionPersister($this->association)
       
   678                             ->slice($this, $offset, $length);
       
   679         }
       
   680 
       
   681         $this->initialize();
       
   682         return $this->coll->slice($offset, $length);
       
   683     }
       
   684 }