Adds the doCountJoin*() methods.

@param string &$script The script will be modified in this method.
760704
protected function addDoCountJoin(&$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()) {

                    if ($fk->getForeignTableName() != $table->getName()) {

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

                        $joinClassName = $joinedTableObjectBuilder->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 doCountJoin" . $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 won't ever affect the count

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

        if (\$con === null) {
            \$con = Propel::getConnection(" . $this->getPeerClassname() . "::DATABASE_NAME, Propel::CONNECTION_READ);
        }
";
                        $script .= $this->addCriteriaJoin($fk, $table, $joinTable, $joinedTablePeerBuilder);

                        // 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;
    }
";
                    } // if fk table name != this table name
                } // if ! is reference only
            } // foreach column
        } // if count(fk) > 1

    }
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

    }
1176383
protected function addBuildRelations(&$script)
    {
        $script .= "
    /**
     * Build the RelationMap objects for this table relationships
     */
    public function buildRelations()
    {";
        foreach ($this->getTable()->getForeignKeys() as $fkey) {
            $joinCondition = var_export($fkey->getNormalizedMap($fkey->getMapping()), true);
            $onDelete = $fkey->hasOnDelete() ? "'" . $fkey->getOnDelete() . "'" : 'null';
            $onUpdate = $fkey->hasOnUpdate() ? "'" . $fkey->getOnUpdate() . "'" : 'null';
            $isPolymorphic = $fkey->isPolymorphic() ? 'true' : 'false';
            $script .= "
        \$this->addRelation('" . $this->getFKPhpNameAffix($fkey) . "', '" . addslashes($this->getNewStubObjectBuilder($fkey->getForeignTable())->getFullyQualifiedClassName()) . "', RelationMap::MANY_TO_ONE, $joinCondition, $onDelete, $onUpdate, null, $isPolymorphic);";
        }

        foreach ($this->getTable()->getReferrers() as $fkey) {
            $relationName = $this->getRefFKPhpNameAffix($fkey);
            $joinCondition = var_export($fkey->getNormalizedMap($fkey->getMapping()), true);
            $onDelete = $fkey->hasOnDelete() ? "'" . $fkey->getOnDelete() . "'" : 'null';
            $onUpdate = $fkey->hasOnUpdate() ? "'" . $fkey->getOnUpdate() . "'" : 'null';
            $isPolymorphic = $fkey->isPolymorphic() ? 'true' : 'false';
            $script .= "
        \$this->addRelation('$relationName', '" . addslashes($this->getNewStubObjectBuilder($fkey->getTable())->getFullyQualifiedClassName()) . "', RelationMap::ONE_TO_" . ($fkey->isLocalPrimaryKey() ? "ONE" : "MANY") .", $joinCondition, $onDelete, $onUpdate";
            if ($fkey->isLocalPrimaryKey()) {
                 $script .= ", null";
            } else {
                $script .= ", '" . $this->getRefFKPhpNameAffix($fkey, true) . "'";
            }

            $script .= ", $isPolymorphic);";
        }

        foreach ($this->getTable()->getCrossFks() as $crossFKs) {
            foreach ($crossFKs->getCrossForeignKeys() as $crossFK) {
                $relationName = $this->getFKPhpNameAffix($crossFK);
                $pluralName = "'" . $this->getFKPhpNameAffix($crossFK, true) . "'";
                $onDelete = $crossFK->hasOnDelete() ? "'" . $crossFK->getOnDelete() . "'" : 'null';
                $onUpdate = $crossFK->hasOnUpdate() ? "'" . $crossFK->getOnUpdate() . "'" : 'null';
                $script .= "
        \$this->addRelation('$relationName', '" . addslashes($this->getNewStubObjectBuilder($crossFK->getForeignTable())->getFullyQualifiedClassName()) . "', RelationMap::MANY_TO_MANY, array(), $onDelete, $onUpdate, $pluralName);";
            }
        }
        $script .= "
    } // buildRelations()
";
    }
722999
public function add_script($script){
		if ( \is_object($this->obj) ){
			if ( !isset($this->obj->script) ){
				$this->obj->script = '';
			}
			$this->obj->script .= $script;
		}
		return $this;
	}
1108634
protected function addPopulateObject(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * Populates an object of the default type or an object that inherit from the default.
     *
     * @param      array \$row PropelPDO resultset row.
     * @param      int \$startcol The 0-based offset for reading from the resultset row.
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     * @return array (" . $this->getStubObjectBuilder()->getClassName() . " object, last column rank)
     */
    public static function populateObject(\$row, \$startcol = 0)
    {
        \$key = " . $this->getPeerClassname() . "::getPrimaryKeyHashFromRow(\$row, \$startcol);
        if (null !== (\$obj = " . $this->getPeerClassname() . "::getInstanceFromPool(\$key))) {
            // We no longer rehydrate the object, since this can cause data loss.
            // See http://www.propelorm.org/ticket/509
            // \$obj->hydrate(\$row, \$startcol, true); // rehydrate
            \$col = \$startcol + " . $this->getPeerClassname() . "::NUM_HYDRATE_COLUMNS;";
        if ($table->isAbstract()) {
            $script .= "
        } elseif (null == \$key) {
            // empty resultset, probably from a left join
            // since this table is abstract, we can't hydrate an empty object
            \$obj = null;
            \$col = \$startcol + " . $this->getPeerClassname() . "::NUM_HYDRATE_COLUMNS;";
        }
        $script .= "
        } else {";
        if (!$table->getChildrenColumn()) {
            $script .= "
            \$cls = " . $this->getPeerClassname() . "::OM_CLASS;";
        } else {
            $script .= "
            \$cls = " . $this->getPeerClassname() . "::getOMClass(\$row, \$startcol);";
        }
        $script .= "
            \$obj = new \$cls();
            \$col = \$obj->hydrate(\$row, \$startcol);
            " . $this->getPeerClassname() . "::addInstanceToPool(\$obj, \$key);
        }

        return array(\$obj, \$col);
    }
";
    }
670996
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 PropelPDO \$con (optional) The PropelPDO 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, PropelPDO \$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::getConnection(" . $this->getPeerClassname() . "::DATABASE_NAME, Propel::CONNECTION_READ);
        }

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

        \$stmt = " . $this->getPeerClassname() . "::doSelectStmt(\$this->buildPkeyCriteria(), \$con);
        \$row = \$stmt->fetch(PDO::FETCH_NUM);
        \$stmt->closeCursor();
        if (!\$row) {
            throw new PropelException('Cannot find matching row in the database to reload object values.');
        }
        \$this->hydrate(\$row, 0, true); // rehydrate
";

        // support for lazy load columns
        foreach ($table->getColumns() as $col) {
            if ($col->isLazyLoad()) {
                $clo = strtolower($col->getName());
                $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 $fkList) {
            list($refFK, $crossFK) = $fkList;
            $script .= "
            \$this->" . $this->getCrossFKVarName($crossFK) . " = null;";
        }

        $script .= "
        } // if (deep)
    }
";
    }
1059739
protected function addDoInsert(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * Performs an INSERT on the database, given a " . $this->getObjectClassname() . " or Criteria object.
     *
     * @param      mixed \$values Criteria or " . $this->getObjectClassname() . " object containing data that is used to create the INSERT statement.
     * @param      PropelPDO \$con the PropelPDO 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(\$values, PropelPDO \$con = null)
    {
        if (\$con === null) {
            \$con = Propel::getConnection(" . $this->getPeerClassname() . "::DATABASE_NAME, Propel::CONNECTION_WRITE);
        }

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

        foreach ($table->getColumns() as $col) {
            $cfc = $col->getPhpName();
            if ($col->isPrimaryKey() && $col->isAutoIncrement() && $table->getIdMethod() != "none" && !$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() && $table->getIdMethod() != "none" && $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
        \$criteria->setDbName(" . $this->getPeerClassname() . "::DATABASE_NAME);

        try {
            // use transaction because \$criteria could contain info
            // for more than one table (I guess, conceivably)
            \$con->beginTransaction();
            \$pk = " . $this->basePeerClassname . "::doInsert(\$criteria, \$con);
            \$con->commit();
        } catch (Exception \$e) {
            \$con->rollBack();
            throw \$e;
        }

        return \$pk;
    }
";
    }
123206
protected function addClassBody(&$script)
    {
        $table = $this->getTable();

        $this->addAttributes($script);

        $this->addGetIterator($script);

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

        $this->addMakeRoot($script);

        $this->addGetLevel($script);
        $this->addGetPath($script);

        $this->addGetNumberOfChildren($script);
        $this->addGetNumberOfDescendants($script);

        $this->addGetChildren($script);
        $this->addGetDescendants($script);

        $this->addSetLevel($script);

        $this->addSetChildren($script);
        $this->addSetParentNode($script);
        $this->addSetPrevSibling($script);
        $this->addSetNextSibling($script);

        $this->addIsRoot($script);
        $this->addIsLeaf($script);
        $this->addIsEqualTo($script);

        $this->addHasParent($script);
        $this->addHasChildren($script);
        $this->addHasPrevSibling($script);
        $this->addHasNextSibling($script);

        $this->addRetrieveParent($script);
        $this->addRetrieveFirstChild($script);
        $this->addRetrieveLastChild($script);
        $this->addRetrievePrevSibling($script);
        $this->addRetrieveNextSibling($script);

        $this->addInsertAsFirstChildOf($script);
        $this->addInsertAsLastChildOf($script);

        $this->addInsertAsPrevSiblingOf($script);
        $this->addInsertAsNextSiblingOf($script);

        $this->addMoveToFirstChildOf($script);
        $this->addMoveToLastChildOf($script);

        $this->addMoveToPrevSiblingOf($script);
        $this->addMoveToNextSiblingOf($script);

        $this->addInsertAsParentOf($script);

        $this->addGetLeft($script);
        $this->addGetRight($script);
        $this->addGetScopeId($script);

        $this->addSetLeft($script);
        $this->addSetRight($script);
        $this->addSetScopeId($script);
    }
1188059
protected function addColumnAttributes(&$script)
    {

        $table = $this->getTable();

        foreach ($table->getColumns() as $col) {
            $this->addColumnAttributeComment($script, $col);
            $this->addColumnAttributeDeclaration($script, $col);
            if ($col->isLazyLoad()) {
                $this->addColumnAttributeLoaderComment($script, $col);
                $this->addColumnAttributeLoaderDeclaration($script, $col);
            }
            if ($col->getType() == PropelTypes::OBJECT || $col->getType() == PropelTypes::PHP_ARRAY) {
                $this->addColumnAttributeUnserializedComment($script, $col);
                $this->addColumnAttributeUnserializedDeclaration($script, $col);
            }
        }
    }
723204
protected function addDoSave(&$script)
    {
        $table = $this->getTable();

        $reloadOnUpdate = $table->isReloadOnUpdate();
        $reloadOnInsert = $table->isReloadOnInsert();

        $script .= "
    /**
     * Performs the work of inserting or updating the row in the database.
     *
     * If the object is new, it inserts it; otherwise an update is performed.
     * All related objects are also updated in this method.
     *
     * @param      ConnectionInterface \$con";
        if ($reloadOnUpdate || $reloadOnInsert) {
            $script .= "
     * @param      boolean \$skipReload Whether to skip the reload for this object from database.";
        }
        $script .= "
     * @return int             The number of rows affected by this insert/update and any referring fk objects' save() operations.
     * @throws PropelException
     * @see save()
     */
    protected function doSave(ConnectionInterface \$con".($reloadOnUpdate || $reloadOnInsert ? ", \$skipReload = false" : "").")
    {
        \$affectedRows = 0; // initialize var to track total num of affected rows
        if (!\$this->alreadyInSave) {
            \$this->alreadyInSave = true;
";
        if ($reloadOnInsert || $reloadOnUpdate) {
            $script .= "
            \$reloadObject = false;
";
        }

        if (count($table->getForeignKeys())) {

            $script .= "
            // We call the save method on the following object(s) if they
            // were passed to this object by their corresponding set
            // method.  This object relates to these object(s) by a
            // foreign key reference.
";

            foreach ($table->getForeignKeys() as $fk) {
                $aVarName = $this->getFKVarName($fk);
                $script .= "
            if (\$this->$aVarName !== null) {
                if (\$this->" . $aVarName . "->isModified() || \$this->" . $aVarName . "->isNew()) {
                    \$affectedRows += \$this->" . $aVarName . "->save(\$con);
                }
                \$this->set".$this->getFKPhpNameAffix($fk, false)."(\$this->$aVarName);
            }
";
            } // foreach foreign k
        } // if (count(foreign keys))

        $script .= "
            if (\$this->isNew() || \$this->isModified()) {
                // persist changes
                if (\$this->isNew()) {
                    \$this->doInsert(\$con);
                    \$affectedRows += 1;";
        if ($reloadOnInsert) {
            $script .= "
                    if (!\$skipReload) {
                        \$reloadObject = true;
                    }";
        }
        $script .= "
                } else {
                    \$affectedRows += \$this->doUpdate(\$con);";
        if ($reloadOnUpdate) {
            $script .= "
                    if (!\$skipReload) {
                        \$reloadObject = true;
                    }";
        }
        $script .= "
                }";

        // We need to rewind any LOB columns
        foreach ($table->getColumns() as $col) {
            $clo = $col->getLowercasedName();
            if ($col->isLobType()) {
                $script .= "
                // Rewind the $clo LOB column, since PDO does not rewind after inserting value.
                if (\$this->$clo !== null && is_resource(\$this->$clo)) {
                    rewind(\$this->$clo);
                }
";
            }
        }

        $script .= "
                \$this->resetModified();
            }
";

        if ($table->hasCrossForeignKeys()) {
            foreach ($table->getCrossFks() as $crossFKs) {
                $this->addCrossFkScheduledForDeletion($script, $crossFKs);
            }
        }

        foreach ($table->getReferrers() as $refFK) {
            if ($refFK->isLocalPrimaryKey()) {
                $varName = $this->getPKRefFKVarName($refFK);
                $script .= "
            if (\$this->$varName !== null) {
                if (!\$this->{$varName}->isDeleted() && (\$this->{$varName}->isNew() || \$this->{$varName}->isModified())) {
                    \$affectedRows += \$this->{$varName}->save(\$con);
                }
            }
";
            } else {
                $this->addRefFkScheduledForDeletion($script, $refFK);

                $collName = $this->getRefFKCollVarName($refFK);
                $script .= "
            if (\$this->$collName !== null) {
                foreach (\$this->$collName as \$referrerFK) {
                    if (!\$referrerFK->isDeleted() && (\$referrerFK->isNew() || \$referrerFK->isModified())) {
                        \$affectedRows += \$referrerFK->save(\$con);
                    }
                }
            }
";
            } // if refFK->isLocalPrimaryKey()
        } /* foreach getReferrers() */

        $script .= "
            \$this->alreadyInSave = false;
";
        if ($reloadOnInsert || $reloadOnUpdate) {
            $script .= "
            if (\$reloadObject) {
                \$this->reload(\$con);
            }
";
        }
        $script .= "
        }

        return \$affectedRows;
    } // doSave()
";

    }
1175285
protected function addClassBody(&$script)
    {
        $table = $this->getTable();

        // FIXME
        // - Probably the build needs to be customized for supporting
        // tables that are "aliases".  -- definitely a fringe usecase, though.

        $this->addConstants($script);

        $this->addIsCodeBase($script);

        $this->addRetrieveMethods($script);

        $this->addCreateNewRootNode($script);
        $this->addInsertNewRootNode($script);
        $this->addMoveNodeSubTree($script);
        $this->addDeleteNodeSubTree($script);

        $this->addBuildFamilyCriteria($script);
        $this->addBuildTree($script);

        $this->addPopulateNodes($script);
    }
115091
protected function addHookMethods(&$script)
    {
        $hooks = [];
        foreach (['pre', 'post'] as $hook) {
            foreach (['Insert', 'Update', 'Save', 'Delete'] as $action) {
                $hooks[$hook.$action] = false === strpos($script, "function $hook.$action(");
            }
        }
        $script .= $this->renderTemplate('baseObjectMethodHook', $hooks);
    }
723142
protected function addDoSelectJoinAllExcept(&$script)
    {
        $table = $this->getTable();
        $join_behavior = $this->getJoinBehavior();

        // ------------------------------------------------------------------------
        // doSelectJoinAllExcept*()
        // ------------------------------------------------------------------------

        // 2) create a bunch of doSelectJoinAllExcept*() methods
        // -- these were existing in original Torque, so we should keep them for compatibility

        $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 .= "

    /**
     * Selects a collection of " . $this->getObjectClassname() . " objects pre-filled with all related objects except " . $thisTableObjectBuilder->getFKPhpNameAffix($fk) . ".
     *
     * @param      Criteria  \$criteria
     * @param      PropelPDO \$con
     * @param      String    \$join_behavior the type of joins to use, defaults to $join_behavior
     * @return array           Array of " . $this->getObjectClassname() . " objects.
     * @throws PropelException Any exceptions caught during processing will be
     *		 rethrown wrapped into a PropelException.
     */
    public static function doSelectJoinAllExcept" . $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
        // \$criteria->getDbName() will return the same object if not set to another value
        // so == check is okay and faster
        if (\$criteria->getDbName() == Propel::getDefaultDB()) {
            \$criteria->setDbName(" . $this->getPeerClassname() . "::DATABASE_NAME);
        }

        " . $this->getPeerClassname() . "::addSelectColumns(\$criteria);
        \$startcol2 = " . $this->getPeerClassname() . "::NUM_HYDRATE_COLUMNS;
";
            $index = 2;
            foreach ($table->getForeignKeys() as $subfk) {
                // want to cover this case, but the code is not there yet.
                // Why not? - because we would have to alias the tables in the join
                if (!($subfk->getForeignTableName() == $table->getName())) {
                    $joinTable = $table->getDatabase()->getTable($subfk->getForeignTableName());
                    $joinTablePeerBuilder = $this->getNewPeerBuilder($joinTable);
                    $joinClassName = $joinTablePeerBuilder->getObjectClassname();

                    if ($joinClassName != $excludedClassName) {
                        $new_index = $index + 1;
                        $script .= "
        " . $joinTablePeerBuilder->getPeerClassname() . "::addSelectColumns(\$criteria);
        \$startcol$new_index = \$startcol$index + " . $joinTablePeerBuilder->getPeerClassname() . "::NUM_HYDRATE_COLUMNS;
";
                        $index = $new_index;
                    } // if joinClassName not excludeClassName
                } // if subfk is not curr table
            } // foreach [sub] foreign keys

            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 . "::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
";

            $index = 1;
            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());

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

                    $joinClassName = $joinedTableObjectBuilder->getObjectClassname();

                    $interfaceName = $joinClassName;
                    if ($joinTable->getInterface()) {
                        $interfaceName = $this->prefixClassname($joinTable->getInterface());
                    }

                    if ($joinClassName != $excludedClassName) {

                        $index++;

                        $script .= "
                // Add objects for joined $joinClassName rows

                \$key$index = " . $joinedTablePeerBuilder->getPeerClassname() . "::getPrimaryKeyHashFromRow(\$row, \$startcol$index);
                if (\$key$index !== null) {
                    \$obj$index = " . $joinedTablePeerBuilder->getPeerClassname() . "::getInstanceFromPool(\$key$index);
                    if (!\$obj$index) {
    ";

                        if ($joinTable->getChildrenColumn()) {
                            $script .= "
                        \$omClass = " . $joinedTablePeerBuilder->getPeerClassname() . "::getOMClass(\$row, \$startcol$index);
            \$cls = substr('.'.\$omClass, strrpos('.'.\$omClass, '.') + 1);
";
                        } else {
                            $script .= "
                        \$cls = " . $joinedTablePeerBuilder->getPeerClassname() . "::getOMClass();
";
                        } /* $joinTable->getChildrenColumn() */
                        $script .= "
                    " . $this->buildObjectInstanceCreationCode('$obj' . $index, '$cls') . "
                    \$obj" . $index . "->hydrate(\$row, \$startcol$index);
                    " . $joinedTablePeerBuilder->getPeerClassname() . "::addInstanceToPool(\$obj$index, \$key$index);
                } // if \$obj$index already loaded

                // Add the \$obj1 (" . $this->getObjectClassname() . ") to the collection in \$obj" . $index . " (" . $joinedTablePeerBuilder->getObjectClassname() . ")";
                        if ($subfk->isLocalPrimaryKey()) {
                            $script .= "
                \$obj1->set" . $joinedTablePeerBuilder->getObjectClassname() . "(\$obj" . $index . ");";
                        } else {
                            $script .= "
                \$obj" . $index . "->add" . $joinedTableObjectBuilder->getRefFKPhpNameAffix($subfk, $plural = false) . "(\$obj1);";
                        }
                        $script .= "

            } // if joined row is not null
";
                    } // if ($joinClassName != $excludedClassName) {
                } // $subfk->getForeignTableName() != $table->getName()
            } // foreach
            $script .= "
            \$results[] = \$obj1;
        }
        \$stmt->closeCursor();

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

    }
928109
protected function addDoDeleteAll(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * Deletes all rows from the ".$table->getName()." table.
     *
     * @param ConnectionInterface \$con the connection to use
     * @return int The number of affected rows (if supported by underlying database driver).
     */
    public function doDeleteAll(ConnectionInterface \$con = null)
    {
        if (null === \$con) {
            \$con = Propel::getServiceContainer()->getWriteConnection(" . $this->getTableMapClass() . "::DATABASE_NAME);
        }

        // use transaction because \$criteria could contain info
        // for more than one table or we could emulating ON DELETE CASCADE, etc.
        return \$con->transaction(function () use (\$con) {
            \$affectedRows = 0; // initialize var to track total num of affected rows
            ";
        if ($this->isDeleteCascadeEmulationNeeded()) {
            $script .="\$affectedRows += \$this->doOnDeleteCascade(\$con);
            ";
        }
        if ($this->isDeleteSetNullEmulationNeeded()) {
            $script .= "\$this->doOnDeleteSetNull(\$con);
            ";
        }
        $script .= "\$affectedRows += parent::doDeleteAll(\$con);
            // Because this db requires some delete cascade/set null emulation, we have to
            // clear the cached instance *after* the emulation has happened (since
            // instances get re-added by the select statement contained therein).
            {$this->getTableMapClassName()}::clearInstancePool();
            {$this->getTableMapClassName()}::clearRelatedInstancePool();

            return \$affectedRows;
        });
    }
";
    }
1231204
protected function addDoValidate(&$script)
    {
        $table = $this->getTable();

        $script .= "
    /**
     * This function performs the validation work for complex object models.
     *
     * In addition to checking the current object, all related objects will
     * also be validated.  If all pass then <code>true</code> is returned; otherwise
     * an aggregated array of ValidationFailed objects will be returned.
     *
     * @param array \$columns Array of column names to validate.
     * @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objects otherwise.
     */
    protected function doValidate(\$columns = null)
    {
        if (!\$this->alreadyInValidation) {
            \$this->alreadyInValidation = true;
            \$retval = null;

            \$failureMap = array();
";
        if (count($table->getForeignKeys()) != 0) {
            $script .= "

            // We call the validate method on the following object(s) if they
            // were passed to this object by their corresponding set
            // method.  This object relates to these object(s) by a
            // foreign key reference.
";
            foreach ($table->getForeignKeys() as $fk) {
                $aVarName = $this->getFKVarName($fk);
                $script .= "
            if (\$this->" . $aVarName . " !== null) {
                if (!\$this->" . $aVarName . "->validate(\$columns)) {
                    \$failureMap = array_merge(\$failureMap, \$this->" . $aVarName . "->getValidationFailures());
                }
            }
";
            } /* for () */
        } /* if count(fkeys) */

        $script .= "

            if ((\$retval = " . $this->getPeerClassname() . "::doValidate(\$this, \$columns)) !== true) {
                \$failureMap = array_merge(\$failureMap, \$retval);
            }

";

        foreach ($table->getReferrers() as $refFK) {
            if ($refFK->isLocalPrimaryKey()) {
                $varName = $this->getPKRefFKVarName($refFK);
                $script .= "
                if (\$this->$varName !== null) {
                    if (!\$this->" . $varName . "->validate(\$columns)) {
                        \$failureMap = array_merge(\$failureMap, \$this->" . $varName . "->getValidationFailures());
                    }
                }
";
            } else {
                $collName = $this->getRefFKCollVarName($refFK);
                $script .= "
                if (\$this->$collName !== null) {
                    foreach (\$this->$collName as \$referrerFK) {
                        if (!\$referrerFK->validate(\$columns)) {
                            \$failureMap = array_merge(\$failureMap, \$referrerFK->getValidationFailures());
                        }
                    }
                }
";
            }
        } /* foreach getReferrers() */

        $script .= "

            \$this->alreadyInValidation = false;
        }

        return (!empty(\$failureMap) ? \$failureMap : true);
    }
";
    }
374460
protected function addClear(&$script)
    {
        $table = $this->getTable();

        $script .= "
    /**
     * Clears the current object and sets all attributes to their default values
     */
    public function clear()
    {";
        foreach ($table->getColumns() as $col) {
            $clo = strtolower($col->getName());
            $script .= "
        \$this->" . $clo . " = null;";
            if ($col->isLazyLoad()) {
                $script .= "
        \$this->" . $clo . "_isLoaded = false;";
            }
            if ($col->getType() == PropelTypes::OBJECT || $col->getType() == PropelTypes::PHP_ARRAY) {
                $cloUnserialized = $clo . '_unserialized';
                $script .= "
        \$this->$cloUnserialized = null;";
            }
        }

        $script .= "
        \$this->alreadyInSave = false;
        \$this->alreadyInValidation = false;
        \$this->alreadyInClearAllReferencesDeep = false;
        \$this->clearAllReferences();";

        if ($this->hasDefaultValues()) {
            $script .= "
        \$this->applyDefaultValues();";
        }

        $script .= "
        \$this->resetModified();
        \$this->setNew(true);
        \$this->setDeleted(false);
    }
";
    }
212981
protected function addDelete(&$script)
    {
        $script .= "
    /**
     * Performs a DELETE on the database based on the current ModelCriteria
     *
     * @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 function delete(ConnectionInterface \$con = null)
    {
        if (null === \$con) {
            \$con = Propel::getServiceContainer()->getWriteConnection(" . $this->getTableMapClass() . "::DATABASE_NAME);
        }

        \$criteria = \$this;

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

        // use transaction because \$criteria could contain info
        // for more than one table or we could emulating ON DELETE CASCADE, etc.
        return \$con->transaction(function () use (\$con, \$criteria) {
            \$affectedRows = 0; // initialize var to track total num of affected rows
            ";

        if ($this->isDeleteCascadeEmulationNeeded()) {
            $script .= "
            // cloning the Criteria in case it's modified by doSelect() or doSelectStmt()
            \$c = clone \$criteria;
            \$affectedRows += \$c->doOnDeleteCascade(\$con);
            ";
        }

        if ($this->isDeleteSetNullEmulationNeeded()) {
            $script .= "
            // cloning the Criteria in case it's modified by doSelect() or doSelectStmt()
            \$c = clone \$criteria;
            \$c->doOnDeleteSetNull(\$con);
            ";
        }

        $script .= "
            {$this->getTableMapClassName()}::removeInstanceFromPool(\$criteria);
        ";

        $script .= "
            \$affectedRows += ModelCriteria::delete(\$con);
            {$this->getTableMapClassName()}::clearRelatedInstancePool();

            return \$affectedRows;
        });
    }
";
    }