Record.class.php 35.5 KB
Newer Older
doctrine's avatar
doctrine committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
<?php
require_once("Access.class.php");
/**
 * Doctrine_Record
 */
abstract class Doctrine_Record extends Doctrine_Access implements Countable, IteratorAggregate {
    /**
     * STATE CONSTANTS
     */

    /**
     * DIRTY STATE
     * a Doctrine_Record is in dirty state when its properties are changed
     */
    const STATE_DIRTY       = 1;
    /**
     * TDIRTY STATE
     * a Doctrine_Record is in transient dirty state when it is created and some of its fields are modified
     * but it is NOT yet persisted into database
     */
    const STATE_TDIRTY      = 2;
    /**
     * CLEAN STATE
     * a Doctrine_Record is in clean state when all of its properties are loaded from the database
     * and none of its properties are changed
     */
    const STATE_CLEAN       = 3;
    /**
     * PROXY STATE
     * a Doctrine_Record is in proxy state when its properties are not fully loaded
     */
    const STATE_PROXY       = 4;
    /**
     * NEW TCLEAN
     * a Doctrine_Record is in transient clean state when it is created and none of its fields are modified
     */
    const STATE_TCLEAN      = 5;
    /**
     * DELETED STATE
     * a Doctrine_Record turns into deleted state when it is deleted
     */
    const STATE_DELETED     = 6;

    /**
     * FETCHMODE CONSTANTS
     */

    /**
     * @var object Doctrine_Table $table    the factory that created this data access object
     */
    protected $table;
    /**
     * @var integer $id                     the primary key of this object
     */
    protected $id;
    /**
57
     * @var array $data                     the record data
doctrine's avatar
doctrine committed
58 59 60 61 62 63 64 65
     */
    protected $data       = array();

    /**
     * @var array $modified                 an array containing properties that have been modified
     */
    private $modified   = array();
    /**
66
     * @var integer $state                  the state of this record
doctrine's avatar
doctrine committed
67 68 69 70
     * @see STATE_* constants
     */
    private $state;
    /**
71
     * @var array $collections              the collections this record is in
doctrine's avatar
doctrine committed
72 73 74 75 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
     */
    private $collections = array();
    /**
     * @var mixed $references               an array containing all the references
     */
    private $references  = array();
    /**
     * @var mixed $originals                an array containing all the original references
     */
    private $originals   = array();
    /**
     * @var integer $index                  this index is used for creating object identifiers
     */
    private static $index = 1;
    /**
     * @var integer $oid                    object identifier
     */
    private $oid;

    /**
     * constructor
     * @param Doctrine_Table $table         a Doctrine_Table object
     * @throws Doctrine_Session_Exception   if object is created using the new operator and there are no
     *                                      open sessions
     */
    public function __construct($table = null) {
        if(isset($table) && $table instanceof Doctrine_Table) {
            $this->table = $table;
            $exists  = ( ! $this->table->isNewEntry());
        } else {
            $this->table = Doctrine_Manager::getInstance()->getCurrentSession()->getTable(get_class($this));
            $exists  = false;
        }

        // Check if the current session has the records table in its registry
        // If not this is record is only used for creating table definition and setting up
        // relations.

        if($this->table->getSession()->hasTable($this->table->getComponentName())) {

            $this->oid = self::$index;
    
            self::$index++;

116
            $keys = $this->table->getPrimaryKeys();
doctrine's avatar
doctrine committed
117 118 119 120 121 122 123 124 125 126 127 128 129

            if( ! $exists) {
                // listen the onPreCreate event
                $this->table->getAttribute(Doctrine::ATTR_LISTENER)->onPreCreate($this);
            } else {
                // listen the onPreLoad event
                $this->table->getAttribute(Doctrine::ATTR_LISTENER)->onPreLoad($this);
            }
            // get the data array
            $this->data = $this->table->getData();
    
            // clean data array
            $cols = $this->cleanData();
130 131 132

            $this->prepareIdentifiers($exists);

doctrine's avatar
doctrine committed
133 134 135 136 137 138
            if( ! $exists) {
    
                if($cols > 0)
                    $this->state = Doctrine_Record::STATE_TDIRTY;
                else
                    $this->state = Doctrine_Record::STATE_TCLEAN;
139

doctrine's avatar
doctrine committed
140 141
                // listen the onCreate event
                $this->table->getAttribute(Doctrine::ATTR_LISTENER)->onCreate($this);
142

doctrine's avatar
doctrine committed
143
            } else {
144
                $this->state      = Doctrine_Record::STATE_CLEAN;
doctrine's avatar
doctrine committed
145 146 147 148

                if($cols <= 1)
                    $this->state  = Doctrine_Record::STATE_PROXY;

149

doctrine's avatar
doctrine committed
150 151 152 153 154 155 156 157 158 159 160 161 162
                // listen the onLoad event
                $this->table->getAttribute(Doctrine::ATTR_LISTENER)->onLoad($this);
            }
            $this->table->getRepository()->add($this);
        }
    }
    /** 
     * setUp
     * implemented by child classes
     */
    public function setUp() { }
    /**
     * return the object identifier
163
     *
doctrine's avatar
doctrine committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
     * @return integer
     */
    public function getOID() {
        return $this->oid;
    }
    /**
     * cleanData
     * modifies data array
     * example:
     *
     * $data = array("name"=>"John","lastname"=> null,"id"=>1,"unknown"=>"unknown");
     * $names = array("name","lastname","id");
     * $data after operation:
     * $data = array("name"=>"John","lastname" => array(),"id"=>1);
     */
    private function cleanData() {
        $cols = 0;
        $tmp  = $this->data;
        
        $this->data = array();

        foreach($this->table->getColumnNames() as $name) {
            if( ! isset($tmp[$name])) {
                $this->data[$name] = array();

            } else {
                $cols++;
                $this->data[$name] = $tmp[$name];
            }
        }

        return $cols;
    }
197
    /**
198 199
     * prepares identifiers
     *
200 201
     * @return void
     */
202
    private function prepareIdentifiers($exists = true) {
203 204 205
        switch($this->table->getIdentifierType()):
            case Doctrine_Identifier::AUTO_INCREMENT:
            case Doctrine_Identifier::SEQUENCE:
206 207
                if($exists) {
                    $name = $this->table->getIdentifier();
doctrine's avatar
doctrine committed
208

209 210 211 212 213 214 215 216 217
                    if(isset($this->data[$name]))
                        $this->id = $this->data[$name];
    
                    unset($this->data[$name]);
                }
            break;
            case Doctrine_Identifier::COMPOSITE:
                $names      = $this->table->getIdentifier();
                $this->id   = array();
218

219 220 221
                foreach($names as $name) {
                    $this->id[$name] = isset($this->data[$name])?$this->data[$name]:null;
                }
222 223 224
            break;
        endswitch;
    }
doctrine's avatar
doctrine committed
225 226
    /**
     * this method is automatically called when this Doctrine_Record is serialized
227 228
     *
     * @return array
doctrine's avatar
doctrine committed
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
     */
    public function __sleep() {
        $this->table->getAttribute(Doctrine::ATTR_LISTENER)->onSleep($this);

        $this->table = $this->table->getComponentName();
        // unset all vars that won't need to be serialized

        unset($this->modified);
        unset($this->associations);
        unset($this->state);
        unset($this->collections);
        unset($this->references);    
        unset($this->originals);
        unset($this->oid);

        foreach($this->data as $k=>$v) {
            if($v instanceof Doctrine_Record)
                $this->data[$k] = array();
        }
        return array_keys(get_object_vars($this));
doctrine's avatar
doctrine committed
249

doctrine's avatar
doctrine committed
250 251
    }
    /**
doctrine's avatar
doctrine committed
252
     * unseralize
doctrine's avatar
doctrine committed
253
     * this method is automatically called everytime a Doctrine_Record object is unserialized
254 255
     *
     * @return void
doctrine's avatar
doctrine committed
256 257
     */
    public function __wakeup() {
doctrine's avatar
doctrine committed
258

doctrine's avatar
doctrine committed
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
        $this->modified = array();
        $this->state    = Doctrine_Record::STATE_CLEAN;

        $name       = $this->table;

        $manager    = Doctrine_Manager::getInstance();
        $sess       = $manager->getCurrentSession();

        $this->oid  = self::$index;
        self::$index++;

        $this->table = $sess->getTable($name);

        $this->table->getRepository()->add($this);

        $this->cleanData();

276 277
        //unset($this->data['id']);
        
doctrine's avatar
doctrine committed
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
        $this->table->getAttribute(Doctrine::ATTR_LISTENER)->onWakeUp($this);

    }
    /**
     * addCollection
     * @param Doctrine_Collection $collection
     * @param mixed $key
     */
    final public function addCollection(Doctrine_Collection $collection,$key = null) {
        if($key !== null) {
            if(isset($this->collections[$key])) 
                throw InvalidKeyException();

            $this->collections[$key] = $collection;
        } else {
            $this->collections[] = $collection;
        }
    }
    /**
     * getCollection
     * @param integer $key
     * @return Doctrine_Collection
     */
    final public function getCollection($key) {
        return $this->collections[$key];
    }
    /**
     * hasCollections
doctrine's avatar
doctrine committed
306 307 308
     * whether or not this record is part of a collection
     *
     * @return boolean
doctrine's avatar
doctrine committed
309 310 311 312 313 314
     */
    final public function hasCollections() {
        return (! empty($this->collections));
    }
    /**
     * getState
doctrine's avatar
doctrine committed
315 316
     * returns the current state of the object
     *
doctrine's avatar
doctrine committed
317
     * @see Doctrine_Record::STATE_* constants
doctrine's avatar
doctrine committed
318
     * @return integer
doctrine's avatar
doctrine committed
319 320 321 322 323
     */
    final public function getState() {
        return $this->state;
    }
    /**
doctrine's avatar
doctrine committed
324 325 326
     * refresh   
     * refresh internal data from the database
     *
doctrine's avatar
doctrine committed
327 328 329
     * @return boolean
     */
    final public function refresh() {
330 331 332 333 334 335 336 337
        $id = $this->getID();
        if( ! is_array($id))
            $id = array($id);

        if(empty($id))
            return false;

        $id = array_values($id);
doctrine's avatar
doctrine committed
338 339

        $query          = $this->table->getQuery()." WHERE ".implode(" = ? && ",$this->table->getPrimaryKeys())." = ?";
340
        $this->data     = $this->table->getSession()->execute($query,$id)->fetch(PDO::FETCH_ASSOC);
341

doctrine's avatar
doctrine committed
342 343
        $this->modified = array();
        $this->cleanData();
doctrine's avatar
doctrine committed
344

345 346
        $this->prepareIdentifiers();

doctrine's avatar
doctrine committed
347 348 349 350 351 352 353 354 355 356 357
        $this->state    = Doctrine_Record::STATE_CLEAN;

        return true;
    }
    /**
     * factoryRefresh
     * @throws Doctrine_Exception
     * @return void
     */
    final public function factoryRefresh() {
        $data = $this->table->getData();
358 359 360
        $id   = $this->id;
        
        $this->prepareIdentifiers();
doctrine's avatar
doctrine committed
361

362
        if($this->id != $id)
doctrine's avatar
doctrine committed
363 364
            throw new Doctrine_Refresh_Exception();

doctrine's avatar
doctrine committed
365
        $this->data     = $data;
doctrine's avatar
doctrine committed
366

doctrine's avatar
doctrine committed
367
        $this->cleanData();
doctrine's avatar
doctrine committed
368

doctrine's avatar
doctrine committed
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
        $this->state    = Doctrine_Record::STATE_CLEAN;
        $this->modified = array();
    }
    /**
     * return the factory that created this data access object
     * @return object Doctrine_Table        a Doctrine_Table object
     */
    final public function getTable() {
        return $this->table;
    }
    /**
     * return all the internal data
     * @return array                    an array containing all the properties
     */
    final public function getData() {
        return $this->data;
    }
    /**
     * get
doctrine's avatar
doctrine committed
388
     * returns a value of a property or a related component 
doctrine's avatar
doctrine committed
389 390 391 392 393 394 395 396 397
     *
     * @param $name                     name of the property or related component
     * @throws InvalidKeyException
     * @return mixed
     */
    public function get($name) {
        if(isset($this->data[$name])) {

            // check if the property is not loaded (= it is an empty array)
doctrine's avatar
doctrine committed
398
            if(is_array($this->data[$name])) {
doctrine's avatar
doctrine committed
399 400

                // no use trying to load the data from database if the Doctrine_Record is not a proxy
401
                if($this->state == Doctrine_Record::STATE_PROXY) {   
doctrine's avatar
doctrine committed
402 403 404
                    if( ! empty($this->collections)) {
                        foreach($this->collections as $collection) {
                            $collection->load($this);
doctrine's avatar
doctrine committed
405
                        }
doctrine's avatar
doctrine committed
406 407
                    } else {
                        $this->refresh();
doctrine's avatar
doctrine committed
408
                    }
doctrine's avatar
doctrine committed
409
                    $this->state = Doctrine_Record::STATE_CLEAN;
doctrine's avatar
doctrine committed
410
                }
doctrine's avatar
doctrine committed
411

doctrine's avatar
doctrine committed
412 413 414 415 416
                if(is_array($this->data[$name]))
                    return null;
            }
            return $this->data[$name];
        }
417

418
        if($name == $this->table->getIdentifier())
doctrine's avatar
doctrine committed
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
            return $this->id;

        if( ! isset($this->references[$name]))
                $this->loadReference($name);


        return $this->references[$name];
    }
    /**
     * rawSet
     * doctrine uses this function internally, not recommended for developers
     *
     * @param mixed $name               name of the property or reference
     * @param mixed $value              value of the property or reference
     */
    final public function rawSet($name,$value) {
        if($value instanceof Doctrine_Record)
            $id = $value->getID();

        if( ! empty($id))
            $value = $id;
doctrine's avatar
doctrine committed
440 441 442 443 444 445 446 447 448 449 450 451 452
            
        if(isset($this->data[$name])) {
            if( ! is_array($this->data[$name])) {
                if($this->data[$name] !== $value) {
                    switch($this->state):
                        case Doctrine_Record::STATE_CLEAN:
                            $this->state = Doctrine_Record::STATE_DIRTY;
                        break;
                        case Doctrine_Record::STATE_TCLEAN:
                            $this->state = Doctrine_Record::STATE_TDIRTY;
                    endswitch;
                }
            }
doctrine's avatar
doctrine committed
453 454 455 456

            if($this->state == Doctrine_Record::STATE_TCLEAN)
                $this->state = Doctrine_Record::STATE_TDIRTY;

doctrine's avatar
doctrine committed
457 458 459
            $this->data[$name] = $value;
            $this->modified[]  = $name;
        }
doctrine's avatar
doctrine committed
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    }
    /**
     * set
     * method for altering properties and Doctrine_Record references
     *
     * @param mixed $name               name of the property or reference
     * @param mixed $value              value of the property or reference
     * @throws InvalidKeyException
     * @throws InvalidTypeException
     * @return void
     */
    public function set($name,$value) {
        if(isset($this->data[$name])) {

            if($value instanceof Doctrine_Record) {
                $id = $value->getID();
                
                if( ! empty($id)) 
                    $value = $value->getID();
            }
doctrine's avatar
doctrine committed
480 481
            
            $old = $this->get($name);
doctrine's avatar
doctrine committed
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504

            if($old !== $value) {
                $this->data[$name] = $value;
                $this->modified[]  = $name;
                switch($this->state):
                    case Doctrine_Record::STATE_CLEAN:
                    case Doctrine_Record::STATE_PROXY:
                        $this->state = Doctrine_Record::STATE_DIRTY;
                    break;
                    case Doctrine_Record::STATE_TCLEAN:
                        $this->state = Doctrine_Record::STATE_TDIRTY;
                    break;
                endswitch;
            }
        } else {
            // if not found, throws InvalidKeyException

            $fk = $this->table->getForeignKey($name);

            // one-to-many or one-to-one relation
            if($fk instanceof Doctrine_ForeignKey || 
               $fk instanceof Doctrine_LocalKey) {
                switch($fk->getType()):
505 506
                    case Doctrine_Relation::MANY_COMPOSITE:
                    case Doctrine_Relation::MANY_AGGREGATE:
doctrine's avatar
doctrine committed
507 508
                        // one-to-many relation found
                        if( ! ($value instanceof Doctrine_Collection))
509
                            throw new Doctrine_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references.");
doctrine's avatar
doctrine committed
510 511 512

                        $value->setReference($this,$fk);
                    break;
513 514
                    case Doctrine_Relation::ONE_COMPOSITE:
                    case Doctrine_Relation::ONE_AGGREGATE:
doctrine's avatar
doctrine committed
515 516
                        // one-to-one relation found
                        if( ! ($value instanceof Doctrine_Record))
517
                            throw new Doctrine_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Record when setting one-to-one references.");
doctrine's avatar
doctrine committed
518

519
                        if($fk->getLocal() == $this->table->getIdentifier()) {
doctrine's avatar
doctrine committed
520 521 522 523 524 525 526 527
                            $this->references[$name]->set($fk->getForeign(),$this);
                        } else {
                            $this->set($fk->getLocal(),$value);
                        }
                    break;
                endswitch;

            } elseif($fk instanceof Doctrine_Association) {
528
                // join table relation found
doctrine's avatar
doctrine committed
529
                if( ! ($value instanceof Doctrine_Collection))
530
                    throw new Doctrine_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references.");
doctrine's avatar
doctrine committed
531 532 533 534 535
            }

            $this->references[$name] = $value;
        }
    }
doctrine's avatar
doctrine committed
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560
    /**
     * __isset
     *
     * @param string $name
     * @return boolean
     */
    public function __isset($name) {
        if(isset($this->data[$name]))
            return true;

        if(isset($this->references[$name]))
            return true;

        return false;
    }
    /**
     * @param string $name
     * @return void
     */
    public function __unset($name) {
        if(isset($this->data[$name]))
            $this->data[$name] = array();

        // todo: what to do with references ?
    }
doctrine's avatar
doctrine committed
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
    /**
     * applies the changes made to this object into database
     * this method is smart enough to know if any changes are made
     * and whether to use INSERT or UPDATE statement
     *
     * this method also saves the related composites
     *
     * @return void
     */
    final public function save() {
        $this->table->getSession()->beginTransaction();

        // listen the onPreSave event
        $this->table->getAttribute(Doctrine::ATTR_LISTENER)->onPreSave($this);

        $saveLater = $this->table->getSession()->saveRelated($this);

        $this->table->getSession()->save($this);

        foreach($saveLater as $fk) {
doctrine's avatar
doctrine committed
581

doctrine's avatar
doctrine committed
582 583 584 585
            $table = $fk->getTable();
            $foreign = $fk->getForeign();
            $local   = $fk->getLocal();

doctrine's avatar
doctrine committed
586 587 588 589
            $alias   = $this->table->getAlias($table->getComponentName());

            if(isset($this->references[$alias])) {
                $obj = $this->references[$alias];
doctrine's avatar
doctrine committed
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
                $obj->save();
            }
        }

        // save the MANY-TO-MANY associations

        $this->saveAssociations();
            
        $this->table->getSession()->commit();
    }
    /**
     * returns an array of modified fields and associated values
     * @return array
     */
    final public function getModified() {
        $a = array();

        foreach($this->modified as $k=>$v) {
            $a[$v] = $this->data[$v];
        }
        return $a;
    }
612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
    /**
     * returns an array of modified fields and values with data preparation
     * adds column aggregation inheritance and converts Records into primary key values
     *
     * @return array
     */
    final public function getPrepared() {
        $a = array();

        foreach($this->table->getInheritanceMap() as $k => $v) {
            $this->set($k,$v);                                                       	
        }

        foreach($this->modified as $k => $v) {
            if($this->data[$v] instanceof Doctrine_Record) {
                $this->data[$v] = $this->data[$v]->getID();
            }
            $a[$v] = $this->data[$v];
        }

        return $a;
    }
doctrine's avatar
doctrine committed
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
    /**
     * this class implements countable interface
     * @return integer                      the number of columns
     */
    public function count() {
        return count($this->data);
    }
    /**
     * getIterator
     * @return ArrayIterator                an ArrayIterator that iterates through the data
     */
    public function getIterator() {
        return new ArrayIterator($this->data);
    }
    /**
     * saveAssociations
     * save the associations of many-to-many relations
     * this method also deletes associations that do not exist anymore
     * @return void
     */
    final public function saveAssociations() {
        foreach($this->table->getForeignKeys() as $fk):
656
            $table   = $fk->getTable();
doctrine's avatar
doctrine committed
657
            $name    = $table->getComponentName();
658
            $alias   = $this->table->getAlias($name);
doctrine's avatar
doctrine committed
659

doctrine's avatar
doctrine committed
660 661
            if($fk instanceof Doctrine_Association) {
                switch($fk->getType()):
662
                    case Doctrine_Relation::MANY_COMPOSITE:
doctrine's avatar
doctrine committed
663 664

                    break;
665
                    case Doctrine_Relation::MANY_AGGREGATE:
doctrine's avatar
doctrine committed
666 667
                        $asf     = $fk->getAssociationFactory();

668
                        if(isset($this->references[$alias])) {
doctrine's avatar
doctrine committed
669

670 671 672 673
                            $new = $this->references[$alias];

                            if( ! isset($this->originals[$alias])) {
                                $this->loadReference($alias);
doctrine's avatar
doctrine committed
674 675
                            }

676
                            $r = $this->getRelationOperations($alias,$new);
doctrine's avatar
doctrine committed
677 678 679 680 681 682 683 684 685 686 687 688

                            foreach($r["delete"] as $record) {
                                $query = "DELETE FROM ".$asf->getTableName()." WHERE ".$fk->getForeign()." = ?"
                                                                            ." && ".$fk->getLocal()." = ?";
                                $this->table->getSession()->execute($query, array($record->getID(),$this->getID()));
                            }
                            foreach($r["add"] as $record) {
                                $reldao = $asf->create();
                                $reldao->set($fk->getForeign(),$record);
                                $reldao->set($fk->getLocal(),$this);
                                $reldao->save();
                            }  
689
                            $this->originals[$alias] = clone $this->references[$alias];
doctrine's avatar
doctrine committed
690 691 692 693 694 695 696
                        }
                    break;
                endswitch;
            } elseif($fk instanceof Doctrine_ForeignKey || 
                     $fk instanceof Doctrine_LocalKey) {
                
                switch($fk->getType()):
697
                    case Doctrine_Relation::ONE_COMPOSITE:
698 699
                        if(isset($this->originals[$alias]) && $this->originals[$alias]->getID() != $this->references[$alias]->getID())
                            $this->originals[$alias]->delete();
doctrine's avatar
doctrine committed
700 701
                    
                    break;
702
                    case Doctrine_Relation::MANY_COMPOSITE:
703 704
                        if(isset($this->references[$alias])) {
                            $new = $this->references[$alias];
doctrine's avatar
doctrine committed
705

706 707
                            if( ! isset($this->originals[$alias]))
                                $this->loadReference($alias);
doctrine's avatar
doctrine committed
708

709
                            $r = $this->getRelationOperations($alias,$new);
doctrine's avatar
doctrine committed
710 711 712 713 714

                            foreach($r["delete"] as $record) {
                                $record->delete();
                            }
                            
715
                            $this->originals[$alias] = clone $this->references[$alias];
doctrine's avatar
doctrine committed
716 717 718 719 720 721 722 723 724 725 726 727 728
                        }
                    break;
                endswitch;
            }
        endforeach;
    }
    /**
     * get the records that need to be added
     * and/or deleted in order to change the old collection
     * to the new one
     *
     * The algorithm here is very simple and definitely not
     * the fastest one, since we have to iterate through the collections twice.
729
     * the complexity of this algorithm is O(n^2)
doctrine's avatar
doctrine committed
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797
     *
     * First we iterate through the new collection and get the
     * records that do not exist in the old collection (Doctrine_Records that need to be added).
     *
     * Then we iterate through the old collection and get the records
     * that do not exists in the new collection (Doctrine_Records that need to be deleted).
     */
    final public function getRelationOperations($name, Doctrine_Collection $new) {
        $r["add"]    = array();
        $r["delete"] = array();



        foreach($new as $k=>$record) {

            $found = false;

            if($record->getID() !== null) {
                foreach($this->originals[$name] as $k2 => $record2) {
                    if($record2->getID() == $record->getID()) {
                        $found = true;
                        break;
                    }
                }
            }
            if( ! $found) {
                $this->originals[$name][] = $record;
                $r["add"][] = $record;
            }
        }

        foreach($this->originals[$name] as $k => $record) {
            if($record->getID() === null)
                continue;

            $found = false;
            foreach($new as $k2=>$record2) {
                if($record2->getID() == $record->getID()) {
                    $found = true;
                    break;
                }
            }

            if( ! $found)  {
                $r["delete"][] = $record;
                unset($this->originals[$name][$k]);
            }
        }

        return $r;
    }
    /**
     * getOriginals
     */
    final public function getOriginals($name) {
        if( ! isset($this->originals[$name]))
            throw new InvalidKeyException();

        return $this->originals[$name];
    }
    /**
     * deletes this data access object and all the related composites
     * this operation is isolated by a transaction
     *
     * this event can be listened by the onPreDelete and onDelete listeners
     *
     * @return boolean      true on success, false on failure
     */
798
    public function delete() {
doctrine's avatar
doctrine committed
799 800 801 802 803 804
        $this->table->getSession()->delete($this);
    }
    /**
     * returns a copy of this object
     * @return DAO
     */
doctrine's avatar
doctrine committed
805
    public function copy() {
doctrine's avatar
doctrine committed
806 807 808 809 810 811
        return $this->table->create($this->data);
    }
    /**
     * @param integer $id
     * @return void
     */
812 813 814
    final public function setID($id = false) {
        if($id === false) {
            $this->id       = false;
doctrine's avatar
doctrine committed
815
            $this->cleanData();
816
            $this->state    = Doctrine_Record::STATE_TCLEAN;
doctrine's avatar
doctrine committed
817
            $this->modified = array();
818 819 820 821
        } elseif($id === true) {
            $this->prepareIdentifiers(false);
            $this->state    = Doctrine_Record::STATE_CLEAN;
            $this->modified = array();
doctrine's avatar
doctrine committed
822 823 824 825 826 827 828
        } else {
            $this->id       = $id;
            $this->state    = Doctrine_Record::STATE_CLEAN;
            $this->modified = array();
        }
    }
    /**
829 830
     * return the primary key(s) this object is pointing at
     * @return mixed id
doctrine's avatar
doctrine committed
831 832 833 834 835 836 837
     */
    final public function getID() {
        return $this->id;
    }
    /**
     * hasRefence
     * @param string $name
doctrine's avatar
doctrine committed
838
     * @return boolean
doctrine's avatar
doctrine committed
839 840 841 842 843 844 845 846 847
     */
    public function hasReference($name) {
        return isset($this->references[$name]);
    }
    /**
     * @param Doctrine_Collection $coll
     * @param string $connectorField
     */
    public function initReference(Doctrine_Collection $coll, Doctrine_Relation $connector) {
doctrine's avatar
doctrine committed
848
        $name = $this->table->getAlias($coll->getTable()->getComponentName());
doctrine's avatar
doctrine committed
849 850 851 852 853 854
        $coll->setReference($this, $connector);
        $this->references[$name] = $coll;
        $this->originals[$name]  = clone $coll;
    }
    /**
     * addReference
doctrine's avatar
doctrine committed
855 856 857
     * @param Doctrine_Record $record
     * @param mixed $key
     * @return void
doctrine's avatar
doctrine committed
858
     */
doctrine's avatar
doctrine committed
859
    public function addReference(Doctrine_Record $record, $key = null) {
doctrine's avatar
doctrine committed
860 861
        $name = $this->table->getAlias($record->getTable()->getComponentName());

doctrine's avatar
doctrine committed
862 863
        $this->references[$name]->add($record, $key);
        $this->originals[$name]->add($record, $key);
doctrine's avatar
doctrine committed
864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880
    }
    /**
     * getReferences
     * @return array    all references
     */
    public function getReferences() {
        return $this->references;
    }

    /**
     * @throws InvalidKeyException
     * @param name
     * @return void
     */
    final public function loadReference($name) {
        $fk      = $this->table->getForeignKey($name);
        $table   = $fk->getTable();
881

doctrine's avatar
doctrine committed
882 883
        $local   = $fk->getLocal();
        $foreign = $fk->getForeign();
884
        $graph   = $table->getQueryObject();
885
        $type    = $fk->getType();
doctrine's avatar
doctrine committed
886 887 888 889 890

        switch($this->getState()):
            case Doctrine_Record::STATE_TDIRTY:
            case Doctrine_Record::STATE_TCLEAN:

891
                if($type == Doctrine_Relation::ONE_COMPOSITE ||
892
                   $type == Doctrine_Relation::ONE_AGGREGATE) {
893

doctrine's avatar
doctrine committed
894 895 896 897 898 899 900 901 902 903 904 905 906 907
                    // ONE-TO-ONE
                    $this->references[$name] = $table->create();

                    if($fk instanceof Doctrine_ForeignKey) {
                        $this->references[$name]->set($fk->getForeign(),$this);
                    } else {
                        $this->set($fk->getLocal(),$this->references[$name]);
                    }
                } else {
                    $this->references[$name] = new Doctrine_Collection($table);
                    if($fk instanceof Doctrine_ForeignKey) {
                        // ONE-TO-MANY
                        $this->references[$name]->setReference($this,$fk);
                    }
doctrine's avatar
doctrine committed
908
                    $this->originals[$name]  = new Doctrine_Collection($table);
doctrine's avatar
doctrine committed
909 910 911 912 913
                }
            break;
            case Doctrine_Record::STATE_DIRTY:
            case Doctrine_Record::STATE_CLEAN:
            case Doctrine_Record::STATE_PROXY:
914

doctrine's avatar
doctrine committed
915
                 switch($fk->getType()):
916 917
                    case Doctrine_Relation::ONE_COMPOSITE:
                    case Doctrine_Relation::ONE_AGGREGATE:
918

doctrine's avatar
doctrine committed
919 920
                        // ONE-TO-ONE
                        $id      = $this->get($local);
doctrine's avatar
doctrine committed
921

doctrine's avatar
doctrine committed
922
                        if($fk instanceof Doctrine_LocalKey) {
923

doctrine's avatar
doctrine committed
924 925 926 927 928 929 930 931 932 933 934 935
                            if(empty($id)) {
                                $this->references[$name] = $table->create();
                                $this->set($fk->getLocal(),$this->references[$name]);
                            } else {
                                try {
                                    $this->references[$name] = $table->find($id);
                                } catch(Doctrine_Find_Exception $e) {

                                }
                            }

                        } elseif ($fk instanceof Doctrine_ForeignKey) {
936

937 938 939 940
                            if(empty($id)) {
                                $this->references[$name] = $table->create();
                                $this->references[$name]->set($fk->getForeign(), $this);
                            } else {
941
                                $dql  = "FROM ".$table->getComponentName()." WHERE ".$table->getComponentName().".".$fk->getForeign()." = ?";
942
                                $coll = $graph->query($dql, array($id));
943 944 945
                                $this->references[$name] = $coll[0];
                                $this->references[$name]->set($fk->getForeign(), $this);
                            }
doctrine's avatar
doctrine committed
946 947 948 949 950
                        }
                    break;
                    default:
                        // ONE-TO-MANY
                        if($fk instanceof Doctrine_ForeignKey) {
951
                            $id      = $this->get($local);
952
                            $query = "FROM ".$table->getComponentName()." WHERE ".$table->getComponentName().".".$fk->getForeign()." = ?";
doctrine's avatar
doctrine committed
953
                            $coll = $graph->query($query,array($id));
doctrine's avatar
doctrine committed
954

doctrine's avatar
doctrine committed
955
                            $this->references[$name] = $coll;
doctrine's avatar
doctrine committed
956
                            $this->references[$name]->setReference($this, $fk);
doctrine's avatar
doctrine committed
957 958 959
    
                            $this->originals[$name]  = clone $coll;

960
                        } elseif($fk instanceof Doctrine_Association) {            
doctrine's avatar
doctrine committed
961 962 963
                            $asf     = $fk->getAssociationFactory();
                            $query   = "SELECT ".$foreign." FROM ".$asf->getTableName()." WHERE ".$local." = ?";
        
964
                            $graph   = new Doctrine_Query($table->getSession());
965
                            $query   = "FROM ".$table->getComponentName()." WHERE ".$table->getComponentName().".".$table->getIdentifier()." IN ($query)";
doctrine's avatar
doctrine committed
966 967 968 969

                            $coll    = $graph->query($query, array($this->getID()));
        
                            $this->references[$name] = $coll;
doctrine's avatar
doctrine committed
970
                            $this->originals[$name]  = clone $coll;
971

doctrine's avatar
doctrine committed
972 973
                        }
                 endswitch;
doctrine's avatar
doctrine committed
974 975 976 977 978
            break;
        endswitch;
    }

    /**
979 980
     * binds One-to-One composite relation
     *
doctrine's avatar
doctrine committed
981 982 983 984
     * @param string $objTableName
     * @param string $fkField
     * @return void
     */
985 986
    final public function ownsOne($componentName,$foreignKey, $localKey = null) {
        $this->table->bind($componentName,$foreignKey,Doctrine_Relation::ONE_COMPOSITE, $localKey);
doctrine's avatar
doctrine committed
987 988
    }
    /**
989 990
     * binds One-to-Many composite relation
     *
doctrine's avatar
doctrine committed
991 992 993 994
     * @param string $objTableName
     * @param string $fkField
     * @return void
     */
995 996
    final public function ownsMany($componentName,$foreignKey, $localKey = null) {
        $this->table->bind($componentName,$foreignKey,Doctrine_Relation::MANY_COMPOSITE, $localKey);
doctrine's avatar
doctrine committed
997 998
    }
    /**
999 1000
     * binds One-to-One aggregate relation
     *
doctrine's avatar
doctrine committed
1001 1002 1003 1004
     * @param string $objTableName
     * @param string $fkField
     * @return void
     */
1005 1006
    final public function hasOne($componentName,$foreignKey, $localKey = null) {
        $this->table->bind($componentName,$foreignKey,Doctrine_Relation::ONE_AGGREGATE, $localKey);
doctrine's avatar
doctrine committed
1007 1008
    }
    /**
1009 1010
     * binds One-to-Many aggregate relation
     *
doctrine's avatar
doctrine committed
1011 1012 1013 1014
     * @param string $objTableName
     * @param string $fkField
     * @return void
     */
1015 1016
    final public function hasMany($componentName,$foreignKey, $localKey = null) {
        $this->table->bind($componentName,$foreignKey,Doctrine_Relation::MANY_AGGREGATE, $localKey);
doctrine's avatar
doctrine committed
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    }
    /**
     * setInheritanceMap
     * @param array $inheritanceMap
     * @return void
     */
    final public function setInheritanceMap(array $inheritanceMap) {
        $this->table->setInheritanceMap($inheritanceMap);
    }
    /**
     * setPrimaryKey
1028
     * @param mixed $key
doctrine's avatar
doctrine committed
1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
     */
    final public function setPrimaryKey($key) {
        $this->table->setPrimaryKey($key);
    }
    /**
     * setTableName
     * @param string $name              table name
     * @return void
     */
    final public function setTableName($name) {
        $this->table->setTableName($name);
    }
    /**
     * setAttribute
     * @param integer $attribute
     * @param mixed $value
     * @see Doctrine::ATTR_* constants
     * @return void
     */
    final public function setAttribute($attribute, $value) {
        $this->table->setAttribute($attribute,$value);
    }
    /**
     * hasColumn
1053 1054
     * sets a column definition
     *
doctrine's avatar
doctrine committed
1055 1056 1057 1058 1059 1060 1061
     * @param string $name
     * @param string $type
     * @param integer $length
     * @param mixed $options
     * @return void
     */
    final public function hasColumn($name, $type, $length = 20, $options = "") {
doctrine's avatar
doctrine committed
1062
        $this->table->setColumn($name, $type, $length, $options);
doctrine's avatar
doctrine committed
1063 1064 1065 1066 1067 1068 1069 1070 1071
    }
    /**
     * returns a string representation of this object
     */
    public function __toString() {
        return Doctrine_Lib::getRecordAsString($this);
    }
}
?>