/app/protected/core/models/RedBeanModel.php
PHP | 3138 lines | 2231 code | 155 blank | 752 comment | 279 complexity | a7a859a6cf6cd1f0fc97544e6a5013c4 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0, LGPL-2.1, BSD-2-Clause, GPL-2.0, GPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /*********************************************************************************
- * Zurmo is a customer relationship management program developed by
- * Zurmo, Inc. Copyright (C) 2012 Zurmo Inc.
- *
- * Zurmo is free software; you can redistribute it and/or modify it under
- * the terms of the GNU General Public License version 3 as published by the
- * Free Software Foundation with the addition of the following permission added
- * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
- * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
- * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
- *
- * Zurmo is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
- * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
- * details.
- *
- * You should have received a copy of the GNU General Public License along with
- * this program; if not, see http://www.gnu.org/licenses or write to the Free
- * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
- * 02110-1301 USA.
- *
- * You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207,
- * Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com.
- ********************************************************************************/
- /**
- * Abstraction over the top of an application database accessed via
- * <a href="http://www.redbeanphp.com/">RedBean</a>. The base class for
- * an MVC model. Replaces the M part of MVC in Yii. Yii maps from the
- * database scheme to the objects, (good for database guys, not so good
- * for OO guys), this maps from objects to the database schema.
- *
- * A domain model is created by extending RedBeanModel and supplying
- * a getDefaultMetadata() method.
- *
- * Static getXxxx() methods can be supplied to query for the given domain
- * models, and instance methods should supply additional behaviour.
- *
- * getDefaultMetadata() returns an array of the class name mapped to
- * an array containing 'members' mapped to an array of member names,
- * (to be accessed as $model->memberName).
- *
- * It can then optionally have, 'relations' mapped
- * to an array of relation names, (to be accessed as $model->relationName),
- * mapped to its type, (the extending model class to which it relates).
- *
- * And it can then optionally have as well, 'rules' mapped to an array of
- * attribute names, (attributes are members and relations), a validator name,
- * and the parameters to the validator, if any, as per the Yii::CModel::rules()
- * method.See http://www.yiiframework.com/wiki/56/reference-model-rules-validation.
- *
- * These are used to automatically and dynamically create the database
- * schema on the fly as opposed to Yii's getting attributes from an
- * already existing schema.
- */
- abstract class RedBeanModel extends ObservableComponent implements Serializable
- {
- /**
- * Models that have not been saved yet have no id as far
- * as the database is concerned. Until they are saved they are
- * assigned a negative id, so that they have identity.
- * @var integer
- */
- private static $nextPseudoId = -1;
- /**
- * Array of static models. Used by Observers @see ObservableComponent to add events to a class.
- * @var array
- */
- private static $_models = array();
- /*
- * The id of an unsaved model.
- * @var integer
- */
- private $pseudoId;
- /**
- * When creating the class heirarchy for bean creation and maintenence, which class is the last class in the
- * lineage to create a bean for? Normally the RedBeanModel is the lastClass in the line, and therefore there
- * will not be a table redbeanmodel. Some classes that extend RedBeanModel might want the line to stop before
- * RedBeanModel since creating a table with just an 'id' would be pointless. @see OwnedModel
- * @var string
- */
- protected static $lastClassInBeanHeirarchy = 'RedBeanModel';
- // A model maps to one or more beans. If Person extends RedBeanModel
- // there is one bean, but if User then extends Person a User model
- // has two beans, the one holding the person data and the one holding
- // the extended User data. In this way in inheritance hierarchy from
- // model is normalized over several tables, one for each extending
- // class.
- private $modelClassNameToBean = array();
- private $attributeNameToBeanAndClassName = array();
- private $attributeNamesNotBelongsToOrManyMany = array();
- private $relationNameToRelationTypeModelClassNameAndOwns = array();
- private $relationNameToRelatedModel = array();
- private $unlinkedRelationNames = array();
- private $validators = array();
- private $attributeNameToErrors = array();
- private $scenarioName = '';
- // An object is automatcally savable if it is new or contains
- // modified members or related objects.
- // If it is newly created and has never had any data put into it
- // it can be saved explicitly but it wont be saved automatically
- // when it is a related model and will be redispensed next
- // time it is referenced.
- protected $modified = false;
- protected $deleted = false;
- protected $isInIsModified = false;
- protected $isInHasErrors = false;
- protected $isInGetErrors = false;
- protected $isValidating = false;
- protected $isSaving = false;
- protected $isNewModel = false;
- /**
- * Can this model be saved when save is called from a related model? True if it can, false if it cannot.
- * Setting this value to false can reduce unnecessary queries to the database. If the models of a class do
- * not change often then it can make sense to set this to false. An example is @see Currency.
- * @var boolean
- */
- protected $isSavableFromRelation = true;
- // Mapping of Yii validators to validators doing things that
- // are either required for RedBean, or that simply implement
- // The semantics that we want.
- private static $yiiValidatorsToRedBeanValidators = array(
- 'CDefaultValueValidator' => 'RedBeanModelDefaultValueValidator',
- 'CNumberValidator' => 'RedBeanModelNumberValidator',
- 'CTypeValidator' => 'RedBeanModelTypeValidator',
- 'CRequiredValidator' => 'RedBeanModelRequiredValidator',
- 'CUniqueValidator' => 'RedBeanModelUniqueValidator',
- 'defaultCalculatedDate' => 'RedBeanModelDefaultCalculatedDateValidator',
- 'readOnly' => 'RedBeanModelReadOnlyValidator',
- 'dateTimeDefault' => 'RedBeanModelDateTimeDefaultValueValidator',
- );
- /**
- * Can the class have a bean. Some classes do not have beans as they are just used for modeling purposes
- * and do not need to store persistant data.
- * @var boolean
- */
- private static $canHaveBean = true;
- /**
- * Used in an extending class's getDefaultMetadata() method to specify
- * that a relation is 1:1 and that the class on the side of the relationship where this is not a column in that
- * model's table. Example: model X HAS_ONE Y. There will be a y_id on the x table. But in Y you would have
- * HAS_ONE_BELONGS_TO X and there would be no column in the y table.
- */
- const HAS_ONE_BELONGS_TO = 0;
- /**
- * Used in an extending class's getDefaultMetadata() method to specify
- * that a relation is 1:M and that the class on the M side of the
- * relation.
- * Note: Currently if you have a relation that is set to HAS_MANY_BELONGS_TO, then that relation name
- * must be the strtolower() same as the related model class name. This is the current support for this
- * relation type. If something different is set, an exception will be thrown.
- */
- const HAS_MANY_BELONGS_TO = 1;
- /**
- * Used in an extending class's getDefaultMetadata() method to specify
- * that a relation is 1:1.
- */
- const HAS_ONE = 2;
- /**
- * Used in an extending class's getDefaultMetadata() method to specify
- * that a relation is 1:M and that the class is on the 1 side of the
- * relation.
- */
- const HAS_MANY = 3;
- /**
- * Used in an extending class's getDefaultMetadata() method to specify
- * that a relation is M:N and that the class on the either side of the
- * relation.
- */
- const MANY_MANY = 4;
- /**
- * Used in an extending class's getDefaultMetadata() method to specify
- * that a 1:1 or 1:M relation is one in which the left side of the relation
- * owns the model or models on the right side, meaning that if the model
- * is deleted it owns the related models and they are deleted along with it.
- * If not specified the related model is independent and is not deleted.
- */
- const OWNED = true;
- /**
- * @see const OWNED for more information.
- * @var boolean
- */
- const NOT_OWNED = false;
- /**
- * Returns the static model of the specified AR class.
- * The model returned is a static instance of the AR class.
- * It is provided for invoking class-level methods (something similar to static class methods.)
- *
- * EVERY derived AR class must override this method as follows,
- * <pre>
- * public static function model($className=__CLASS__)
- * {
- * return parent::model($className);
- * }
- * </pre>
- *
- * @param string $className active record class name.
- * @return CActiveRecord active record model instance.
- */
- public static function model($className = null)
- {
- if ($className == null)
- {
- $className = get_called_class();
- }
- if (isset(self::$_models[$className]))
- {
- return self::$_models[$className];
- }
- else
- {
- $model = self::$_models[$className] = new $className(false);
- return $model;
- }
- }
- /**
- * Gets all the models from the database of the named model type.
- * @param $orderBy TODO
- * @param $modelClassName Pass only when getting it at runtime
- * gets the wrong name.
- * @return An array of models of the type of the extending model.
- */
- public static function getAll($orderBy = null, $sortDescending = false, $modelClassName = null)
- {
- assert('$orderBy === null || is_string($orderBy) && $orderBy != ""');
- assert('is_bool($sortDescending)');
- assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
- $quote = DatabaseCompatibilityUtil::getQuote();
- $orderBySql = null;
- if ($orderBy !== null)
- {
- $orderBySql = "$quote$orderBy$quote";
- if ($sortDescending)
- {
- $orderBySql .= ' desc';
- }
- }
- return static::getSubset(null, null, null, null, $orderBySql, $modelClassName);
- }
- /**
- * Gets a range of models from the database of the named model type.
- * @param $modelClassName
- * @param $joinTablesAdapter null or instance of joinTablesAdapter.
- * @param $offset The zero based index of the first model to be returned.
- * @param $count The number of models to be returned.
- * @param $where
- * @param $orderBy - sql string. Example 'a desc' or 'a.b desc'. Currently only supports non-related attributes
- * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
- * @return An array of models of the type of the extending model.
- */
- public static function getSubset(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
- $offset = null, $count = null,
- $where = null, $orderBy = null,
- $modelClassName = null,
- $selectDistinct = false)
- {
- assert('$offset === null || is_integer($offset) && $offset >= 0');
- assert('$count === null || is_integer($count) && $count >= 1');
- assert('$where === null || is_string ($where) && $where != ""');
- assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
- assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
- if ($modelClassName === null)
- {
- $modelClassName = get_called_class();
- }
- if ($joinTablesAdapter == null)
- {
- $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
- }
- $tableName = self::getTableName($modelClassName);
- $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, $offset, $count, $where,
- $orderBy, false, $selectDistinct);
- $ids = R::getCol($sql);
- $tableName = self::getTableName($modelClassName);
- $beans = R::batch ($tableName, $ids);
- return self::makeModels($beans, $modelClassName);
- }
- /**
- * @param boolean $selectCount If true then make this a count query. If false, select ids from rows.
- * @param array $quotedExtraSelectColumnNameAndAliases - extra columns to select.
- * @return string - sql statement.
- */
- public static function makeSubsetOrCountSqlQuery($tableName,
- RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter,
- $offset = null, $count = null,
- $where = null, $orderBy = null,
- $selectCount = false,
- $selectDistinct = false,
- array $quotedExtraSelectColumnNameAndAliases = array())
- {
- assert('is_string($tableName) && $tableName != ""');
- assert('$offset === null || is_integer($offset) && $offset >= 0');
- assert('$count === null || is_integer($count) && $count >= 1');
- assert('$where === null || is_string ($where) && $where != ""');
- assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
- assert('is_bool($selectCount)');
- assert('is_bool($selectDistinct)');
- $selectQueryAdapter = new RedBeanModelSelectQueryAdapter($selectDistinct);
- if ($selectCount)
- {
- $selectQueryAdapter->addCountClause($tableName);
- }
- else
- {
- $selectQueryAdapter->addClause($tableName, 'id', 'id');
- }
- foreach ($quotedExtraSelectColumnNameAndAliases as $columnName => $columnAlias)
- {
- $selectQueryAdapter->addClauseWithColumnNameOnlyAndNoEnclosure($columnName, $columnAlias);
- }
- return SQLQueryUtil::
- makeQuery($tableName, $selectQueryAdapter, $joinTablesAdapter, $offset, $count, $where, $orderBy);
- }
- /**
- * @param $modelClassName
- * @param $joinTablesAdapter null or instance of joinTablesAdapter.
- * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
- */
- public static function getCount(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
- $where = null, $modelClassName = null, $selectDistinct = false)
- {
- assert('$where === null || is_string($where)');
- assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
- if ($modelClassName === null)
- {
- $modelClassName = get_called_class();
- }
- if ($joinTablesAdapter == null)
- {
- $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
- }
- $tableName = self::getTableName($modelClassName);
- $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, null, null, $where, null, true,
- $selectDistinct);
- $count = R::getCell($sql);
- if ($count === null || empty($count))
- {
- $count = 0;
- }
- return $count;
- }
- /**
- * Gets a model from the database by Id.
- * @param $id Integer Id.
- * @param $modelClassName Pass only when getting it at runtime
- * gets the wrong name.
- * @return A model of the type of the extending model.
- */
- public static function getById($id, $modelClassName = null)
- {
- assert('is_integer($id) && $id > 0');
- assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
- // I would have thought it was correct to user R::load() and get
- // a null, or error or something if the bean doesn't exist, but
- // it still returns a bean. So until I've investigated further
- // I'm using Finder.
- if ($modelClassName === null)
- {
- $modelClassName = get_called_class();
- }
- $tableName = self::getTableName($modelClassName);
- $beans = R::find($tableName, "id = '$id'");
- assert('count($beans) <= 1');
- if (count($beans) == 0)
- {
- throw new NotFoundException();
- }
- return RedBeanModel::makeModel(end($beans), $modelClassName);
- }
- public function getIsNewModel()
- {
- return $this->isNewModel;
- }
- /**
- * Constructs a new model.
- * Important:
- * Models are only constructed with beans by the RedBeanModel. Beans are
- * never used by the application directly.
- * The application can construct a new model object by constructing a
- * model without specifying a bean. In other words, if Php had
- * overloading a constructor with $setDefaults would be public, and
- * a constructor taking a $bean and $forceTreatAsCreation would be private.
- * @param $setDefaults. If false the default validators will not be run
- * on construction. The Yii way is that defaults are
- * filled in after the fact, which is counter the usual
- * for objects.
- * @param $bean A bean. Never specified by an application.
- * @param $forceTreatAsCreation. Never specified by an application.
- * @see getById()
- * @see makeModel()
- * @see makeModels()
- */
- public function __construct($setDefaults = true, RedBean_OODBBean $bean = null, $forceTreatAsCreation = false)
- {
- $this->pseudoId = self::$nextPseudoId--;
- $this->init();
- if ($bean === null)
- {
- foreach (array_reverse(RuntimeUtil::getClassHierarchy(get_class($this), static::$lastClassInBeanHeirarchy)) as $modelClassName)
- {
- if ($modelClassName::getCanHaveBean())
- {
- $tableName = self::getTableName($modelClassName);
- $newBean = R::dispense($tableName);
- $this->modelClassNameToBean[$modelClassName] = $newBean;
- $this->mapAndCacheMetadataAndSetHints($modelClassName, $newBean);
- }
- }
- // The yii way of doing defaults is the the default validator
- // fills in the defaults on attributes that don't have values
- // when you validator, or save. This weird, since when you get
- // a model the things with defaults have not been defaulted!
- // We want that semantic.
- if ($setDefaults)
- {
- $this->runDefaultValidators();
- }
- $forceTreatAsCreation = true;
- }
- else
- {
- assert('$bean->id > 0');
- $first = true;
- foreach (RuntimeUtil::getClassHierarchy(get_class($this), static::$lastClassInBeanHeirarchy) as $modelClassName)
- {
- if ($modelClassName::getCanHaveBean())
- {
- if ($first)
- {
- $lastBean = $bean;
- $first = false;
- }
- else
- {
- $tableName = self::getTableName($modelClassName);
- $lastBean = ZurmoRedBeanLinkManager::getBean($lastBean, $tableName);
- if ($lastBean === null)
- {
- throw new MissingBeanException();
- }
- assert('$lastBean->id > 0');
- }
- $this->modelClassNameToBean[$modelClassName] = $lastBean;
- $this->mapAndCacheMetadataAndSetHints($modelClassName, $lastBean);
- }
- }
- $this->modelClassNameToBean = array_reverse($this->modelClassNameToBean);
- }
- $this->constructDerived($bean, $setDefaults);
- if ($forceTreatAsCreation)
- {
- $this->onCreated();
- }
- else
- {
- $this->onLoaded();
- RedBeanModelsCache::cacheModel($this);
- }
- $this->modified = false;
- }
- // Derived classes can insert additional steps into the construction.
- protected function constructDerived($bean, $setDefaults)
- {
- assert('$bean === null || $bean instanceof RedBean_OODBBean');
- assert('is_bool($setDefaults)');
- }
- /**
- * Utilized when pieces of information need to be constructed on an existing model, that can potentially be
- * missing. For example, if a model is created, then a custom field is added, it is possible the cached model
- * is missing the custom field customFieldData.
- * @param unknown_type $bean
- */
- protected function constructIncomplete($bean)
- {
- assert('$bean === null || $bean instanceof RedBean_OODBBean');
- $this->init();
- }
- public function serialize()
- {
- return serialize(array(
- $this->pseudoId,
- $this->modelClassNameToBean,
- $this->attributeNameToBeanAndClassName,
- $this->attributeNamesNotBelongsToOrManyMany,
- $this->relationNameToRelationTypeModelClassNameAndOwns,
- $this->validators,
- ));
- }
- public function unserialize($data)
- {
- try
- {
- $data = unserialize($data);
- assert('is_array($data)');
- if (count($data) != 6)
- {
- return null;
- }
- $this->pseudoId = $data[0];
- $this->modelClassNameToBean = $data[1];
- $this->attributeNameToBeanAndClassName = $data[2];
- $this->attributeNamesNotBelongsToOrManyMany = $data[3];
- $this->relationNameToRelationTypeModelClassNameAndOwns = $data[4];
- $this->validators = $data[5];
- $this->relationNameToRelatedModel = array();
- $this->unlinkedRelationNames = array();
- $this->attributeNameToErrors = array();
- $this->scenarioName = '';
- $this->modified = false;
- $this->deleted = false;
- $this->isInIsModified = false;
- $this->isInHasErrors = false;
- $this->isInGetErrors = false;
- $this->isValidating = false;
- $this->isSaving = false;
- }
- catch (Exception $e)
- {
- return null;
- }
- }
- /**
- * Overriding constructors must call this function to ensure that
- * they leave the newly constructed instance not modified since
- * anything modifying the class during constructionm will set it
- * modified automatically.
- */
- protected function setNotModified()
- {
- $this->modified = false; // This sets this class to the right state.
- assert('!$this->isModified()'); // This tests that related classes are in the right state.
- }
- /**
- * By default the table name is the lowercased class name. If this
- * conflicts with a database keyword override to return true.
- * RedBean does not quote table names in most cases.
- */
- // Public for unit testing.
- public static function mangleTableName()
- {
- return false;
- }
- /**
- * Returns the table name for a class.
- * For use by RedBeanModelDataProvider. It will not
- * be of any use to an application. Applications
- * should not be doing anything table related.
- * Derived classes can refer directly to the
- * table name.
- */
- public static function getTableName($modelClassName)
- {
- assert('is_string($modelClassName) && $modelClassName != ""');
- $tableName = strtolower($modelClassName);
- if ($modelClassName::mangleTableName())
- {
- $tableName = '_' . $tableName;
- }
- return $tableName;
- }
- /**
- * Returns the table names for an array of classes.
- * For use by RedBeanModelDataProvider. It will not
- * be of any use to an application.
- */
- public static function getTableNames($classNames)
- {
- $tableNames = array();
- foreach ($classNames as $className)
- {
- $tableNames[] = self::getTableName($className);
- }
- return $tableNames;
- }
- /**
- * Used by classes such as containers which use sql to
- * optimize getting models from the database.
- */
- public static function getForeignKeyName($modelClassName, $relationName)
- {
- assert('is_string($modelClassName)');
- assert('$modelClassName != ""');
- $metadata = $modelClassName::getMetadata();
- foreach ($metadata as $modelClassName => $modelClassMetadata)
- {
- if (isset($metadata[$modelClassName]["relations"]) &&
- array_key_exists($relationName, $metadata[$modelClassName]["relations"]))
- {
- $relatedModelClassName = $metadata[$modelClassName]['relations'][$relationName][1];
- self::resolveModelClassNameForClassesWithoutBeans($relatedModelClassName);
- $relatedModelTableName = self::getTableName($relatedModelClassName);
- $columnName = '';
- if (strtolower($relationName) != strtolower($relatedModelClassName))
- {
- $columnName = strtolower($relationName) . '_';
- }
- $columnName .= $relatedModelTableName . '_id';
- return $columnName;
- }
- }
- throw new NotSupportedException;
- }
- /**
- * Called on construction when a new model is created.
- */
- protected function onCreated()
- {
- }
- /**
- * Called on construction when a model is loaded.
- */
- protected function onLoaded()
- {
- }
- /**
- * Called when a model is modified.
- */
- protected function onModified()
- {
- }
- /**
- * Used for mixins.
- */
- protected function mapAndCacheMetadataAndSetHints($modelClassName, RedBean_OODBBean $bean)
- {
- assert('is_string($modelClassName)');
- assert('$modelClassName != ""');
- $metadata = $this->getMetadata();
- if (isset($metadata[$modelClassName]))
- {
- $hints = array();
- if (isset($metadata[$modelClassName]['members']))
- {
- foreach ($metadata[$modelClassName]['members'] as $memberName)
- {
- $this->attributeNameToBeanAndClassName[$memberName] = array($bean, $modelClassName);
- $this->attributeNamesNotBelongsToOrManyMany[] = $memberName;
- if (substr($memberName, -2) == 'Id')
- {
- $columnName = strtolower($memberName);
- $hints[$columnName] = 'id';
- }
- }
- }
- if (isset($metadata[$modelClassName]['relations']))
- {
- foreach ($metadata[$modelClassName]['relations'] as $relationName => $relationTypeModelClassNameAndOwns)
- {
- assert('in_array(count($relationTypeModelClassNameAndOwns), array(2, 3, 4))');
- $relationType = $relationTypeModelClassNameAndOwns[0];
- $relationModelClassName = $relationTypeModelClassNameAndOwns[1];
- if ($relationType == self::HAS_MANY_BELONGS_TO &&
- strtolower($relationName) != strtolower($relationModelClassName))
- {
- $label = 'Relations of type HAS_MANY_BELONGS_TO must have the relation name ' .
- 'the same as the related model class name. Relation: {relationName} ' .
- 'Relation model class name: {relationModelClassName}';
- throw new NotSupportedException(Zurmo::t('Core', $label,
- array('{relationName}' => $relationName,
- '{relationModelClassName}' => $relationModelClassName)));
- }
- if (count($relationTypeModelClassNameAndOwns) >= 3 &&
- $relationTypeModelClassNameAndOwns[2] == self::OWNED)
- {
- $owns = true;
- }
- else
- {
- $owns = false;
- }
- if (count($relationTypeModelClassNameAndOwns) == 4 && $relationType != self::HAS_MANY)
- {
- throw new NotSupportedException();
- }
- if (count($relationTypeModelClassNameAndOwns) == 4)
- {
- $relationPolyOneToManyName = $relationTypeModelClassNameAndOwns[3];
- }
- else
- {
- $relationPolyOneToManyName = null;
- }
- assert('in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, ' .
- 'self::HAS_ONE, self::HAS_MANY, self::MANY_MANY))');
- $this->attributeNameToBeanAndClassName[$relationName] = array($bean, $modelClassName);
- $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName] = array($relationType,
- $relationModelClassName,
- $owns,
- $relationPolyOneToManyName);
- if (!in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, self::MANY_MANY)))
- {
- $this->attributeNamesNotBelongsToOrManyMany[] = $relationName;
- }
- }
- }
- // Add model validators. Parent validators are already applied.
- if (isset($metadata[$modelClassName]['rules']))
- {
- foreach ($metadata[$modelClassName]['rules'] as $validatorMetadata)
- {
- assert('isset($validatorMetadata[0])');
- assert('isset($validatorMetadata[1])');
- $attributeName = $validatorMetadata[0];
- // Each rule in RedBeanModel must specify one attribute name.
- // This was just better style, now it is mandatory.
- assert('strpos($attributeName, " ") === false');
- $validatorName = $validatorMetadata[1];
- $validatorParameters = array_slice($validatorMetadata, 2);
- if (isset(CValidator::$builtInValidators[$validatorName]))
- {
- $validatorName = CValidator::$builtInValidators[$validatorName];
- }
- if (isset(self::$yiiValidatorsToRedBeanValidators[$validatorName]))
- {
- $validatorName = self::$yiiValidatorsToRedBeanValidators[$validatorName];
- }
- $validator = CValidator::createValidator($validatorName, $this, $attributeName, $validatorParameters);
- switch ($validatorName)
- {
- case 'RedBeanModelTypeValidator':
- case 'TypeValidator':
- $columnName = strtolower($attributeName);
- if (array_key_exists($columnName, $hints))
- {
- unset($hints[$columnName]);
- }
- if (in_array($validator->type, array('date', 'datetime', 'blob', 'longblob', 'string', 'text', 'longtext')))
- {
- $hints[$columnName] = $validator->type;
- }
- break;
- case 'CBooleanValidator':
- $columnName = strtolower($attributeName);
- $hints[$columnName] = 'boolean';
- break;
- case 'RedBeanModelUniqueValidator':
- if (!$this->isRelation($attributeName))
- {
- $bean->setMeta("buildcommand.unique", array(array($attributeName)));
- }
- else
- {
- $relatedModelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][1];
- $relatedModelTableName = self::getTableName($relatedModelClassName);
- $columnName = strtolower($attributeName);
- if ($columnName != $relatedModelTableName)
- {
- $columnName .= '_' . $relatedModelTableName;
- }
- $columnName .= '_id';
- $bean->setMeta("buildcommand.unique", array(array($columnName)));
- }
- break;
- }
- $this->validators[] = $validator;
- }
- // Check if we need to update string type to long string type, based on validators.
- if (isset($metadata[$modelClassName]['members']))
- {
- foreach ($metadata[$modelClassName]['members'] as $memberName)
- {
- $allValidators = $this->getValidators($memberName);
- if (!empty($allValidators))
- {
- foreach ($allValidators as $validator)
- {
- if ((get_class($validator) == 'RedBeanModelTypeValidator' ||
- get_class($validator) == 'TypeValidator') &&
- $validator->type == 'string')
- {
- $columnName = strtolower($validator->attributes[0]);
- if (count($allValidators) > 1)
- {
- $haveCStringValidator = false;
- foreach ($allValidators as $innerValidator)
- {
- if (get_class($innerValidator) == 'CStringValidator' &&
- isset($innerValidator->max) &&
- $innerValidator->max > 0)
- {
- if ($innerValidator->max > 65535)
- {
- $hints[$columnName] = 'longtext';
- }
- elseif ($innerValidator->max < 255)
- {
- $hints[$columnName] = "string({$innerValidator->max})";
- }
- else
- {
- $hints[$columnName] = 'text';
- }
- }
- if (get_class($innerValidator) == 'CStringValidator')
- {
- $haveCStringValidator = true;
- }
- }
- if (!$haveCStringValidator)
- {
- $hints[$columnName] = 'text';
- }
- }
- else
- {
- $hints[$columnName] = 'text';
- }
- }
- }
- }
- }
- }
- }
- $bean->setMeta('hint', $hints);
- }
- }
- /**
- * Used for mixins.
- */
- protected function runDefaultValidators()
- {
- foreach ($this->validators as $validator)
- {
- if ($validator instanceof CDefaultValueValidator)
- {
- $validator->validate($this);
- }
- }
- }
- /**
- * For use only by RedBeanModel and RedBeanModels. Beans are
- * never used by the application directly.
- */
- public function getPrimaryBean()
- {
- return end($this->modelClassNameToBean);
- }
- /**
- * Used for optimization.
- */
- public function getClassId($modelClassName)
- {
- assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
- return intval($this->getClassBean($modelClassName)->id); // Trying to combat the slop.
- }
- public function getClassBean($modelClassName)
- {
- assert('is_string($modelClassName)');
- assert('$modelClassName != ""');
- self::resolveModelClassNameForClassesWithoutBeans($modelClassName);
- assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
- return $this->modelClassNameToBean[$modelClassName];
- }
- /**
- * Used for mixins.
- */
- protected function setClassBean($modelClassName, RedBean_OODBBean $bean)
- {
- assert('is_string($modelClassName)');
- assert('$modelClassName != ""');
- assert('!array_key_exists($modelClassName, $this->modelClassNameToBean)');
- $this->modelClassNameToBean = array_merge(array($modelClassName => $bean),
- $this->modelClassNameToBean);
- }
- public function getModelIdentifier()
- {
- return get_class($this) . strval($this->getPrimaryBean()->id);
- }
- /**
- * Returns metadata for the model. Attempts to cache metadata, if it is not already cached.
- * @see getDefaultMetadata()
- * @returns An array of metadata.
- */
- public static function getMetadata()
- {
- try
- {
- return GeneralCache::getEntry(get_called_class() . 'Metadata');
- }
- catch (NotFoundException $e)
- {
- $className = get_called_Class();
- $defaultMetadata = $className::getDefaultMetadata();
- $metadata = array();
- foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy)) as $modelClassName)
- {
- if ($modelClassName::getCanHaveBean())
- {
- if ($modelClassName::canSaveMetadata())
- {
- try
- {
- $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
- $metadata[$modelClassName] = unserialize($globalMetadata->serializedMetadata);
- }
- catch (NotFoundException $e)
- {
- if (isset($defaultMetadata[$modelClassName]))
- {
- $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
- }
- }
- }
- else
- {
- if (isset($defaultMetadata[$modelClassName]))
- {
- $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
- }
- }
- }
- }
- if (YII_DEBUG)
- {
- self::assertMetadataIsValid($metadata);
- }
- GeneralCache::cacheEntry(get_called_class() . 'Metadata', $metadata);
- return $metadata;
- }
- }
- /**
- * By default models cannot save their metadata, allowing
- * them to be loaded quickly because the loading of of
- * metadata can be avoided as much as possible.
- * To make a model able to save its metadata override
- * this method to return true. PUT it before the
- * getDefaultMetadata in the derived class.
- */
- public static function canSaveMetadata()
- {
- return false;
- }
- /**
- * Sets metadata for the model.
- * @see getDefaultMetadata()
- * @returns An array of metadata.
- */
- public static function setMetadata(array $metadata)
- {
- if (YII_DEBUG)
- {
- self::assertMetadataIsValid($metadata);
- }
- $className = get_called_class();
- foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy)) as $modelClassName)
- {
- if ($modelClassName::getCanHaveBean())
- {
- if ($modelClassName::canSaveMetadata())
- {
- if (isset($metadata[$modelClassName]))
- {
- try
- {
- $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
- }
- catch (NotFoundException $e)
- {
- $globalMetadata = new GlobalMetadata();
- $globalMetadata->className = $modelClassName;
- }
- $globalMetadata->serializedMetadata = serialize($metadata[$modelClassName]);
- $saved = $globalMetadata->save();
- // TODO: decide how to deal with this properly if it fails.
- // ie: throw or return false, or something other than
- // this naughty assert.
- assert('$saved');
- }
- }
- }
- }
- RedBeanModelsCache::forgetAllByModelType(get_called_class());
- GeneralCache::forgetEntry(get_called_class() . 'Metadata');
- }
- /**
- * Returns the default meta data for the class.
- * It must be appended to the meta data
- * from the parent model, if any.
- */
- public static function getDefaultMetadata()
- {
- return array();
- }
- protected static function assertMetadataIsValid(array $metadata)
- {
- $className = get_called_Class();
- foreach (RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy) as $modelClassName)
- {
- if ($modelClassName::getCanHaveBean())
- {
- if (isset($metadata[$modelClassName]['members']))
- {
- assert('is_array($metadata[$modelClassName]["members"])');
- foreach ($metadata[$modelClassName]["members"] as $memberName)
- {
- assert('ctype_lower($memberName{0})');
- }
- }
- if (isset($metadata[$modelClassName]['relations']))
- {
- assert('is_array($metadata[$modelClassName]["relations"])');
- foreach ($metadata[$modelClassName]["relations"] as $relationName => $notUsed)
- {
- assert('ctype_lower($relationName{…
Large files files are truncated, but you can click here to view the full file