Record.php 52.1 KB
Newer Older
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 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
<?php
/*
 *  $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.phpdoctrine.com>.
 */
Doctrine::autoload('Doctrine_Access');
/**
 * Doctrine_Record
 * All record classes should inherit this super class
 *
 * @author      Konsta Vesterinen <kvesteri@cc.hut.fi>
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @package     Doctrine
 * @category    Object Relational Mapping
 * @link        www.phpdoctrine.com
 * @since       1.0
 * @version     $Revision$
 */
abstract class Doctrine_Record extends Doctrine_Access implements Countable, IteratorAggregate, Serializable
{
    /**
     * 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;
    /**
     * the following protected variables use '_' prefixes, the reason for this is to allow child
     * classes call for example $this->id, $this->state for getting the values of columns named 'id' and 'state'
     * rather than the values of these protected variables
     */
    /**
     * @var object Doctrine_Table $_table   the factory that created this data access object
     */
    protected $_table;
81
    /**
zYne's avatar
zYne committed
82
     * @var Doctrine_Node_<TreeImpl>        node object
83 84
     */
    protected $_node;
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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
    /**
     * @var integer $_id                    the primary keys of this object
     */
    protected $_id           = array();
    /**
     * @var array $_data                    the record data
     */
    protected $_data         = array();
    /**
     * @var array $_values                  the values array, aggregate values and such are mapped into this array
     */
    protected $_values       = array();
    /**
     * @var integer $_state                 the state of this record
     * @see STATE_* constants
     */
    protected $_state;
    /**
     * @var array $_modified                an array containing properties that have been modified
     */
    protected $_modified     = array();
    /**
     * @var Doctrine_Validator_ErrorStack   error stack object
     */
    protected $_errorStack;
    /**
     * @var array $references               an array containing all the references
     */
    private $references     = array();
    /**
     * @var array $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 Doctrine_Null $null             a Doctrine_Null object used for extremely fast
     *                                      null value testing
     */
    private static $null;
    /**
     * @var integer $oid                    object identifier, each Record object has a unique object identifier
     */
    private $oid;

    /**
     * constructor
     * @param Doctrine_Table|null $table       a Doctrine_Table object or null,
     *                                         if null the table object is retrieved from current connection
     *
     * @param boolean $isNewEntry              whether or not this record is transient
     *
     * @throws Doctrine_Connection_Exception   if object is created using the new operator and there are no
     *                                         open connections
     * @throws Doctrine_Record_Exception       if the cleanData operation fails somehow
     */
    public function __construct($table = null, $isNewEntry = false)
    {
        if (isset($table) && $table instanceof Doctrine_Table) {
            $this->_table = $table;
            $exists = ( ! $isNewEntry);
        } else {
            $class  = get_class($this);
            // get the table of this class
151 152 153
            $this->_table = Doctrine_Manager::getInstance()
                            ->getTable(get_class($this));

154 155 156 157 158 159 160 161 162 163 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
            $exists = false;
        }

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

        if ($this->_table->getConnection()->hasTable($this->_table->getComponentName())) {
            $this->oid = self::$index;

            self::$index++;

            $keys = $this->_table->getPrimaryKeys();

            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();

            // get the column count
            $count = count($this->_data);

            // clean data array
            $this->cleanData();

            $this->prepareIdentifiers($exists);

            if ( ! $exists) {
                if ($count > 0) {
                    $this->_state = Doctrine_Record::STATE_TDIRTY;
                } else {
                    $this->_state = Doctrine_Record::STATE_TCLEAN;
                }

                // set the default values for this record
zYne's avatar
zYne committed
195
                $this->assignDefaultValues();
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 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 306 307 308 309 310 311 312 313 314 315 316 317

                // listen the onCreate event
                $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onCreate($this);

            } else {
                $this->_state      = Doctrine_Record::STATE_CLEAN;

                if ($count < $this->_table->getColumnCount()) {
                    $this->_state  = Doctrine_Record::STATE_PROXY;
                }

                // listen the onLoad event
                $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onLoad($this);
            }

            $this->_errorStack = new Doctrine_Validator_ErrorStack();

            $repository = $this->_table->getRepository();
            $repository->add($this);
        }
        $this->construct();
    }
    /**
     * initNullObject
     *
     * @param Doctrine_Null $null
     * @return void
     */
    public static function initNullObject(Doctrine_Null $null)
    {
        self::$null = $null;
    }
    /**
     * @return Doctrine_Null
     */
    public static function getNullObject()
    {
        return self::$null;
    }
    /**
     * setUp
     * this method is used for setting up relations and attributes
     * it should be implemented by child classes
     *
     * @return void
     */
    public function setUp()
    { }
    /**
     * construct
     * Empty tempalte method to provide concrete Record classes with the possibility
     * to hook into the constructor procedure
     *
     * @return void
     */
    public function construct()
    { }
    /**
     * getOID
     * returns the object identifier
     *
     * @return integer
     */
    public function getOID()
    {
        return $this->oid;
    }
    /**
     * isValid
     *
     * @return boolean                          whether or not this record passes all column validations
     */
    public function isValid()
    {
        if ( ! $this->_table->getAttribute(Doctrine::ATTR_VLD)) {
            return true;
        }
        // Clear the stack from any previous errors.
        $this->_errorStack->clear();

        // Run validation process
        $validator = new Doctrine_Validator();
        $validator->validateRecord($this);
        $this->validate();
        if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) {
            $this->validateOnInsert();
        } else {
            $this->validateOnUpdate();
        }

        return $this->_errorStack->count() == 0 ? true : false;
    }
    /**
     * Emtpy template method to provide concrete Record classes with the possibility
     * to hook into the validation procedure, doing any custom / specialized
     * validations that are neccessary.
     */
    protected function validate()
    {}
    /**
     * Empty tempalte method to provide concrete Record classes with the possibility
     * to hook into the validation procedure only when the record is going to be
     * updated.
     */
    protected function validateOnUpdate()
    {}
    /**
     * Empty tempalte method to provide concrete Record classes with the possibility
     * to hook into the validation procedure only when the record is going to be
     * inserted into the data store the first time.
     */
    protected function validateOnInsert()
    {}
    /**
     * getErrorStack
     *
     * @return Doctrine_Validator_ErrorStack    returns the errorStack associated with this record
     */
    public function getErrorStack()
    {
        return $this->_errorStack;
    }
zYne's avatar
zYne committed
318 319 320 321 322 323 324 325 326
    /**
     * errorStack
     * assigns / returns record errorStack
     *
     * @param Doctrine_Validator_ErrorStack          errorStack to be assigned for this record
     * @return void|Doctrine_Validator_ErrorStack    returns the errorStack associated with this record
     */
    public function errorStack($stack = null)
    {
327 328 329 330
        if($stack !== null) {
            if( ! ($stack instanceof Doctrine_Validator_ErrorStack)) {
               throw new Doctrine_Record_Exception('Argument should be an instance of Doctrine_Validator_ErrorStack.');
            }
zYne's avatar
zYne committed
331
            $this->_errorStack = $stack;
332
        } else {
zYne's avatar
zYne committed
333 334 335
            return $this->_errorStack;
        }
    }
336 337 338 339 340 341 342
    /**
     * setDefaultValues
     * sets the default values for records internal data
     *
     * @param boolean $overwrite                whether or not to overwrite the already set values
     * @return boolean
     */
zYne's avatar
zYne committed
343
    public function assignDefaultValues($overwrite = false)
344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    {
        if ( ! $this->_table->hasDefaultValues()) {
            return false;
        }
        foreach ($this->_data as $column => $value) {
            $default = $this->_table->getDefaultValueOf($column);

            if ($default === null)
                $default = self::$null;

            if ($value === self::$null || $overwrite) {
                $this->_data[$column] = $default;
                $this->_modified[]    = $column;
                $this->_state = Doctrine_Record::STATE_TDIRTY;
            }
        }
    }
    /**
     * cleanData
     * this method does several things to records internal data
     *
     * 1. It unserializes array and object typed columns
     * 2. Uncompresses gzip typed columns
     * 3. Gets the appropriate enum values for enum typed columns
     * 4. Initializes special null object pointer for null values (for fast column existence checking purposes)
     *
     *
     * example:
     *
     * $data = array("name"=>"John","lastname"=> null, "id" => 1,"unknown" => "unknown");
     * $names = array("name", "lastname", "id");
     * $data after operation:
     * $data = array("name"=>"John","lastname" => Object(Doctrine_Null));
     *
     * here column 'id' is removed since its auto-incremented primary key (read-only)
     *
     * @throws Doctrine_Record_Exception        if unserialization of array/object typed column fails or
     *                                          if uncompression of gzip typed column fails
     *
     * @return integer
     */
zYne's avatar
zYne committed
385
    private function cleanData()
386 387 388 389 390 391 392 393 394 395 396 397 398 399
    {
        $tmp = $this->_data;

        $this->_data = array();

        $count = 0;

        foreach ($this->_table->getColumnNames() as $name) {
            $type = $this->_table->getTypeOf($name);

            if ( ! isset($tmp[$name])) {
                $this->_data[$name] = self::$null;
            } else {
                switch ($type) {
zYne's avatar
zYne committed
400 401
                    case 'array':
                    case 'object':
402 403 404 405 406
                        if ($tmp[$name] !== self::$null) {
                            if (is_string($tmp[$name])) {
                                $value = unserialize($tmp[$name]);

                                if ($value === false)
zYne's avatar
zYne committed
407
                                    throw new Doctrine_Record_Exception('Unserialization of ' . $name . ' failed.');
408 409 410 411 412 413
                            } else {
                                $value = $tmp[$name];
                            }
                            $this->_data[$name] = $value;
                        }
                        break;
zYne's avatar
zYne committed
414
                    case 'gzip':
415 416 417 418
                        if ($tmp[$name] !== self::$null) {
                            $value = gzuncompress($tmp[$name]);

                            if ($value === false)
zYne's avatar
zYne committed
419
                                throw new Doctrine_Record_Exception('Uncompressing of ' . $name . ' failed.');
420 421 422 423

                            $this->_data[$name] = $value;
                        }
                        break;
zYne's avatar
zYne committed
424
                    case 'enum':
425 426
                        $this->_data[$name] = $this->_table->enumValue($name, $tmp[$name]);
                        break;
427 428 429 430
                    case 'boolean':
                    case 'integer':
                        if($tmp[$name] !== self::$null)
                            settype($tmp[$name], $type);
431 432
                    default:
                        $this->_data[$name] = $tmp[$name];
zYne's avatar
zYne committed
433
                }
434 435 436 437 438 439
                $count++;
            }
        }

        return $count;
    }
zYne's avatar
zYne committed
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
    /**
     * hydrate
     * hydrates this object from given array
     *
     * @param array $data
     * @return boolean
     */
    public function hydrate(array $data)
    {
        foreach ($data as $k => $v) {
            $this->_data[$k] = $v;
        }
        $this->cleanData();
        $this->prepareIdentifiers();
    }
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    /**
     * prepareIdentifiers
     * prepares identifiers for later use
     *
     * @param boolean $exists               whether or not this record exists in persistent data store
     * @return void
     */
    private function prepareIdentifiers($exists = true)
    {
        switch ($this->_table->getIdentifierType()) {
            case Doctrine_Identifier::AUTO_INCREMENT:
            case Doctrine_Identifier::SEQUENCE:
                $name = $this->_table->getIdentifier();

                if ($exists) {
                    if (isset($this->_data[$name]) && $this->_data[$name] !== self::$null) {
                        $this->_id[$name] = $this->_data[$name];
                    }
                }

                unset($this->_data[$name]);

                break;
            case Doctrine_Identifier::NORMAL:
                $this->_id   = array();
                $name       = $this->_table->getIdentifier();

                if (isset($this->_data[$name]) && $this->_data[$name] !== self::$null) {
                    $this->_id[$name] = $this->_data[$name];
                }
                break;
            case Doctrine_Identifier::COMPOSITE:
                $names      = $this->_table->getIdentifier();

                foreach ($names as $name) {
                    if ($this->_data[$name] === self::$null) {
                        $this->_id[$name] = null;
                    } else {
                        $this->_id[$name] = $this->_data[$name];
                    }
                }
                break;
zYne's avatar
zYne committed
497
        }
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
    }
    /**
     * serialize
     * this method is automatically called when this Doctrine_Record is serialized
     *
     * @return array
     */
    public function serialize()
    {
        $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onSleep($this);

        $vars = get_object_vars($this);

        unset($vars['references']);
        unset($vars['originals']);
        unset($vars['_table']);
zYne's avatar
zYne committed
514
        unset($vars['_errorStack']);
515 516 517 518 519 520 521 522 523 524 525

        $name = $this->_table->getIdentifier();
        $this->_data = array_merge($this->_data, $this->_id);

        foreach ($this->_data as $k => $v) {
            if ($v instanceof Doctrine_Record) {
                unset($vars['_data'][$k]);
            } elseif ($v === self::$null) {
                unset($vars['_data'][$k]);
            } else {
                switch ($this->_table->getTypeOf($k)) {
526 527
                    case 'array':
                    case 'object':
528 529
                        $vars['_data'][$k] = serialize($vars['_data'][$k]);
                        break;
530 531 532 533 534 535
                    case 'gzip':
                        $vars['_data'][$k] = gzcompress($vars['_data'][$k]);
                        break;
                    case 'enum':
                        $vars['_data'][$k] = $this->_table->enumIndex($k, $vars['_data'][$k]);
                        break;
zYne's avatar
zYne committed
536
                }
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
            }
        }

        return serialize($vars);
    }
    /**
     * unseralize
     * this method is automatically called everytime a Doctrine_Record object is unserialized
     *
     * @param string $serialized                Doctrine_Record as serialized string
     * @throws Doctrine_Record_Exception        if the cleanData operation fails somehow
     * @return void
     */
    public function unserialize($serialized)
    {
        $manager    = Doctrine_Manager::getInstance();
zYne's avatar
zYne committed
553
        $connection = $manager->getConnectionForComponent(get_class($this));
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 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

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

        $this->_table = $connection->getTable(get_class($this));

        $array = unserialize($serialized);

        foreach ($array as $name => $values) {
            $this->$name = $values;
        }

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

        $this->cleanData();

        $this->prepareIdentifiers($this->exists());

        $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onWakeUp($this);
    }
    /**
     * getState
     * returns the current state of the object
     *
     * @see Doctrine_Record::STATE_* constants
     * @return integer
     */
    public function getState()
    {
        return $this->_state;
    }
    /**
     * state
     * returns / assigns the state of this record
     *
     * @param integer|string $state                 if set, this method tries to set the record state to $state
     * @see Doctrine_Record::STATE_* constants
     *
     * @throws Doctrine_Record_State_Exception      if trying to set an unknown state
     * @return null|integer
     */
    public function state($state = null)
    {
        if ($state == null) {
            return $this->_state;
        }
        $err = false;
        if (is_integer($state)) {

            if ($state >= 1 && $state <= 6) {
                $this->_state = $state;
            } else {
                $err = true;
            }
        } elseif (is_string($state)) {
            $upper = strtoupper($state);
            switch ($upper) {
                case 'DIRTY':
                case 'CLEAN':
                case 'TDIRTY':
                case 'TCLEAN':
                case 'PROXY':
                case 'DELETED':
                    $this->_state = constant('Doctrine_Record::STATE_' . $upper);
                    break;
                default:
                    $err = true;
            }
        }

        if ($err)
            throw new Doctrine_Record_State_Exception('Unknown record state ' . $state);
    }
    /**
     * refresh
     * refresh internal data from the database
     *
     * @throws Doctrine_Record_Exception        When the refresh operation fails (when the database row
     *                                          this record represents does not exist anymore)
     * @return boolean
     */
    final public function refresh()
    {
        $id = $this->obtainIdentifier();
        if ( ! is_array($id)) {
            $id = array($id);
        }
        if (empty($id)) {
            return false;
        }
        $id = array_values($id);

        $query          = $this->_table->getQuery()." WHERE ".implode(" = ? AND ",$this->_table->getPrimaryKeys())." = ?";
        $stmt           = $this->_table->getConnection()->execute($query,$id);

        $this->_data     = $stmt->fetch(PDO::FETCH_ASSOC);

        if ( ! $this->_data)
            throw new Doctrine_Record_Exception('Failed to refresh. Record does not exist anymore');

        $this->_data     = array_change_key_case($this->_data, CASE_LOWER);

        $this->_modified = array();
        $this->cleanData(true);

        $this->prepareIdentifiers();

        $this->_state    = Doctrine_Record::STATE_CLEAN;

        $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onLoad($this);

        return true;
    }
    /**
     * factoryRefresh
     * refreshes the data from outer source (Doctrine_Table)
     *
     * @throws Doctrine_Record_Exception        When the primary key of this record doesn't match the primary key fetched from a collection
     * @return void
     */
    final public function factoryRefresh()
    {
        $this->_data = $this->_table->getData();
        $old  = $this->_id;

        $this->cleanData();

        $this->prepareIdentifiers();

        if ($this->_id != $old)
            throw new Doctrine_Record_Exception("The refreshed primary key doesn't match the one in the record memory.", Doctrine::ERR_REFRESH);

        $this->_state    = Doctrine_Record::STATE_CLEAN;
        $this->_modified = array();

        $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onLoad($this);
    }
    /**
     * getTable
     * returns the table object for this record
     *
     * @return object Doctrine_Table        a Doctrine_Table object
     */
    final public function getTable()
    {
        return $this->_table;
    }
    /**
     * getData
     * return all the internal data
     *
     * @return array                        an array containing all the properties
     */
    final public function getData()
    {
        return $this->_data;
    }
    /**
     * rawGet
     * returns the value of a property, if the property is not yet loaded
     * this method does NOT load it
     *
     * @param $name                         name of the property
     * @throws Doctrine_Record_Exception    if trying to get an unknown property
     * @return mixed
     */

    public function rawGet($name)
    {
        if ( ! isset($this->_data[$name])) {
            throw new Doctrine_Record_Exception('Unknown property '. $name);
        }
        if ($this->_data[$name] === self::$null)
            return null;

        return $this->_data[$name];
    }

    /**
     * load
     * loads all the unitialized properties from the database
     *
     * @return boolean
     */
    public function load()
    {
        // only load the data from database if the Doctrine_Record is in proxy state
        if ($this->_state == Doctrine_Record::STATE_PROXY) {
            $this->refresh();

            $this->_state = Doctrine_Record::STATE_CLEAN;

            return true;
        }
        return false;
    }
    /**
     * get
     * returns a value of a property or a related component
     *
     * @param mixed $name                       name of the property or related component
     * @param boolean $invoke                   whether or not to invoke the onGetProperty listener
     * @throws Doctrine_Record_Exception        if trying to get a value of unknown property / related component
     * @return mixed
     */
    public function get($name, $invoke = true)
    {
        $value    = self::$null;
        $lower    = strtolower($name);

zYne's avatar
zYne committed
764 765
        $lower    = $this->_table->getColumnName($lower);

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 798 799 800 801 802 803
        if (isset($this->_data[$lower])) {
            // check if the property is null (= it is the Doctrine_Null object located in self::$null)
            if ($this->_data[$lower] === self::$null) {
                $this->load();
            }

            if ($this->_data[$lower] === self::$null) {
                $value = null;
            } else {
                $value = $this->_data[$lower];
            }

        }

        if ($value !== self::$null) {
            $value = $this->_table->invokeGet($this, $name, $value);

            if ($invoke && $name !== $this->_table->getIdentifier()) {
                return $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onGetProperty($this, $name, $value);
            } else {
                return $value;
            }
        }

        if (isset($this->_id[$lower])) {
            return $this->_id[$lower];
        }
        if ($name === $this->_table->getIdentifier()) {
            return null;
        }
        if (isset($this->_values[$lower])) {
            return $this->_values[$lower];
        }

        try {
            if ( ! isset($this->references[$name])) {
                $this->loadReference($name);
            }
804
        } catch(Doctrine_Table_Exception $e) { 
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842
            throw new Doctrine_Record_Exception("Unknown property / related component '$name'.");
        }

        return $this->references[$name];
    }
    /**
     * mapValue
     * This simple method is used for mapping values to $values property.
     * Usually this method is used internally by Doctrine for the mapping of
     * aggregate values.
     *
     * @param string $name                  the name of the mapped value
     * @param mixed $value                  mixed value to be mapped
     * @return void
     */
    public function mapValue($name, $value)
    {
        $name = strtolower($name);
        $this->_values[$name] = $value;
    }
    /**
     * set
     * method for altering properties and Doctrine_Record references
     * if the load parameter is set to false this method will not try to load uninitialized record data
     *
     * @param mixed $name                   name of the property or reference
     * @param mixed $value                  value of the property or reference
     * @param boolean $load                 whether or not to refresh / load the uninitialized record data
     *
     * @throws Doctrine_Record_Exception    if trying to set a value for unknown property / related component
     * @throws Doctrine_Record_Exception    if trying to set a value of wrong type for related component
     *
     * @return Doctrine_Record
     */
    public function set($name, $value, $load = true)
    {
        $lower = strtolower($name);

zYne's avatar
zYne committed
843 844
        $lower = $this->_table->getColumnName($lower);

845 846 847 848
        if (isset($this->_data[$lower])) {
            if ($value instanceof Doctrine_Record) {
                $id = $value->getIncremented();

zYne's avatar
zYne committed
849
                if ($id !== null) {
850
                    $value = $id;
zYne's avatar
zYne committed
851
                }
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984
            }

            if ($load) {
                $old = $this->get($lower, false);
            } else {
                $old = $this->_data[$lower];
            }

            if ($old !== $value) {
                $value = $this->_table->invokeSet($this, $name, $value);

                $value = $this->_table->getAttribute(Doctrine::ATTR_LISTENER)->onSetProperty($this, $name, $value);

                if ($value === null)
                    $value = self::$null;

                $this->_data[$lower] = $value;
                $this->_modified[]   = $lower;
                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;
                        break;
                };
            }
        } else {
            try {
                $this->coreSetRelated($name, $value);
            } catch(Doctrine_Table_Exception $e) {
                throw new Doctrine_Record_Exception("Unknown property / related component '$name'.");
            }
        }
    }

    public function coreSetRelated($name, $value)
    {
        $rel = $this->_table->getRelation($name);

        // one-to-many or one-to-one relation
        if ($rel instanceof Doctrine_Relation_ForeignKey ||
           $rel instanceof Doctrine_Relation_LocalKey) {
            if ( ! $rel->isOneToOne()) {
                // one-to-many relation found
                if ( ! ($value instanceof Doctrine_Collection)) {
                    throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Collection when setting one-to-many references.");
                }
                $value->setReference($this,$rel);
            } else {
                // one-to-one relation found
                if ( ! ($value instanceof Doctrine_Record)) {
                    throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Record when setting one-to-one references.");
                }
                if ($rel instanceof Doctrine_Relation_LocalKey) {
                    $this->set($rel->getLocal(), $value, false);
                } else {
                    $value->set($rel->getForeign(), $this, false);
                }
            }

        } elseif ($rel instanceof Doctrine_Relation_Association) {
            // join table relation found
            if ( ! ($value instanceof Doctrine_Collection)) {
                throw new Doctrine_Record_Exception("Couldn't call Doctrine::set(), second argument should be an instance of Doctrine_Collection when setting many-to-many references.");
            }
        }

        $this->references[$name] = $value;
    }
    /**
     * contains
     *
     * @param string $name
     * @return boolean
     */
    public function contains($name)
    {
        $lower = strtolower($name);

        if (isset($this->_data[$lower])) {
            return true;
        }
        if (isset($this->_id[$lower])) {
            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 ?
    }
    /**
     * 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 components
     *
     * @param Doctrine_Connection $conn                 optional connection parameter
     * @return void
     */
    public function save(Doctrine_Connection $conn = null)
    {
        if ($conn === null) {
            $conn = $this->_table->getConnection();
        }
        $conn->beginTransaction();

        $saveLater = $conn->unitOfWork->saveRelated($this);

        if ($this->isValid()) {
            $conn->save($this);
        } else {
            $conn->transaction->addInvalid($this);
        }

        foreach ($saveLater as $fk) {
            $table   = $fk->getTable();
            $alias   = $this->_table->getAlias($table->getComponentName());

            if (isset($this->references[$alias])) {
                $obj = $this->references[$alias];
985
                $obj->save($conn);
986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083
            }
        }

        // save the MANY-TO-MANY associations

        $conn->unitOfWork->saveAssociations($this);
        //$this->saveAssociations();

        $conn->commit();
    }
    /**
     * Tries to save the object and all its related components.
     * In contrast to Doctrine_Record::save(), this method does not
     * throw an exception when validation fails but returns TRUE on
     * success or FALSE on failure.
     * 
     * @param Doctrine_Connection $conn                 optional connection parameter
     * @return TRUE if the record was saved sucessfully without errors, FALSE otherwise.
     */
    public function trySave(Doctrine_Connection $conn = null) {
        try {
            $this->save($conn);
            return true;
        } catch (Doctrine_Validator_Exception $ignored) {
            return false;
        }
    }
    /**
     * replace
     * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
     * query, except that if there is already a row in the table with the same
     * key field values, the REPLACE query just updates its values instead of
     * inserting a new row.
     *
     * The REPLACE type of query does not make part of the SQL standards. Since
     * practically only MySQL and SQLIte implement it natively, this type of
     * query isemulated through this method for other DBMS using standard types
     * of queries inside a transaction to assure the atomicity of the operation.
     *
     * @param Doctrine_Connection $conn             optional connection parameter
     * @throws Doctrine_Connection_Exception        if some of the key values was null
     * @throws Doctrine_Connection_Exception        if there were no key fields
     * @throws PDOException                         if something fails at PDO level
     * @return integer                              number of rows affected
     */
    public function replace(Doctrine_Connection $conn = null)
    {
        if ($conn === null) {
            $conn = $this->_table->getConnection();
        }

        return $conn->replace($this->_table->getTableName(), $this->getPrepared(), $this->id);
    }
    /**
     * returns an array of modified fields and associated values
     * @return array
     */
    public function getModified()
    {
        $a = array();

        foreach ($this->_modified as $k => $v) {
            $a[$v] = $this->_data[$v];
        }
        return $a;
    }
    /**
     * getPrepared
     *
     * returns an array of modified fields and values with data preparation
     * adds column aggregation inheritance and converts Records into primary key values
     *
     * @param array $array
     * @return array
     */
    public function getPrepared(array $array = array()) {
        $a = array();

        if (empty($array)) {
            $array = $this->_modified;
        }
        foreach ($array as $k => $v) {
            $type = $this->_table->getTypeOf($v);

            if ($this->_data[$v] === self::$null) {
                $a[$v] = null;
                continue;
            }

            switch ($type) {
                case 'array':
                case 'object':
                    $a[$v] = serialize($this->_data[$v]);
                    break;
                case 'gzip':
                    $a[$v] = gzcompress($this->_data[$v],5);
                    break;
                case 'boolean':
zYne's avatar
zYne committed
1084
                    $a[$v] = $this->getTable()->getConnection()->convertBooleans($this->_data[$v]);
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
                break;
                case 'enum':
                    $a[$v] = $this->_table->enumIndex($v,$this->_data[$v]);
                    break;
                default:
                    if ($this->_data[$v] instanceof Doctrine_Record)
                        $this->_data[$v] = $this->_data[$v]->getIncremented();

                    $a[$v] = $this->_data[$v];
            }
        }
zYne's avatar
zYne committed
1096 1097
        $map = $this->_table->inheritanceMap;
        foreach ($map as $k => $v) {
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
            $old = $this->get($k, false);

            if ((string) $old !== (string) $v || $old === null) {
                $a[$k] = $v;
                $this->_data[$k] = $v;
            }
        }

        return $a;
    }
    /**
     * count
     * this class implements countable interface
     *
     * @return integer          the number of columns in this record
     */
    public function count()
    {
        return count($this->_data);
    }
    /**
     * alias for count()
     *
     * @return integer          the number of columns in this record
     */
    public function columnCount()
    {
        return $this->count();
    }
    /**
     * toArray
     * returns the record as an array
     *
     * @return array
     */
    public function toArray()
    {
        $a = array();

        foreach ($this as $column => $value) {
            $a[$column] = $value;
        }
        if ($this->_table->getIdentifierType() == Doctrine_Identifier::AUTO_INCREMENT) {
            $i      = $this->_table->getIdentifier();
            $a[$i]  = $this->getIncremented();
        }
        return $a;
    }
    /**
     * exists
     * returns true if this record is persistent, otherwise false
     *
     * @return boolean
     */
    public function exists()
    {
        return ($this->_state !== Doctrine_Record::STATE_TCLEAN &&
                $this->_state !== Doctrine_Record::STATE_TDIRTY);
    }
    /**
     * method for checking existence of properties and Doctrine_Record references
     * @param mixed $name               name of the property or reference
     * @return boolean
     */
    public function hasRelation($name)
    {
        if (isset($this->_data[$name]) || isset($this->_id[$name])) {
            return true;
        }
        return $this->_table->hasRelation($name);
    }
    /**
     * getIterator
     * @return Doctrine_Record_Iterator     a Doctrine_Record_Iterator that iterates through the data
     */
    public function getIterator()
    {
        return new Doctrine_Record_Iterator($this);
    }
    /**
     * getOriginals
     * returns an original collection of related component
     *
     * @return Doctrine_Collection|false
     */
    public function obtainOriginals($name)
    {
        if (isset($this->originals[$name])) {
            return $this->originals[$name];
        }
        return false;
    }
    /**
     * 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
     */
    public function delete(Doctrine_Connection $conn = null)
    {
        if ($conn == null) {
            $conn = $this->_table->getConnection();
        }
        return $conn->delete($this);
    }
    /**
     * copy
     * returns a copy of this object
     *
     * @return Doctrine_Record
     */
    public function copy()
    {
        $ret = $this->_table->create($this->_data);
        $modified = array();
        foreach ($this->_data as $key => $val) {
zYne's avatar
zYne committed
1216
            if ( ! ($val instanceof Doctrine_Null)) {
1217 1218 1219 1220 1221
                $ret->_modified[] = $key;
            }
        }
        return $ret;
    }
runa's avatar
runa committed
1222 1223 1224 1225 1226 1227 1228
    /**
     * copyDeep
     * returns a copy of this object and all its related objects
     *
     * @return Doctrine_Record
     */
    public function copyDeep(){
zYne's avatar
zYne committed
1229 1230 1231 1232 1233 1234
        $copy = $this->copy();

        foreach ($this->references as $key => $value) {
            if ($value instanceof Doctrine_Collection) {
                foreach ($value as $record) {
                    $copy->{$key}[] = $record->copyDeep();
runa's avatar
runa committed
1235
                }
zYne's avatar
zYne committed
1236 1237
            } else {
                $copy->set($key, $value->copyDeep());
runa's avatar
runa committed
1238 1239
            }
        }
zYne's avatar
zYne committed
1240
        return $copy;
runa's avatar
runa committed
1241 1242
    }
    
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426
    /**
     * assignIdentifier
     *
     * @param integer $id
     * @return void
     */
    final public function assignIdentifier($id = false)
    {
        if ($id === false) {
            $this->_id       = array();
            $this->cleanData();
            $this->_state    = Doctrine_Record::STATE_TCLEAN;
            $this->_modified = array();
        } elseif ($id === true) {
            $this->prepareIdentifiers(false);
            $this->_state    = Doctrine_Record::STATE_CLEAN;
            $this->_modified = array();
        } else {
            $name            = $this->_table->getIdentifier();

            $this->_id[$name] = $id;
            $this->_state     = Doctrine_Record::STATE_CLEAN;
            $this->_modified  = array();
        }
    }
    /**
     * assignOriginals
     *
     * @param string $alias
     * @param Doctrine_Collection $coll
     * @return void
     */
    public function assignOriginals($alias, Doctrine_Collection $coll)
    {
        $this->originals[$alias] = $coll;
    }
    /**
     * returns the primary keys of this object
     *
     * @return array
     */
    final public function obtainIdentifier()
    {
        return $this->_id;
    }
    /**
     * returns the value of autoincremented primary key of this object (if any)
     *
     * @return integer
     */
    final public function getIncremented()
    {
        $id = current($this->_id);
        if ($id === false)
            return null;

        return $id;
    }
    /**
     * getLast
     * this method is used internally be Doctrine_Query
     * it is needed to provide compatibility between
     * records and collections
     *
     * @return Doctrine_Record
     */
    public function getLast()
    {
        return $this;
    }
    /**
     * hasRefence
     * @param string $name
     * @return boolean
     */
    public function hasReference($name)
    {
        return isset($this->references[$name]);
    }
    /**
     * obtainReference
     *
     * @param string $name
     * @throws Doctrine_Record_Exception        if trying to get an unknown related component
     */
    public function obtainReference($name)
    {
        if (isset($this->references[$name])) {
            return $this->references[$name];
        }
        throw new Doctrine_Record_Exception("Unknown reference $name");
    }
    /**
     * initalizes a one-to-many / many-to-many relation
     *
     * @param Doctrine_Collection $coll
     * @param Doctrine_Relation $connector
     * @return boolean
     */
    public function initReference(Doctrine_Collection $coll, Doctrine_Relation $connector)
    {
        $alias = $connector->getAlias();

        if (isset($this->references[$alias])) {
            return false;
        }
        if ( ! $connector->isOneToOne()) {
            if ( ! ($connector instanceof Doctrine_Relation_Association)) {
                $coll->setReference($this, $connector);
            }
            $this->references[$alias] = $coll;
            $this->originals[$alias]  = clone $coll;

            return true;
        }
        return false;
    }

    public function lazyInitRelated(Doctrine_Collection $coll, Doctrine_Relation $connector)
    {

    }
    /**
     * addReference
     * @param Doctrine_Record $record
     * @param mixed $key
     * @return void
     */
    public function addReference(Doctrine_Record $record, Doctrine_Relation $connector, $key = null)
    {
        $alias = $connector->getAlias();

        $this->references[$alias]->add($record, $key);
        $this->originals[$alias]->add($record, $key);
    }
    /**
     * getReferences
     * @return array    all references
     */
    public function getReferences()
    {
        return $this->references;
    }
    /**
     * setRelated
     *
     * @param string $alias
     * @param Doctrine_Access $coll
     */
    final public function setRelated($alias, Doctrine_Access $coll)
    {
        $this->references[$alias] = $coll;
        $this->originals[$alias]  = $coll;
    }
    /**
     * loadReference
     * loads a related component
     *
     * @throws Doctrine_Table_Exception             if trying to load an unknown related component
     * @param string $name
     * @return void
     */
    final public function loadReference($name)
    {

        $fk      = $this->_table->getRelation($name);

        if ($fk->isOneToOne()) {
            $this->references[$name] = $fk->fetchRelatedFor($this);

        } else {
            $coll = $fk->fetchRelatedFor($this);

            $this->references[$name] = $coll;
            $this->originals[$name]  = clone $coll;
        }
    }
    /**
     * binds One-to-One composite relation
     *
     * @param string $objTableName
     * @param string $fkField
     * @return void
     */
zYne's avatar
zYne committed
1427
    final public function ownsOne($componentName, $foreignKey, $options = null)
1428
    {
zYne's avatar
zYne committed
1429
        $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::ONE_COMPOSITE, $options);
1430 1431 1432 1433 1434 1435 1436 1437
    }
    /**
     * binds One-to-Many composite relation
     *
     * @param string $objTableName
     * @param string $fkField
     * @return void
     */
zYne's avatar
zYne committed
1438
    final public function ownsMany($componentName, $foreignKey, $options = null)
1439
    {
zYne's avatar
zYne committed
1440
        $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::MANY_COMPOSITE, $options);
1441 1442 1443 1444 1445 1446 1447 1448
    }
    /**
     * binds One-to-One aggregate relation
     *
     * @param string $objTableName
     * @param string $fkField
     * @return void
     */
zYne's avatar
zYne committed
1449
    final public function hasOne($componentName, $foreignKey, $options = null)
1450
    {
zYne's avatar
zYne committed
1451
        $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::ONE_AGGREGATE, $options);
1452 1453 1454 1455 1456 1457 1458 1459
    }
    /**
     * binds One-to-Many aggregate relation
     *
     * @param string $objTableName
     * @param string $fkField
     * @return void
     */
zYne's avatar
zYne committed
1460
    final public function hasMany($componentName, $foreignKey, $options = null)
1461
    {
zYne's avatar
zYne committed
1462
        $this->_table->bind($componentName, $foreignKey, Doctrine_Relation::MANY_AGGREGATE, $options);
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    }
    /**
     * hasColumn
     * sets a column definition
     *
     * @param string $name
     * @param string $type
     * @param integer $length
     * @param mixed $options
     * @return void
     */
    final public function hasColumn($name, $type, $length = 2147483647, $options = "")
    {
        $this->_table->setColumn($name, $type, $length, $options);
    }
    /**
     * countRelated
     *
     * @param string $name      the name of the related component
     * @return integer
     */
    public function countRelated($name)
    {
        $rel            = $this->_table->getRelation($name);
        $componentName  = $rel->getTable()->getComponentName();
        $alias          = $rel->getTable()->getAlias(get_class($this));
        $query          = new Doctrine_Query();
        $query->from($componentName. '(' . 'COUNT(1)' . ')')->where($componentName. '.' .$alias. '.' . $this->getTable()->getIdentifier(). ' = ?');
        $array = $query->execute(array($this->getIncremented()));
        return $array[0]['COUNT(1)'];
    }
    /**
     * merge
     * merges this record with an array of values
     *
     * @param array $values
     * @return void
     */
    public function merge(array $values)
    {
        foreach ($this->_table->getColumnNames() as $value) {
            try {
                if (isset($values[$value])) {
                    $this->set($value, $values[$value]);
                }
            } catch(Exception $e) {
                // silence all exceptions
            }
        }
    }
    public function setAttribute($attr, $value)
    {
        $this->_table->setAttribute($attr, $value);
    }
    public function setTableName($tableName)
    {
zYne's avatar
zYne committed
1519
        $this->_table->setOption('tableName', $tableName);
1520 1521 1522 1523 1524 1525 1526 1527 1528
    }
    public function setInheritanceMap($map)
    {
        $this->_table->setOption('inheritanceMap', $map);
    }
    public function setEnumValues($column, $values)
    {
        $this->_table->setEnumValues($column, $values);
    }
zYne's avatar
zYne committed
1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
    /**
     * attribute
     * sets or retrieves an option
     *
     * @see Doctrine::ATTR_* constants   availible attributes
     * @param mixed $attr
     * @param mixed $value
     * @return mixed
     */
    public function attribute($attr, $value)
    {
        if ($value == null) {
            if (is_array($attr)) {
                foreach ($attr as $k => $v) {
                    $this->_table->setAttribute($k, $v);
                }
            } else {
                return $this->_table->getAttribute($attr);
            }
        } else {
            $this->_table->setAttribute($attr, $value);
        }    
    }
1552 1553 1554 1555 1556
    /**
     * option
     * sets or retrieves an option
     *
     * @see Doctrine_Table::$options    availible options
zYne's avatar
zYne committed
1557 1558
     * @param mixed $name               the name of the option
     * @param mixed $value              options value
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574
     * @return mixed
     */
    public function option($name, $value = null)
    {
        if ($value == null) {
            if (is_array($name)) {
                foreach ($name as $k => $v) {
                    $this->_table->setOption($k, $v);
                }
            } else {
                return $this->_table->getOption($name);
            }
        } else {
            $this->_table->setOption($name, $value);
        }
    }
1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
    /**
     * index
     * defines a foreignKey
     *
     * @param array $definition         the definition array
     * @return void
     */
    public function foreignKey(array $definition = array())
    {
        return $this->_table->addForeignKey($definition);
    }
zYne's avatar
zYne committed
1586 1587 1588 1589 1590 1591 1592
    /**
     * index
     * defines or retrieves an index
     * if the second parameter is set this method defines an index
     * if not this method retrieves index named $name
     *
     * @param string $name              the name of the index
zYne's avatar
zYne committed
1593
     * @param array $definition         the definition array
zYne's avatar
zYne committed
1594 1595
     * @return mixed
     */
zYne's avatar
zYne committed
1596
    public function index($name, array $definition = array())
1597
    {
1598
        if ( ! $definition) {
zYne's avatar
zYne committed
1599 1600
            return $this->_table->getIndex($name);
        } else {
zYne's avatar
zYne committed
1601
            return $this->_table->addIndex($name, $definition);
zYne's avatar
zYne committed
1602
        }
1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
    }
    /**
     * addListener
     *
     * @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener
     * @return Doctrine_Db
     */
    public function addListener($listener, $name = null)
    {
        $this->_table->addListener($listener, $name = null);
        return $this;
    }
    /**
     * getListener
     *
     * @return Doctrine_Db_EventListener_Interface|Doctrine_Overloadable
     */
    public function getListener()
    {
        return $this->_table->getListener();
    }
    /**
     * setListener
     *
     * @param Doctrine_Db_EventListener_Interface|Doctrine_Overloadable $listener
     * @return Doctrine_Db
     */
    public function setListener($listener)
    {
        $this->_table->setListener($listener);
        return $this;
    }
    /**
     * call
     *
     * @param string|array $callback    valid callback
     * @param string $column            column name
     * @param mixed arg1 ... argN       optional callback arguments
     * @return Doctrine_Record
     */
    public function call($callback, $column)
    {
        $args = func_get_args();
        array_shift($args);

        if (isset($args[0])) {
            $column = $args[0];
            $args[0] = $this->get($column);

            $newvalue = call_user_func_array($callback, $args);

            $this->_data[$column] = $newvalue;
        }
        return $this;
    }
1658 1659 1660 1661 1662
    /**
     * getter for node assciated with this record
     *
     * @return mixed if tree returns Doctrine_Node otherwise returns false
     */    
zYne's avatar
zYne committed
1663 1664 1665 1666 1667
    public function getNode() 
    {
        if ( ! $this->_table->isTree()) {
            return false;
        }
1668

zYne's avatar
zYne committed
1669 1670
        if ( ! isset($this->_node)) {
            $this->_node = Doctrine_Node::factory($this,
zYne's avatar
zYne committed
1671 1672 1673
                                              $this->getTable()->getOption('treeImpl'),
                                              $this->getTable()->getOption('treeOptions')
                                              );
zYne's avatar
zYne committed
1674
        }
1675
        
zYne's avatar
zYne committed
1676
        return $this->_node;
1677 1678 1679 1680 1681 1682
    }
    /**
     * used to delete node from tree - MUST BE USE TO DELETE RECORD IF TABLE ACTS AS TREE
     *
     */    
    public function deleteNode() {
zYne's avatar
zYne committed
1683
        $this->getNode()->delete();
1684
    }
1685 1686 1687 1688 1689 1690 1691 1692
    /**
     * returns a string representation of this object
     */
    public function __toString()
    {
        return Doctrine_Lib::getRecordAsString($this);
    }
}