Adds the copyInto() method, which takes an object and sets contents to match current object.
In complex OM this method includes the $deepCopy param for making copies of related objects.
@param string &$script The script will be modified in this method.
963620
protected function addCopyInto(&$script)
    {
        $table = $this->getTable();

        $script .= "
    /**
     * Sets contents of passed object to values from current object.
     *
     * If desired, this method can also make copies of all associated (fkey referrers)
     * objects.
     *
     * @param      object \$copyObj An object of ".$this->getObjectClassName(true)." (or compatible) type.
     * @param      boolean \$deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
     * @param      boolean \$makeNew Whether to reset autoincrement PKs and make the object new.
     * @throws PropelException
     */
    public function copyInto(\$copyObj, \$deepCopy = false, \$makeNew = true)
    {";

        $autoIncCols = [];
        foreach ($table->getColumns() as $col) {
            /* @var        $col Column */
            if ($col->isAutoIncrement()) {
                $autoIncCols[] = $col;
            }
        }

        foreach ($table->getColumns() as $col) {
            if (!in_array($col, $autoIncCols, true)) {
                $script .= "
        \$copyObj->set".$col->getPhpName()."(\$this->get".$col->getPhpName()."());";
            }
        } // foreach

        // Avoid useless code by checking to see if there are any referrers
        // to this table:
        if (count($table->getReferrers()) > 0) {
            $script .= "

        if (\$deepCopy) {
            // important: temporarily setNew(false) because this affects the behavior of
            // the getter/setter methods for fkey referrer objects.
            \$copyObj->setNew(false);
";
            foreach ($table->getReferrers() as $fk) {
                //HL: commenting out self-referential check below
                //        it seems to work as expected and is probably desirable to have those referrers from same table deep-copied.
                //if ( $fk->getTable()->getName() != $table->getName() ) {

                if ($fk->isLocalPrimaryKey()) {

                    $afx = $this->getRefFKPhpNameAffix($fk, false);
                    $script .= "
            \$relObj = \$this->get$afx();
            if (\$relObj) {
                \$copyObj->set$afx(\$relObj->copy(\$deepCopy));
            }
";
                } else {

                    $script .= "
            foreach (\$this->get".$this->getRefFKPhpNameAffix($fk, true)."() as \$relObj) {
                if (\$relObj !== \$this) {  // ensure that we don't try to copy a reference to ourselves
                    \$copyObj->add".$this->getRefFKPhpNameAffix($fk)."(\$relObj->copy(\$deepCopy));
                }
            }
";
                }
                // HL: commenting out close of self-referential check
                // } /* if tblFK != table */
            } /* foreach */
            $script .= "
        } // if (\$deepCopy)
";
        } /* if (count referrers > 0 ) */

        $script .= "
        if (\$makeNew) {
            \$copyObj->setNew(true);";

        // Note: we're no longer resetting non-autoincrement primary keys to default values
        // due to: http://propel.phpdb.org/trac/ticket/618
        foreach ($autoIncCols as $col) {
            $coldefval = $col->getPhpDefaultValue();
            $coldefval = var_export($coldefval, true);
            $script .= "
            \$copyObj->set".$col->getPhpName() ."($coldefval); // this is a auto-increment column, so set to default value";
        } // foreach
        $script .= "
        }
    }
";
    }
1080588
protected function addEnsureConsistency(&$script)
    {
        $table = $this->getTable();

        $script .= "
    /**
     * Checks and repairs the internal consistency of the object.
     *
     * This method is executed after an already-instantiated object is re-hydrated
     * from the database.  It exists to check any foreign keys to make sure that
     * the objects related to the current object are correct based on foreign key.
     *
     * You can override this method in the stub class, but you should always invoke
     * the base method from the overridden method (i.e. parent::ensureConsistency()),
     * in case your model changes.
     *
     * @throws PropelException
     */
    public function ensureConsistency()
    {
";
        foreach ($table->getColumns() as $col) {

            $clo = strtolower($col->getName());

            if ($col->isForeignKey()) {
                foreach ($col->getForeignKeys() as $fk) {

                    $tblFK = $table->getDatabase()->getTable($fk->getForeignTableName());
                    $colFK = $tblFK->getColumn($fk->getMappedForeignColumn($col->getName()));
                    $varName = $this->getFKVarName($fk);

                    $script .= "
        if (\$this->" . $varName . " !== null && \$this->$clo !== \$this->" . $varName . "->get" . $colFK->getPhpName() . "()) {
            \$this->$varName = null;
        }";
                } // foreach
            } /* if col is foreign key */
        } // foreach

        $script .= "
    } // ensureConsistency
";
    }
721163
protected function addClassBody(&$script)
    {
        $table = $this->getTable();

        $this->addAttributes($script);

        $this->addConstructor($script);

        $this->addCallOverload($script);
        $this->addSetIteratorOptions($script);
        $this->addGetIterator($script);

        $this->addGetNodeObj($script);
        $this->addGetNodePath($script);
        $this->addGetNodeIndex($script);
        $this->addGetNodeLevel($script);

        $this->addHasChildNode($script);
        $this->addGetChildNodeAt($script);
        $this->addGetFirstChildNode($script);
        $this->addGetLastChildNode($script);
        $this->addGetSiblingNode($script);

        $this->addGetParentNode($script);
        $this->addGetAncestors($script);
        $this->addIsRootNode($script);

        $this->addSetNew($script);
        $this->addSetDeleted($script);
        $this->addAddChildNode($script);
        $this->addMoveChildNode($script);
        $this->addSave($script);

        $this->addDelete($script);
        $this->addEquals($script);

        $this->addAttachParentNode($script);
        $this->addAttachChildNode($script);
        $this->addDetachParentNode($script);
        $this->addDetachChildNode($script);
        $this->addShiftChildNodes($script);
        $this->addInsertNewChildNode($script);

        $this->addAdjustStatus($script);
        $this->addAdjustNodePath($script);
    }
705110
protected function addClassBody(&$script)
    {
        $this->declareClassFromBuilder($this->getStubObjectBuilder());
        $this->declareClassFromBuilder($this->getStubPeerBuilder());
        $this->declareClassFromBuilder($this->getStubQueryBuilder());
        $this->declareClasses('Propel', 'PropelException', 'PDO', 'PropelPDO', 'PropelQuery', 'Criteria', 'Persistent', 'BasePeer', 'PropelCollection', 'PropelObjectCollection', 'Exception');

        $table = $this->getTable();
        if (!$table->isAlias()) {
            $this->addConstants($script);
            $this->addAttributes($script);
        }

        if ($table->hasCrossForeignKeys()) {
            foreach ($table->getCrossFks() as $fkList) {
                /* @var $refFK ForeignKey */
                list($refFK, $crossFK) = $fkList;
                $fkName = $this->getFKPhpNameAffix($crossFK, $plural = true);

                if (!$refFK->isLocalPrimaryKey()) {
                    $this->addScheduledForDeletionAttribute($script, $fkName);
                }
            }
        }

        foreach ($table->getReferrers() as $refFK) {
            $fkName = $this->getRefFKPhpNameAffix($refFK, $plural = true);

            if (!$refFK->isLocalPrimaryKey()) {
                $this->addScheduledForDeletionAttribute($script, $fkName);
            }
        }

        if ($this->hasDefaultValues()) {
            $this->addApplyDefaultValues($script);
            $this->addConstructor($script);
        }

        $this->addColumnAccessorMethods($script);
        $this->addColumnMutatorMethods($script);

        $this->addHasOnlyDefaultValues($script);

        $this->addHydrate($script);
        $this->addEnsureConsistency($script);

        if (!$table->isReadOnly()) {
            $this->addManipulationMethods($script);
        }

        if ($this->isAddValidateMethod()) {
            $this->addValidationMethods($script);
        }

        if ($this->isAddGenericAccessors()) {
            $this->addGetByName($script);
            $this->addGetByPosition($script);
            $this->addToArray($script);
        }

        if ($this->isAddGenericMutators()) {
            $this->addSetByName($script);
            $this->addSetByPosition($script);
            $this->addFromArray($script);
        }

        $this->addBuildCriteria($script);
        $this->addBuildPkeyCriteria($script);
        $this->addGetPrimaryKey($script);
        $this->addSetPrimaryKey($script);
        $this->addIsPrimaryKeyNull($script);

        $this->addCopy($script);

        if (!$table->isAlias()) {
            $this->addGetPeer($script);
        }

        $this->addFKMethods($script);
        $this->addRefFKMethods($script);
        $this->addCrossFKMethods($script);
        $this->addClear($script);
        $this->addClearAllReferences($script);

        $this->addPrimaryString($script);

        $this->addIsAlreadyInSave($script);

        // apply behaviors
        $this->applyBehaviorModifier('objectMethods', $script, "	");

        $this->addMagicCall($script);
    }
1260275
protected function addDoDelete(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * Performs a DELETE on the database, given a ".$this->getObjectClassName()." or Criteria object OR a primary key value.
     *
     * @param mixed               \$values Criteria or ".$this->getObjectClassName()." object or primary key or array of primary keys
     *              which is used to create the DELETE statement
     * @param  ConnectionInterface \$con the connection to use
     * @return int             The number of affected rows (if supported by underlying database driver).  This includes CASCADE-related rows
     *                         if supported by native driver or if emulated using Propel.
     * @throws PropelException Any exceptions caught during processing will be
     *                         rethrown wrapped into a PropelException.
     */
     public static function doDelete(\$values, ConnectionInterface \$con = null)
     {
        if (null === \$con) {
            \$con = Propel::getServiceContainer()->getWriteConnection(" . $this->getTableMapClass() . "::DATABASE_NAME);
        }

        if (\$values instanceof Criteria) {";
        $script .= "
            // rename for clarity
            \$criteria = \$values;
        } elseif (\$values instanceof \\".$this->getStubObjectBuilder()->getQualifiedClassName().") { // it's a model object";
        if (count($table->getPrimaryKey()) > 0) {
            $script .= "
            // create criteria based on pk values
            \$criteria = \$values->buildPkeyCriteria();";
        } else {
            $script .= "
            // create criteria based on pk value
            \$criteria = \$values->buildCriteria();";
        }

        $script .= "
        } else { // it's a primary key, or an array of pks";

        if (!$table->getPrimaryKey()) {
            $class = $this->getObjectName();
            $this->declareClass('Propel\\Runtime\\Exception\\LogicException');
            $script .= "
            throw new LogicException('The $class object has no primary key');";
        } else {
            $script .= "
            \$criteria = new Criteria(" . $this->getTableMapClass() . "::DATABASE_NAME);";

            if (1 === count($table->getPrimaryKey())) {
                $pkey = $table->getPrimaryKey();
                $col = array_shift($pkey);
                $script .= "
            \$criteria->add(".$this->getColumnConstant($col).", (array) \$values, Criteria::IN);";
            } else {
                $script .= "
            // primary key is composite; we therefore, expect
            // the primary key passed to be an array of pkey values
            if (count(\$values) == count(\$values, COUNT_RECURSIVE)) {
                // array is not multi-dimensional
                \$values = array(\$values);
            }
            foreach (\$values as \$value) {";
                $i = 0;
                foreach ($table->getPrimaryKey() as $col) {
                    if (0 === $i) {
                        $script .= "
                \$criterion = \$criteria->getNewCriterion(".$this->getColumnConstant($col).", \$value[$i]);";
                    } else {
                        $script .= "
                \$criterion->addAnd(\$criteria->getNewCriterion(".$this->getColumnConstant($col).", \$value[$i]));";
                    }
                    $i++;
                }
                $script .= "
                \$criteria->addOr(\$criterion);";
                $script .= "
            }";
            } /* if count(table->getPrimaryKeys()) */
        }

        $script .= "
        }

        \$query = " . $this->getQueryClassName() . "::create()->mergeWith(\$criteria);

        if (\$values instanceof Criteria) {
            {$this->getTableMapClassName()}::clearInstancePool();
        } elseif (!is_object(\$values)) { // it's a primary key, or an array of pks
            foreach ((array) \$values as \$singleval) {
                {$this->getTableMapClassName()}::removeInstanceFromPool(\$singleval);
            }
        }

        return \$query->delete(\$con);
    }
";
    }
1360742
protected function addAddInstanceToPool(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * Adds an object to the instance pool.
     *
     * Propel keeps cached copies of objects in an instance pool when they are retrieved
     * from the database.  In some cases -- especially when you override doSelect*()
     * methods in your stub classes -- you may need to explicitly add objects
     * to the cache in order to ensure that the same objects are always returned by doSelect*()
     * and retrieveByPK*() calls.
     *
     * @param " . $this->getObjectClassname() . " \$obj A " . $this->getObjectClassname() . " object.
     * @param      string \$key (optional) key to use for instance map (for performance boost if key was already calculated externally).
     */
    public static function addInstanceToPool(\$obj, \$key = null)
    {
        if (Propel::isInstancePoolingEnabled()) {
            if (\$key === null) {";

        $pks = $this->getTable()->getPrimaryKey();

        $php = array();
        foreach ($pks as $pk) {
            if ($pk->isTemporalType()) {
                $php[] = '$obj->get' . $pk->getPhpName() . "('U')";
            } else {
                $php[] = '$obj->get' . $pk->getPhpName() . '()';
            }
        }
        $script .= "
                \$key = " . $this->getInstancePoolKeySnippet($php) . ";";
        $script .= "
            } // if key === null
            " . $this->getPeerClassname() . "::\$instances[\$key] = \$obj;
        }
    }
";
    }
595385
protected function addDoSelectJoin(&$script)
    {
        $table = $this->getTable();
        $className = $this->getObjectClassname();
        $countFK = count($table->getForeignKeys());
        $join_behavior = $this->getJoinBehavior();

        if ($countFK >= 1) {

            foreach ($table->getForeignKeys() as $fk) {

                $joinTable = $table->getDatabase()->getTable($fk->getForeignTableName());

                if (!$joinTable->isForReferenceOnly()) {

                    // This condition is necessary because Propel lacks a system for
                    // aliasing the table if it is the same table.
                    if ($fk->getForeignTableName() != $table->getName()) {

                        $thisTableObjectBuilder = $this->getNewObjectBuilder($table);
                        $joinedTableObjectBuilder = $this->getNewObjectBuilder($joinTable);
                        $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable);

                        $joinClassName = $joinedTableObjectBuilder->getObjectClassname();

                        $script .= "

    /**
     * Selects a collection of $className objects pre-filled with their $joinClassName objects.
     * @param      Criteria  \$criteria
     * @param      PropelPDO \$con
     * @param      String    \$join_behavior the type of joins to use, defaults to $join_behavior
     * @return array           Array of $className objects.
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function doSelectJoin" . $thisTableObjectBuilder->getFKPhpNameAffix($fk, $plural = false) . "(Criteria \$criteria, \$con = null, \$join_behavior = $join_behavior)
    {
        \$criteria = clone \$criteria;

        // Set the correct dbName if it has not been overridden
        if (\$criteria->getDbName() == Propel::getDefaultDB()) {
            \$criteria->setDbName(" . $this->getPeerClassname() . "::DATABASE_NAME);
        }

        " . $this->getPeerClassname() . "::addSelectColumns(\$criteria);
        \$startcol = " . $this->getPeerClassname() . "::NUM_HYDRATE_COLUMNS;
        " . $joinedTablePeerBuilder->getPeerClassname() . "::addSelectColumns(\$criteria);
";

                        $script .= $this->addCriteriaJoin($fk, $table, $joinTable, $joinedTablePeerBuilder);

                        // apply behaviors
                        $this->applyBehaviorModifier('preSelect', $script);

                        $script .= "
        \$stmt = " . $this->basePeerClassname . "::doSelect(\$criteria, \$con);
        \$results = array();

        while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) {
            \$key1 = " . $this->getPeerClassname() . "::getPrimaryKeyHashFromRow(\$row, 0);
            if (null !== (\$obj1 = " . $this->getPeerClassname() . "::getInstanceFromPool(\$key1))) {
                // We no longer rehydrate the object, since this can cause data loss.
                // See http://www.propelorm.org/ticket/509
                // \$obj1->hydrate(\$row, 0, true); // rehydrate
            } else {
";
                        if ($table->getChildrenColumn()) {
                            $script .= "
                \$omClass = " . $this->getPeerClassname() . "::getOMClass(\$row, 0);
                \$cls = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1);
";
                        } else {
                            $script .= "
                \$cls = " . $this->getPeerClassname() . "::getOMClass();
";
                        }
                        $script .= "
                " . $this->buildObjectInstanceCreationCode('$obj1', '$cls') . "
                \$obj1->hydrate(\$row);
                " . $this->getPeerClassname() . "::addInstanceToPool(\$obj1, \$key1);
            } // if \$obj1 already loaded

            \$key2 = " . $joinedTablePeerBuilder->getPeerClassname() . "::getPrimaryKeyHashFromRow(\$row, \$startcol);
            if (\$key2 !== null) {
                \$obj2 = " . $joinedTablePeerBuilder->getPeerClassname() . "::getInstanceFromPool(\$key2);
                if (!\$obj2) {
";
                        if ($joinTable->getChildrenColumn()) {
                            $script .= "
                    \$omClass = " . $joinedTablePeerBuilder->getPeerClassname() . "::getOMClass(\$row, \$startcol);
                    \$cls = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1);
";
                        } else {
                            $script .= "
                    \$cls = " . $joinedTablePeerBuilder->getPeerClassname() . "::getOMClass();
";
                        }

                        $script .= "
                    " . $this->buildObjectInstanceCreationCode('$obj2', '$cls') . "
                    \$obj2->hydrate(\$row, \$startcol);
                    " . $joinedTablePeerBuilder->getPeerClassname() . "::addInstanceToPool(\$obj2, \$key2);
                } // if obj2 already loaded

                // Add the \$obj1 (" . $this->getObjectClassname() . ") to \$obj2 (" . $joinedTablePeerBuilder->getObjectClassname() . ")";
                        if ($fk->isLocalPrimaryKey()) {
                            $script .= "
                // one to one relationship
                \$obj1->set" . $joinedTablePeerBuilder->getObjectClassname() . "(\$obj2);";
                        } else {
                            $script .= "
                \$obj2->add" . $joinedTableObjectBuilder->getRefFKPhpNameAffix($fk, $plural = false) . "(\$obj1);";
                        }
                        $script .= "

            } // if joined row was not null

            \$results[] = \$obj1;
        }
        \$stmt->closeCursor();

        return \$results;
    }
";
                    } // if fk table name != this table name
                } // if ! is reference only
            } // foreach column
        } // if count(fk) > 1

    }
1311826
protected function addGetOMClass_Inheritance(&$script)
    {
        $col = $this->getTable()->getChildrenColumn();
        $script .= "
    /**
     * The returned Class will contain objects of the default type or
     * objects that inherit from the default.
     *
     * @param      array \$row PropelPDO result row.
     * @param      int \$colnum Column to examine for OM class information (first is 0).
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function getOMClass(\$row = 0, \$colnum = 0)
    {
        try {
";
        if ($col->isEnumeratedClasses()) {
            $script .= "
            \$omClass = null;
            \$classKey = \$row[\$colnum + " . ($col->getPosition() - 1) . "];

            switch (\$classKey) {
";
            foreach ($col->getChildren() as $child) {
                $script .= "
                case " . $this->getPeerClassname() . "::CLASSKEY_" . strtoupper($child->getKey()) . ":
                    \$omClass = " . $this->getPeerClassname() . "::CLASSNAME_" . strtoupper($child->getKey()) . ";
                    break;
";
            } /* foreach */
            $script .= "
                default:
                    \$omClass = " . $this->getPeerClassname() . "::OM_CLASS;
";
            $script .= "
            } // switch
";
        } else { /* if not enumerated */
            $script .= "
            \$omClass = \$row[\$colnum + " . ($col->getPosition() - 1) . "];
            \$omClass = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1);
";
        }
        $script .= "
        } catch (Exception \$e) {
            throw new PropelException('Unable to get OM class.', \$e);
        }

        return \$omClass;
    }
";
    }
538498
protected function addObjectAccessor(&$script, Column $col)
    {
        $this->addDefaultAccessorComment($script, $col);
        $this->addDefaultAccessorOpen($script, $col);
        $this->addObjectAccessorBody($script, $col);
        $this->addDefaultAccessorClose($script, $col);
    }
453939
protected function addGetOMClassMethod(&$script)
    {
        $table = $this->getTable();
        if ($table->getChildrenColumn()) {
            $this->addGetOMClass_Inheritance($script);
        } else {
            if ($table->isAbstract()) {
                $this->addGetOMClass_NoInheritance_Abstract($script);
            } else {
                $this->addGetOMClass_NoInheritance($script);
            }
        }
    }
216326
protected function addToArray(&$script)
    {
        $fks = $this->getTable()->getForeignKeys();
        $referrers = $this->getTable()->getReferrers();
        $hasFks = count($fks) > 0 || count($referrers) > 0;
        $objectClassName = $this->getUnqualifiedClassName();
        $pkGetter = $this->getTable()->hasCompositePrimaryKey() ? 'serialize($this->getPrimaryKey())' : '$this->getPrimaryKey()';
        $defaultKeyType = $this->getDefaultKeyType();
        $script .= "
    /**
     * Exports the object as an array.
     *
     * You can specify the key type of the array by passing one of the class
     * type constants.
     *
     * @param     string  \$keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_CAMELNAME,
     *                    TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM.
     *                    Defaults to TableMap::$defaultKeyType.
     * @param     boolean \$includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE.
     * @param     array \$alreadyDumpedObjects List of objects to skip to avoid recursion";
        if ($hasFks) {
            $script .= "
     * @param     boolean \$includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE.";
        }
        $script .= "
     *
     * @return array an associative array containing the field names (as keys) and field values
     */
    public function toArray(\$keyType = TableMap::$defaultKeyType, \$includeLazyLoadColumns = true, \$alreadyDumpedObjects = array()" . ($hasFks ? ", \$includeForeignObjects = false" : '') . ")
    {

        if (isset(\$alreadyDumpedObjects['$objectClassName'][\$this->hashCode()])) {
            return '*RECURSION*';
        }
        \$alreadyDumpedObjects['$objectClassName'][\$this->hashCode()] = true;
        \$keys = ".$this->getTableMapClassName()."::getFieldNames(\$keyType);
        \$result = array(";
        foreach ($this->getTable()->getColumns() as $num => $col) {
            if ($col->isLazyLoad()) {
                $script .= "
            \$keys[$num] => (\$includeLazyLoadColumns) ? \$this->get".$col->getPhpName()."() : null,";
            } else {
                $script .= "
            \$keys[$num] => \$this->get".$col->getPhpName()."(),";
            }
        }
        $script .= "
        );";

        foreach ($this->getTable()->getColumns() as $num => $col) {
            if ($col->isTemporalType()) {
                $script .= "
        if (\$result[\$keys[$num]] instanceof \DateTimeInterface) {
            \$result[\$keys[$num]] = \$result[\$keys[$num]]->format('c');
        }
        ";
            }
        }
        $script .= "
        \$virtualColumns = \$this->virtualColumns;
        foreach (\$virtualColumns as \$key => \$virtualColumn) {
            \$result[\$key] = \$virtualColumn;
        }
        ";
        if ($hasFks) {
            $script .= "
        if (\$includeForeignObjects) {";
            foreach ($fks as $fk) {
                $script .= "
            if (null !== \$this->" . $this->getFKVarName($fk) . ") {
                {$this->addToArrayKeyLookUp($fk->getPhpName(), $fk->getForeignTable(), false)}
                \$result[\$key] = \$this->" . $this->getFKVarName($fk) . "->toArray(\$keyType, \$includeLazyLoadColumns,  \$alreadyDumpedObjects, true);
            }";
            }
            foreach ($referrers as $fk) {
                if ($fk->isLocalPrimaryKey()) {
                    $script .= "
            if (null !== \$this->" . $this->getPKRefFKVarName($fk) . ") {
                {$this->addToArrayKeyLookUp($fk->getRefPhpName(), $fk->getTable(), false)}
                \$result[\$key] = \$this->" . $this->getPKRefFKVarName($fk) . "->toArray(\$keyType, \$includeLazyLoadColumns, \$alreadyDumpedObjects, true);
            }";
                } else {
                    $script .= "
            if (null !== \$this->" . $this->getRefFKCollVarName($fk) . ") {
                {$this->addToArrayKeyLookUp($fk->getRefPhpName(), $fk->getTable(), true)}
                \$result[\$key] = \$this->" . $this->getRefFKCollVarName($fk) . "->toArray(null, false, \$keyType, \$includeLazyLoadColumns, \$alreadyDumpedObjects);
            }";
                }
            }
            $script .= "
        }";
        }
        $script .= "

        return \$result;
    }
";
    }
504672
function script($script, $scriptId = null) {
        if (!isset($scriptId) || !isset($this->_scriptIds[$scriptId])) {
            $this->_scripts[] = $script;
            if (isset($scriptId)) $this->_scriptIds[$scriptId] = true;
        }
    }
122684
protected function addDoInsert(&$script)
    {
        $table = $this->getTable();
        $tableMapClass = $this->getTableMapClass();

        $script .= "
    /**
     * Performs an INSERT on the database, given a ".$this->getObjectClassName()." or Criteria object.
     *
     * @param mixed               \$criteria Criteria or ".$this->getObjectClassName()." object containing data that is used to create the INSERT statement.
     * @param ConnectionInterface \$con the ConnectionInterface connection to use
     * @return mixed           The new primary key.
     * @throws PropelException Any exceptions caught during processing will be
     *                         rethrown wrapped into a PropelException.
     */
    public static function doInsert(\$criteria, ConnectionInterface \$con = null)
    {
        if (null === \$con) {
            \$con = Propel::getServiceContainer()->getWriteConnection(" . $tableMapClass  . "::DATABASE_NAME);
        }

        if (\$criteria instanceof Criteria) {
            \$criteria = clone \$criteria; // rename for clarity
        } else {
            \$criteria = \$criteria->buildCriteria(); // build Criteria from ".$this->getObjectClassName()." object
        }
";

        foreach ($table->getColumns() as $col) {
            if ($col->isPrimaryKey()
                && $col->isAutoIncrement()
                && 'none' !== $table->getIdMethod()
                && !$table->isAllowPkInsert()
            ) {
                $script .= "
        if (\$criteria->containsKey(".$this->getColumnConstant($col).") && \$criteria->keyContainsValue(" . $this->getColumnConstant($col) . ") ) {
            throw new PropelException('Cannot insert a value for auto-increment primary key ('.".$this->getColumnConstant($col).".')');
        }
";
                if (!$this->getPlatform()->supportsInsertNullPk()) {
                    $script .= "
        // remove pkey col since this table uses auto-increment and passing a null value for it is not valid
        \$criteria->remove(".$this->getColumnConstant($col).");
";
                }
            } elseif ($col->isPrimaryKey()
                && $col->isAutoIncrement()
                && 'none' !== $table->getIdMethod()
                && $table->isAllowPkInsert()
                && !$this->getPlatform()->supportsInsertNullPk()
            ) {
                $script .= "
        // remove pkey col if it is null since this table does not accept that
        if (\$criteria->containsKey(".$this->getColumnConstant($col).") && !\$criteria->keyContainsValue(" . $this->getColumnConstant($col) . ") ) {
            \$criteria->remove(".$this->getColumnConstant($col).");
        }
";
            }
        }

        $script .= "

        // Set the correct dbName
        \$query = " . $this->getQueryClassName() . "::create()->mergeWith(\$criteria);

        // use transaction because \$criteria could contain info
        // for more than one table (I guess, conceivably)
        return \$con->transaction(function () use (\$con, \$query) {
            return \$query->doInsert(\$con);
        });
    }
";
    }
1021484
protected function addDoCountJoinAllExcept(&$script)
    {
        $table = $this->getTable();
        $join_behavior = $this->getJoinBehavior();

        $fkeys = $table->getForeignKeys(); // this sep assignment is necessary otherwise sub-loops over
        // getForeignKeys() will cause this to only execute one time.
        foreach ($fkeys as $fk) {

            $tblFK = $table->getDatabase()->getTable($fk->getForeignTableName());

            $excludedTable = $table->getDatabase()->getTable($fk->getForeignTableName());

            $thisTableObjectBuilder = $this->getNewObjectBuilder($table);
            $excludedTableObjectBuilder = $this->getNewObjectBuilder($excludedTable);
            $excludedTablePeerBuilder = $this->getNewPeerBuilder($excludedTable);

            $excludedClassName = $excludedTableObjectBuilder->getObjectClassname();

            $script .= "

    /**
     * Returns the number of rows matching criteria, joining the related " . $thisTableObjectBuilder->getFKPhpNameAffix($fk, $plural = false) . " table
     *
     * @param      Criteria \$criteria
     * @param      boolean \$distinct Whether to select only distinct columns; deprecated: use Criteria->setDistinct() instead.
     * @param      PropelPDO \$con
     * @param      String    \$join_behavior the type of joins to use, defaults to $join_behavior
     * @return int Number of matching rows.
     */
    public static function doCountJoinAllExcept" . $thisTableObjectBuilder->getFKPhpNameAffix($fk, $plural = false) . "(Criteria \$criteria, \$distinct = false, PropelPDO \$con = null, \$join_behavior = $join_behavior)
    {
        // we're going to modify criteria, so copy it first
        \$criteria = clone \$criteria;

        // We need to set the primary table name, since in the case that there are no WHERE columns
        // it will be impossible for the BasePeer::createSelectSql() method to determine which
        // tables go into the FROM clause.
        \$criteria->setPrimaryTableName(" . $this->getPeerClassname() . "::TABLE_NAME);

        if (\$distinct && !in_array(Criteria::DISTINCT, \$criteria->getSelectModifiers())) {
            \$criteria->setDistinct();
        }

        if (!\$criteria->hasSelectClause()) {
            " . $this->getPeerClassname() . "::addSelectColumns(\$criteria);
        }

        \$criteria->clearOrderByColumns(); // ORDER BY should not affect count

        // Set the correct dbName
        \$criteria->setDbName(" . $this->getPeerClassname() . "::DATABASE_NAME);

        if (\$con === null) {
            \$con = Propel::getConnection(" . $this->getPeerClassname() . "::DATABASE_NAME, Propel::CONNECTION_READ);
        }
    ";

            foreach ($table->getForeignKeys() as $subfk) {
                // want to cover this case, but the code is not there yet.
                if ($subfk->getForeignTableName() != $table->getName()) {
                    $joinTable = $table->getDatabase()->getTable($subfk->getForeignTableName());
                    $joinedTablePeerBuilder = $this->getNewPeerBuilder($joinTable);
                    $joinClassName = $joinedTablePeerBuilder->getObjectClassname();

                    if ($joinClassName != $excludedClassName) {
                        $script .= $this->addCriteriaJoin($subfk, $table, $joinTable, $joinedTablePeerBuilder);
                    }
                }
            } // foreach fkeys

            // apply behaviors
            $this->applyBehaviorModifier('preSelect', $script);

            $script .= "
        \$stmt = " . $this->basePeerClassname . "::doCount(\$criteria, \$con);

        if (\$row = \$stmt->fetch(PDO::FETCH_NUM)) {
            \$count = (int) \$row[0];
        } else {
            \$count = 0; // no rows returned; we infer that means 0 matches.
        }
        \$stmt->closeCursor();

        return \$count;
    }
";
        } // foreach fk

    }
512441
protected function addSaveBody(&$script)
    {
        $table = $this->getTable();
        $reloadOnUpdate = $table->isReloadOnUpdate();
        $reloadOnInsert = $table->isReloadOnInsert();

        $script .= "
        if (\$this->isDeleted()) {
            throw new PropelException(\"You cannot save an object that has been deleted.\");
        }

        if (\$this->alreadyInSave) {
            return 0;
        }
 
        if (\$con === null) {
            \$con = Propel::getServiceContainer()->getWriteConnection(".$this->getTableMapClass()."::DATABASE_NAME);
        }

        return \$con->transaction(function () use (\$con".($reloadOnUpdate || $reloadOnInsert ? ", \$skipReload" : "").") {";

        if ($this->getBuildProperty('generator.objectModel.addHooks')) {
            // save with runtime hooks
            $script .= "
            \$ret = \$this->preSave(\$con);
            \$isInsert = \$this->isNew();";
            $this->applyBehaviorModifier('preSave', $script, "            ");
            $script .= "
            if (\$isInsert) {
                \$ret = \$ret && \$this->preInsert(\$con);";
            $this->applyBehaviorModifier('preInsert', $script, "                ");
            $script .= "
            } else {
                \$ret = \$ret && \$this->preUpdate(\$con);";
            $this->applyBehaviorModifier('preUpdate', $script, "                ");
            $script .= "
            }
            if (\$ret) {
                \$affectedRows = \$this->doSave(\$con".($reloadOnUpdate || $reloadOnInsert ? ", \$skipReload" : "").");
                if (\$isInsert) {
                    \$this->postInsert(\$con);";
            $this->applyBehaviorModifier('postInsert', $script, "                    ");
            $script .= "
                } else {
                    \$this->postUpdate(\$con);";
            $this->applyBehaviorModifier('postUpdate', $script, "                    ");
            $script .= "
                }
                \$this->postSave(\$con);";
            $this->applyBehaviorModifier('postSave', $script, "                ");
            $script .= "
                ".$this->getTableMapClassName()."::addInstanceToPool(\$this);
            } else {
                \$affectedRows = 0;
            }

            return \$affectedRows;";
        } else {
            // save without runtime hooks
            $script .= "
            \$isInsert = \$this->isNew();";
            $this->applyBehaviorModifier('preSave', $script, "            ");
            if ($this->hasBehaviorModifier('preUpdate')) {
                $script .= "
            if (!\$isInsert) {";
                $this->applyBehaviorModifier('preUpdate', $script, "                ");
                $script .= "
            }";
            }
            if ($this->hasBehaviorModifier('preInsert')) {
                $script .= "
            if (\$isInsert) {";
                $this->applyBehaviorModifier('preInsert', $script, "                ");
                $script .= "
            }";
            }
            $script .= "
            \$affectedRows = \$this->doSave(\$con".($reloadOnUpdate || $reloadOnInsert ? ", \$skipReload" : "").");";
            $this->applyBehaviorModifier('postSave', $script, "            ");
            if ($this->hasBehaviorModifier('postUpdate')) {
                $script .= "
            if (!\$isInsert) {";
                $this->applyBehaviorModifier('postUpdate', $script, "                ");
                $script .= "
            }";
            }
            if ($this->hasBehaviorModifier('postInsert')) {
                $script .= "
            if (\$isInsert) {";
                $this->applyBehaviorModifier('postInsert', $script, "                ");
                $script .= "
            }";
            }
            $script .= "
            ".$this->getTableMapClassName()."::addInstanceToPool(\$this);

            return \$affectedRows;";
        }

        $script .= "
        });";
    }
846114
protected function addAttributes(&$script)
    {
        $table = $this->getTable();

        $script .= "
    /**
     * The Peer class.
     * Instance provides a convenient way of calling static methods on a class
     * that calling code may not be able to identify.
     * @var        " . $this->getPeerClassname() . "
     */
    protected static \$peer;

    /**
     * The flag var to prevent infinite loop in deep copy
     * @var       boolean
     */
    protected \$startCopy = false;
";
        if (!$table->isAlias()) {
            $this->addColumnAttributes($script);
        }

        foreach ($table->getForeignKeys() as $fk) {
            $this->addFKAttributes($script, $fk);
        }

        foreach ($table->getReferrers() as $refFK) {
            $this->addRefFKAttributes($script, $refFK);
        }

        // many-to-many relationships
        foreach ($table->getCrossFks() as $fkList) {
            $crossFK = $fkList[1];
            $this->addCrossFKAttributes($script, $crossFK);
        }

        $this->addAlreadyInSaveAttribute($script);
        $this->addAlreadyInValidationAttribute($script);
        $this->addAlreadyInClearAllReferencesDeepAttribute($script);

        // apply behaviors
        $this->applyBehaviorModifier('objectAttributes', $script, "	");
    }
127785
protected function addReload(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * Reloads this object from datastore based on primary key and (optionally) resets all associated objects.
     *
     * This will only work if the object has been saved and has a valid primary key set.
     *
     * @param      boolean \$deep (optional) Whether to also de-associated any related objects.
     * @param      ConnectionInterface \$con (optional) The ConnectionInterface connection to use.
     * @return void
     * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db
     */
    public function reload(\$deep = false, ConnectionInterface \$con = null)
    {
        if (\$this->isDeleted()) {
            throw new PropelException(\"Cannot reload a deleted object.\");
        }

        if (\$this->isNew()) {
            throw new PropelException(\"Cannot reload an unsaved object.\");
        }

        if (\$con === null) {
            \$con = Propel::getServiceContainer()->getReadConnection(".$this->getTableMapClass()."::DATABASE_NAME);
        }

        // We don't need to alter the object instance pool; we're just modifying this instance
        // already in the pool.

        \$dataFetcher = ".$this->getQueryClassName()."::create(null, \$this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find(\$con);
        \$row = \$dataFetcher->fetch();
        \$dataFetcher->close();
        if (!\$row) {
            throw new PropelException('Cannot find matching row in the database to reload object values.');
        }
        \$this->hydrate(\$row, 0, true, \$dataFetcher->getIndexType()); // rehydrate
";

        // support for lazy load columns
        foreach ($table->getColumns() as $col) {
            if ($col->isLazyLoad()) {
                $clo = $col->getLowercasedName();
                $script .= "
        // Reset the $clo lazy-load column
        \$this->" . $clo . " = null;
        \$this->".$clo."_isLoaded = false;
";
            }
        }

        $script .= "
        if (\$deep) {  // also de-associate any related objects?
";

        foreach ($table->getForeignKeys() as $fk) {
            $varName = $this->getFKVarName($fk);
            $script .= "
            \$this->".$varName." = null;";
        }

        foreach ($table->getReferrers() as $refFK) {
            if ($refFK->isLocalPrimaryKey()) {
                $script .= "
            \$this->".$this->getPKRefFKVarName($refFK)." = null;
";
            } else {
                $script .= "
            \$this->".$this->getRefFKCollVarName($refFK)." = null;
";
            }
        }

        foreach ($table->getCrossFks() as $crossFKs) {
            $script .= "
            \$this->" . $this->getCrossFKsVarName($crossFKs). " = null;";
        }

        $script .= "
        } // if (deep)
    }
";
    }