Adds constant and variable declarations that go at the top of the class.

@param string &$script The script will be modified in this method.

@see        addColumnNameConstants()
436959
protected function addConstantsAndAttributes(&$script)
    {
        $dbName = $this->getDatabase()->getName();
        $tableName = $this->getTable()->getName();
        $tablePhpName = $this->getTable()->isAbstract() ? '' : addslashes($this->getStubObjectBuilder()->getFullyQualifiedClassname());
        $script .= "
    /** the default database name for this class */
    const DATABASE_NAME = '$dbName';

    /** the table name for this class */
    const TABLE_NAME = '$tableName';

    /** the related Propel class for this table */
    const OM_CLASS = '$tablePhpName';

    /** the related TableMap class for this table */
    const TM_CLASS = '" . addslashes($this->getTableMapClass()) . "';

    /** The total number of columns. */
    const NUM_COLUMNS = " . $this->getTable()->getNumColumns() . ";

    /** The number of lazy-loaded columns. */
    const NUM_LAZY_LOAD_COLUMNS = " . $this->getTable()->getNumLazyLoadColumns() . ";

    /** The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS) */
    const NUM_HYDRATE_COLUMNS = " . ($this->getTable()->getNumColumns() - $this->getTable()->getNumLazyLoadColumns()) . ";
";
        $this->addColumnNameConstants($script);
        $this->addInheritanceColumnConstants($script);
        if ($this->getTable()->hasEnumColumns()) {
            $this->addEnumColumnConstants($script);
        }

        $script .= "
    /** The default string format for model objects of the related table **/
    const DEFAULT_STRING_FORMAT = '" . $this->getTable()->getDefaultStringFormat() . "';

    /**
     * An identity map to hold any loaded instances of " . $this->getObjectClassname() . " objects.
     * This must be public so that other peer classes can access this when hydrating from JOIN
     * queries.
     * @var        array " . $this->getObjectClassname() . "[]
     */
    public static \$instances = array();

";

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

        $this->addFieldNamesAttribute($script);
        $this->addFieldKeysAttribute($script);

        if ($this->getTable()->hasEnumColumns()) {
            $this->addEnumColumnAttributes($script);
        }
    }
1200430
protected function addHydrate(&$script)
    {
        $this->addHydrateComment($script);
        $this->addHydrateOpen($script);
        $this->addHydrateBody($script);
        $this->addHydrateClose($script);
    }
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;
    }
";
    }
62582
protected function addEnumMethods(&$script)
    {
        foreach ($this->getTable()->getColumns() as $col) {
            /* @var $col Column */
            if ($col->isEnumType()) {
                $script .= "
    /**
     * Gets the SQL value for " . $col->getPhpName() . " ENUM value
     *
     * @param  string \$enumVal ENUM value to get SQL value for
     * @return int SQL value
     */
    public static function get{$col->getPhpName()}SqlValue(\$enumVal)
    {
        return {$this->getPeerClassname()}::getSqlValueForEnum({$this->getColumnConstant($col)}, \$enumVal);
    }
";
            }
        }
    }
1292513
protected function addDoValidate(&$script)
    {
        $table = $this->getTable();
        $script .= "
    /**
     * Validates all modified columns of given " . $this->getObjectClassname() . " object.
     * If parameter \$columns is either a single column name or an array of column names
     * than only those columns are validated.
     *
     * NOTICE: This does not apply to primary or foreign keys for now.
     *
     * @param " . $this->getObjectClassname() . " \$obj The object to validate.
     * @param      mixed \$cols Column name or array of column names.
     *
     * @return mixed TRUE if all columns are valid or the error message of the first invalid column.
     */
    public static function doValidate(\$obj, \$cols = null)
    {
        \$columns = array();

        if (\$cols) {
            \$dbMap = Propel::getDatabaseMap(" . $this->getPeerClassname() . "::DATABASE_NAME);
            \$tableMap = \$dbMap->getTable(" . $this->getPeerClassname() . "::TABLE_NAME);

            if (! is_array(\$cols)) {
                \$cols = array(\$cols);
            }

            foreach (\$cols as \$colName) {
                if (\$tableMap->hasColumn(\$colName)) {
                    \$get = 'get' . \$tableMap->getColumn(\$colName)->getPhpName();
                    \$columns[\$colName] = \$obj->\$get();
                }
            }
        } else {
";
        foreach ($table->getValidators() as $val) {
            $col = $val->getColumn();
            if (!$col->isAutoIncrement()) {
                $script .= "
        if (\$obj->isNew() || \$obj->isColumnModified(" . $this->getColumnConstant($col) . "))
            \$columns[" . $this->getColumnConstant($col) . "] = \$obj->get" . $col->getPhpName() . "();
";
            } // if
        } // foreach

        $script .= "
        }

        return {$this->basePeerClassname}::doValidate(" . $this->getPeerClassname() . "::DATABASE_NAME, " . $this->getPeerClassname() . "::TABLE_NAME, \$columns);
    }
";
    }
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);
        });
    }
";
    }
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, "	");
    }
281369
protected function addClassBody(&$script)
    {
        $this->declareClassFromBuilder($this->getTableMapBuilder());
        $this->declareClasses(
            '\Propel\Runtime\Connection\ConnectionInterface',
            '\Propel\Runtime\ActiveQuery\Criteria'
        );
        $this->addFactory($script);
        $this->addPreSelect($script);
        $this->addPreUpdate($script);
        $this->addPreDelete($script);
        $this->addDoDeleteAll($script);
    }
1118365
protected function addClassOpen(&$script)
    {
        $table = $this->getTable();
        $this->declareClassFromBuilder($this->getPeerBuilder());
        $tableName = $table->getName();
        $tableDesc = $table->getDescription();

        switch ($table->treeMode()) {
            case 'NestedSet':
                $baseClassname = $this->getNestedSetPeerBuilder()->getClassname();
                break;

            case 'MaterializedPath':
            case 'AdjacencyList':
            default:
                $baseClassname = $this->getPeerBuilder()->getClassname();
                break;
        }

        if ($this->getBuildProperty('addClassLevelComment')) {
            $script .= "

/**
 * Skeleton subclass for performing query and update operations on the '$tableName' table.
 *
 * $tableDesc
 *";
            if ($this->getBuildProperty('addTimeStamp')) {
                $now = strftime('%c');
                $script .= "
 * This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on:
 *
 * $now
 *";
            }
            $script .= "
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 * @package    propel.generator." . $this->getPackage() . "
 */";
        }

        $script .= "
class " . $this->getClassname() . " extends $baseClassname
{";
    }
785204
protected function addFromArray(&$script)
    {
        $defaultKeyType = $this->getDefaultKeyType();
        $table = $this->getTable();
        $script .= "
    /**
     * Populates the object using an array.
     *
     * This is particularly useful when populating an object from one of the
     * request arrays (e.g. \$_POST).  This method goes through the column
     * names, checking to see whether a matching key exists in populated
     * array. If so the setByName() method is called for that column.
     *
     * You can specify the key type of the array by additionally passing one
     * of the class type constants BasePeer::TYPE_PHPNAME, BasePeer::TYPE_STUDLYPHPNAME,
     * BasePeer::TYPE_COLNAME, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_NUM.
     * The default key type is the column's BasePeer::$defaultKeyType
     *
     * @param array  \$arr     An array to populate the object from.
     * @param string \$keyType The type of keys the array uses.
     * @return void
     */
    public function fromArray(\$arr, \$keyType = BasePeer::$defaultKeyType)
    {
        \$keys = " . $this->getPeerClassname() . "::getFieldNames(\$keyType);
";
        foreach ($table->getColumns() as $num => $col) {
            $cfc = $col->getPhpName();
            //TODO: remove. not used
            $cptype = $col->getPhpType();
            $script .= "
        if (array_key_exists(\$keys[$num], \$arr)) \$this->set$cfc(\$arr[\$keys[$num]]);";
        } /* foreach */
        $script .= "
    }
";
    }
154014
protected function addClassBody(&$script)
    {
        $table = $this->getTable();

        $this->declareClasses(
            '\Propel\Runtime\ActiveQuery\InstancePoolTrait',
            '\Propel\Runtime\Map\TableMap',
            '\Propel\Runtime\Map\TableMapTrait',
            '\Propel\Runtime\Map\RelationMap',
            '\Propel\Runtime\ActiveQuery\Criteria',
            '\Propel\Runtime\Connection\ConnectionInterface',
            '\Propel\Runtime\Exception\PropelException',
            '\Propel\Runtime\DataFetcher\DataFetcherInterface',
            '\Propel\Runtime\Propel'
        );

        $script .= $this->addConstants();

        $this->addInheritanceColumnConstants($script);
        if ($table->hasValueSetColumns()) {
            $this->addValueSetColumnConstants($script);
        }

        // apply behaviors
        $this->applyBehaviorModifier('staticConstants', $script, "    ");
        $this->applyBehaviorModifier('staticAttributes', $script, "    ");
        $this->applyBehaviorModifier('staticMethods', $script, "    ");

        $this->addAttributes($script);

        $script .= $this->addFieldsAttributes();

        if ($table->hasValueSetColumns()) {
            $this->addValueSetColumnAttributes($script);
            $this->addGetValueSets($script);
            $this->addGetValueSet($script);
        }

        $this->addInitialize($script);
        $this->addBuildRelations($script);
        $this->addGetBehaviors($script);

        $script .= $this->addInstancePool();
        $script .= $this->addClearRelatedInstancePool();

        $this->addGetPrimaryKeyHash($script);
        $this->addGetPrimaryKeyFromRow($script);

        $this->addGetOMClassMethod($script);
        $this->addPopulateObject($script);
        $this->addPopulateObjects($script);

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

        $this->addBuildTableMap($script);

        $this->addDoDelete($script);
        $this->addDoDeleteAll($script);

        $this->addDoInsert($script);
    }
1213888
protected function addHasOnlyDefaultValuesBody(&$script)
    {
        $table = $this->getTable();
        $colsWithDefaults = [];
        foreach ($table->getColumns() as $col) {
            $def = $col->getDefaultValue();
            if ($def !== null && !$def->isExpression()) {
                $colsWithDefaults[] = $col;
            }
        }

        foreach ($colsWithDefaults as $col) {
            /** @var Column $col */
            $clo = $col->getLowercasedName();
            $accessor = "\$this->$clo";
            if ($col->isTemporalType()) {
                $fmt = $this->getTemporalFormatter($col);
                $accessor = "\$this->$clo && \$this->{$clo}->format('$fmt')";
            }
            $script .= "
            if ($accessor !== " . $this->getDefaultValueString($col).") {
                return false;
            }
";
        }
    }
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;
        }
    }
";
    }
1312371
protected function addClassClose(&$script)
    {
        // apply behaviors
        $this->applyBehaviorModifier('staticMethods', $script, "	");

        $script .= "
} // " . $this->getClassname() . "
";
        $this->addStaticTableMapRegistration($script);
    }
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);
    }
758182
protected function addClassOpen(&$script)
    {
        $table = $this->getTable();
        $tableName = $table->getName();
        $tableDesc = $table->getDescription();

        $baseBuilder = $this->getNewQueryInheritanceBuilder($this->getChild());
        $baseClassName = $this->getClassNameFromBuilder($baseBuilder);

        if ($this->getBuildProperty('generator.objectModel.addClassLevelComment')) {
            $script .= "

/**
 * Skeleton subclass for representing a query for one of the subclasses of the '$tableName' table.
 *
 * $tableDesc
 *";
            if ($this->getBuildProperty('generator.objectModel.addTimeStamp')) {
                $now = strftime('%c');
                $script .= "
 * This class was autogenerated by Propel " . $this->getBuildProperty('general.version') . " on:
 *
 * $now
 *";
            }
            $script .= "
 * You should add additional methods to this class to meet the
 * application requirements.  This class will only be generated as
 * long as it does not already exist in the output directory.
 *
 */";
        }
        $script .= "
class "  .$this->getUnqualifiedClassName() . " extends " . $baseClassName . "
{
";
    }
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
";
    }