3
* $Id: Collection.php 5049 2008-10-04 20:51:17Z jwage $
5
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
6
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
7
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
8
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
9
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
10
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
11
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
12
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
13
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
14
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
15
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
17
* This software consists of voluntary contributions made by many individuals
18
* and is licensed under the LGPL. For more information, see
19
* <http://www.phpdoctrine.org>.
24
* Collection of Doctrine_Record objects.
27
* @subpackage Collection
28
* @license http://www.opensource.org/licenses/lgpl-license.php LGPL
29
* @link www.phpdoctrine.org
31
* @version $Revision: 5049 $
32
* @author Konsta Vesterinen <kvesteri@cc.hut.fi>
34
class Doctrine_Collection extends Doctrine_Access implements Countable, IteratorAggregate, Serializable
37
* @var array $data an array containing the records of this collection
39
protected $data = array();
42
* @var Doctrine_Table $table each collection has only records of specified table
47
* @var array $_snapshot a snapshot of the fetched data
49
protected $_snapshot = array();
52
* @var Doctrine_Record $reference collection can belong to a record
57
* @var string $referenceField the reference field of the collection
59
protected $referenceField;
62
* @var Doctrine_Relation the record this collection is related to, if any
67
* @var string $keyColumn the name of the column that is used for collection key mapping
72
* @var Doctrine_Null $null used for extremely fast null value testing
74
protected static $null;
79
* @param Doctrine_Table|string $table
81
public function __construct($table, $keyColumn = null)
83
if ( ! ($table instanceof Doctrine_Table)) {
84
$table = Doctrine::getTable($table);
87
$this->_table = $table;
89
if ($keyColumn === null) {
90
$keyColumn = $table->getBoundQueryPart('indexBy');
93
if ($keyColumn === null) {
94
$keyColumn = $table->getAttribute(Doctrine::ATTR_COLL_KEY);
97
if ($keyColumn !== null) {
98
$this->keyColumn = $keyColumn;
103
* Initializes the null object for this collection
107
public static function initNullObject(Doctrine_Null $null)
113
* Get the table this collection belongs to
115
* @return Doctrine_Table
117
public function getTable()
119
return $this->_table;
123
* Set the data for the Doctrin_Collection instance
126
* @return Doctrine_Collection
128
public function setData(array $data)
134
* This method is automatically called when this Doctrine_Collection is serialized
138
public function serialize()
140
$vars = get_object_vars($this);
142
unset($vars['reference']);
143
unset($vars['reference_field']);
144
unset($vars['relation']);
145
unset($vars['expandable']);
146
unset($vars['expanded']);
147
unset($vars['generator']);
149
$vars['_table'] = $vars['_table']->getComponentName();
151
return serialize($vars);
155
* This method is automatically called everytime a Doctrine_Collection object is unserialized
159
public function unserialize($serialized)
161
$manager = Doctrine_Manager::getInstance();
162
$connection = $manager->getCurrentConnection();
164
$array = unserialize($serialized);
166
foreach ($array as $name => $values) {
167
$this->$name = $values;
170
$this->_table = $connection->getTable($this->_table);
172
$keyColumn = isset($array['keyColumn']) ? $array['keyColumn'] : null;
173
if ($keyColumn === null) {
174
$keyColumn = $this->_table->getBoundQueryPart('indexBy');
177
if ($keyColumn !== null) {
178
$this->keyColumn = $keyColumn;
183
* Sets the key column for this collection
185
* @param string $column
186
* @return Doctrine_Collection $this
188
public function setKeyColumn($column)
190
$this->keyColumn = $column;
196
* Get the name of the key column
200
public function getKeyColumn()
202
return $this->keyColumn;
206
* Get all the records as an array
210
public function getData()
216
* Get the first record in the collection
220
public function getFirst()
222
return reset($this->data);
226
* Get the last record in the collection
230
public function getLast()
232
return end($this->data);
236
* Get the last record in the collection
240
public function end()
242
return end($this->data);
246
* Get the current key
250
public function key()
252
return key($this->data);
256
* Sets a reference pointer
260
public function setReference(Doctrine_Record $record, Doctrine_Relation $relation)
262
$this->reference = $record;
263
$this->relation = $relation;
265
if ($relation instanceof Doctrine_Relation_ForeignKey ||
266
$relation instanceof Doctrine_Relation_LocalKey) {
267
$this->referenceField = $relation->getForeignFieldName();
269
$value = $record->get($relation->getLocalFieldName());
271
foreach ($this->data as $record) {
272
if ($value !== null) {
273
$record->set($this->referenceField, $value, false);
275
$record->set($this->referenceField, $this->reference, false);
278
} elseif ($relation instanceof Doctrine_Relation_Association) {
284
* Get reference to Doctrine_Record instance
286
* @return Doctrine_Record $reference
288
public function getReference()
290
return $this->reference;
294
* Removes a specified collection element
299
public function remove($key)
301
$removed = $this->data[$key];
303
unset($this->data[$key]);
308
* Whether or not this collection contains a specified element
310
* @param mixed $key the key of the element
313
public function contains($key)
315
return isset($this->data[$key]);
319
* Search a Doctrine_Record instance
321
* @param string $Doctrine_Record
324
public function search(Doctrine_Record $record)
326
return array_search($record, $this->data, true);
330
* Gets a record for given key
332
* There are two special cases:
334
* 1. if null is given as a key a new record is created and attached
335
* at the end of the collection
337
* 2. if given key does not exist, then a new record is create and attached
340
* Collection also maps referential information to newly created records
342
* @param mixed $key the key of the element
343
* @return Doctrine_Record return a specified record
345
public function get($key)
347
if ( ! isset($this->data[$key])) {
348
$record = $this->_table->create();
350
if (isset($this->referenceField)) {
351
$value = $this->reference->get($this->relation->getLocalFieldName());
353
if ($value !== null) {
354
$record->set($this->referenceField, $value, false);
356
$record->set($this->referenceField, $this->reference, false);
360
$this->data[] = $record;
362
$this->data[$key] = $record;
365
if (isset($this->keyColumn)) {
366
$record->set($this->keyColumn, $key);
372
return $this->data[$key];
376
* Get array of primary keys for all the records in the collection
378
* @return array an array containing all primary keys
380
public function getPrimaryKeys()
383
$name = $this->_table->getIdentifier();
385
foreach ($this->data as $record) {
386
if (is_array($record) && isset($record[$name])) {
387
$list[] = $record[$name];
389
$list[] = $record->getIncremented();
396
* Get all keys of the data in the collection
400
public function getKeys()
402
return array_keys($this->data);
406
* Gets the number of records in this collection
407
* This class implements interface countable
411
public function count()
413
return count($this->data);
417
* Set a Doctrine_Record instance to the collection
419
* @param integer $key
420
* @param Doctrine_Record $record
423
public function set($key, $record)
425
if (isset($this->referenceField)) {
426
$record->set($this->referenceField, $this->reference, false);
429
$this->data[$key] = $record;
433
* Adds a record to collection
435
* @param Doctrine_Record $record record to be added
436
* @param string $key optional key for the record
439
public function add($record, $key = null)
441
if (isset($this->referenceField)) {
442
$value = $this->reference->get($this->relation->getLocalFieldName());
443
if ($value !== null) {
444
$record->set($this->referenceField, $value, false);
446
$record->set($this->referenceField, $this->reference, false);
448
$relations = $this->relation['table']->getRelations();
449
foreach ($relations as $relation) {
450
if ($this->relation['class'] == $relation['localTable']->getOption('name') && $relation->getLocal() == $this->relation->getForeignFieldName()) {
451
$record->$relation['alias'] = $this->reference;
457
* for some weird reason in_array cannot be used here (php bug ?)
459
* if used it results in fatal error : [ nesting level too deep ]
461
foreach ($this->data as $val) {
462
if ($val === $record) {
468
if (isset($this->data[$key])) {
471
$this->data[$key] = $record;
475
if (isset($this->keyColumn)) {
476
$value = $record->get($this->keyColumn);
477
if ($value === null) {
478
throw new Doctrine_Collection_Exception("Couldn't create collection index. Record field '".$this->keyColumn."' was null.");
480
$this->data[$value] = $record;
482
$this->data[] = $record;
489
* Merges collection into $this and returns merged collection
491
* @param Doctrine_Collection $coll
492
* @return Doctrine_Collection
494
public function merge(Doctrine_Collection $coll)
496
$localBase = $this->getTable()->getComponentName();
497
$otherBase = $coll->getTable()->getComponentName();
499
if ($otherBase != $localBase && !is_subclass_of($otherBase, $localBase) ) {
500
throw new Doctrine_Collection_Exception("Can't merge collections with incompatible record types");
503
foreach ($coll->getData() as $record) {
511
* Load all relationships or the named relationship passed
516
public function loadRelated($name = null)
519
$query = new Doctrine_Query($this->_table->getConnection());
521
if ( ! isset($name)) {
522
foreach ($this->data as $record) {
523
$value = $record->getIncremented();
524
if ($value !== null) {
528
$query->from($this->_table->getComponentName());
529
$query->where($this->_table->getComponentName() . '.id IN (' . substr(str_repeat("?, ", count($list)),0,-2) . ')');
534
$rel = $this->_table->getRelation($name);
536
if ($rel instanceof Doctrine_Relation_LocalKey || $rel instanceof Doctrine_Relation_ForeignKey) {
537
foreach ($this->data as $record) {
538
$list[] = $record[$rel->getLocal()];
541
foreach ($this->data as $record) {
542
$value = $record->getIncremented();
543
if ($value !== null) {
549
$dql = $rel->getRelationDql(count($list), 'collection');
551
$coll = $query->query($dql, $list);
553
$this->populateRelated($name, $coll);
557
* Populate the relationship $name for all records in the passed collection
559
* @param string $name
560
* @param Doctrine_Collection $coll
563
public function populateRelated($name, Doctrine_Collection $coll)
565
$rel = $this->_table->getRelation($name);
566
$table = $rel->getTable();
567
$foreign = $rel->getForeign();
568
$local = $rel->getLocal();
570
if ($rel instanceof Doctrine_Relation_LocalKey) {
571
foreach ($this->data as $key => $record) {
572
foreach ($coll as $k => $related) {
573
if ($related[$foreign] == $record[$local]) {
574
$this->data[$key]->setRelated($name, $related);
578
} elseif ($rel instanceof Doctrine_Relation_ForeignKey) {
579
foreach ($this->data as $key => $record) {
580
if ( ! $record->exists()) {
583
$sub = new Doctrine_Collection($table);
585
foreach ($coll as $k => $related) {
586
if ($related[$foreign] == $record[$local]) {
592
$this->data[$key]->setRelated($name, $sub);
594
} elseif ($rel instanceof Doctrine_Relation_Association) {
595
$identifier = $this->_table->getIdentifier();
596
$asf = $rel->getAssociationFactory();
597
$name = $table->getComponentName();
599
foreach ($this->data as $key => $record) {
600
if ( ! $record->exists()) {
603
$sub = new Doctrine_Collection($table);
604
foreach ($coll as $k => $related) {
605
if ($related->get($local) == $record[$identifier]) {
606
$sub->add($related->get($name));
609
$this->data[$key]->setRelated($name, $sub);
616
* Get normal iterator - an iterator that will not expand this collection
618
* @return Doctrine_Iterator_Normal $iterator
620
public function getNormalIterator()
622
return new Doctrine_Collection_Iterator_Normal($this);
626
* Takes a snapshot from this collection
628
* snapshots are used for diff processing, for example
629
* when a fetched collection has three elements, then two of those
630
* are being removed the diff would contain one element
632
* Doctrine_Collection::save() attaches the diff with the help of last
635
* @return Doctrine_Collection
637
public function takeSnapshot()
639
$this->_snapshot = $this->data;
645
* Gets the data of the last snapshot
647
* @return array returns the data in last snapshot
649
public function getSnapshot()
651
return $this->_snapshot;
655
* Processes the difference of the last snapshot and the current data
658
* Snapshot with the objects 1, 2 and 4
659
* Current data with objects 2, 3 and 5
661
* The process would remove object 4
663
* @return Doctrine_Collection
665
public function processDiff()
667
foreach (array_udiff($this->_snapshot, $this->data, array($this, "compareRecords")) as $record) {
675
* Mimics the result of a $query->execute(array(), Doctrine::HYDRATE_ARRAY);
677
* @param boolean $deep
679
public function toArray($deep = false, $prefixKey = false)
682
foreach ($this as $key => $record) {
684
$key = $prefixKey ? get_class($record) . '_' .$key:$key;
686
$data[$key] = $record->toArray($deep, $prefixKey);
693
* Populate a Doctrine_Collection from an array of data
695
* @param string $array
698
public function fromArray($array, $deep = true)
701
foreach ($array as $rowKey => $row) {
702
$this[$rowKey]->fromArray($row, $deep);
707
* synchronizes a Doctrine_Collection with data from an array
709
* it expects an array representation of a Doctrine_Collection similar to the return
710
* value of the toArray() method. It will create Dectrine_Records that don't exist
711
* on the collection, update the ones that do and remove the ones missing in the $array
713
* @param array $array representation of a Doctrine_Collection
715
public function synchronizeWithArray(array $array)
717
foreach ($this as $key => $record) {
718
if (isset($array[$key])) {
719
$record->synchronizeWithArray($array[$key]);
722
// remove records that don't exist in the array
726
// create new records for each new row in the array
727
foreach ($array as $rowKey => $row) {
728
$this[$rowKey]->fromArray($row);
731
public function synchronizeFromArray(array $array)
733
return $this->synchronizeWithArray($array);
737
* Export a Doctrine_Collection to one of the supported Doctrine_Parser formats
739
* @param string $type
740
* @param string $deep
743
public function exportTo($type, $deep = false)
745
if ($type == 'array') {
746
return $this->toArray($deep);
748
return Doctrine_Parser::dump($this->toArray($deep, true), $type);
753
* Import data to a Doctrine_Collection from one of the supported Doctrine_Parser formats
755
* @param string $type
756
* @param string $data
759
public function importFrom($type, $data)
761
if ($type == 'array') {
762
return $this->fromArray($data);
764
return $this->fromArray(Doctrine_Parser::load($data, $type));
769
* Perform a delete diff between the last snapshot and the current data
771
* @return array $diff
773
public function getDeleteDiff()
775
return array_udiff($this->_snapshot, $this->data, array($this, 'compareRecords'));
779
* Perform a insert diff between the last snapshot and the current data
781
* @return array $diff
783
public function getInsertDiff()
785
return array_udiff($this->data, $this->_snapshot, array($this, "compareRecords"));
789
* Compares two records. To be used on _snapshot diffs using array_udiff
791
* @param Doctrine_Record $a
792
* @param Doctrine_Record $b
795
protected function compareRecords($a, $b)
797
if ($a->getOid() == $b->getOid()) {
801
return ($a->getOid() > $b->getOid()) ? 1 : -1;
805
* Saves all records of this collection and processes the
806
* difference of the last snapshot and the current data
808
* @param Doctrine_Connection $conn optional connection parameter
809
* @return Doctrine_Collection
811
public function save(Doctrine_Connection $conn = null, $processDiff = true)
814
$conn = $this->_table->getConnection();
818
$conn->beginInternalTransaction();
820
$conn->transaction->addCollection($this);
823
$this->processDiff();
826
foreach ($this->getData() as $key => $record) {
827
$record->save($conn);
831
} catch (Exception $e) {
840
* Deletes all records from this collection
842
* @return Doctrine_Collection
844
public function delete(Doctrine_Connection $conn = null, $clearColl = true)
847
$conn = $this->_table->getConnection();
851
$conn->beginInternalTransaction();
852
$conn->transaction->addCollection($this);
854
foreach ($this as $key => $record) {
855
$record->delete($conn);
859
} catch (Exception $e) {
872
* Clears the collection.
876
public function clear()
878
$this->data = array();
882
* Frees the resources used by the collection.
883
* WARNING: After invoking free() the collection is no longer considered to
884
* be in a useable state. Subsequent usage may result in unexpected behavior.
888
public function free($deep = false)
890
foreach ($this->getData() as $key => $record) {
891
if ( ! ($record instanceof Doctrine_Null)) {
892
$record->free($deep);
896
$this->data = array();
898
if ($this->reference) {
899
$this->reference->free($deep);
900
$this->reference = null;
905
* Get collection data iterator
907
* @return object ArrayIterator
909
public function getIterator()
912
return new ArrayIterator($data);
916
* Returns a string representation of this object
918
* @return string $string
920
public function __toString()
922
return Doctrine_Lib::getCollectionAsString($this);
926
* Returns the relation object
928
* @return object Doctrine_Relation
930
public function getRelation()
932
return $this->relation;