PageRenderTime 56ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/app/protected/core/models/RedBeanModel.php

https://bitbucket.org/ddonthula/zurmoimports
PHP | 3138 lines | 2231 code | 155 blank | 752 comment | 279 complexity | a7a859a6cf6cd1f0fc97544e6a5013c4 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-2-Clause, GPL-2.0, GPL-3.0, BSD-3-Clause, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*********************************************************************************
  3. * Zurmo is a customer relationship management program developed by
  4. * Zurmo, Inc. Copyright (C) 2012 Zurmo Inc.
  5. *
  6. * Zurmo is free software; you can redistribute it and/or modify it under
  7. * the terms of the GNU General Public License version 3 as published by the
  8. * Free Software Foundation with the addition of the following permission added
  9. * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
  10. * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
  11. * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
  12. *
  13. * Zurmo is distributed in the hope that it will be useful, but WITHOUT
  14. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  15. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  16. * details.
  17. *
  18. * You should have received a copy of the GNU General Public License along with
  19. * this program; if not, see http://www.gnu.org/licenses or write to the Free
  20. * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  21. * 02110-1301 USA.
  22. *
  23. * You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207,
  24. * Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com.
  25. ********************************************************************************/
  26. /**
  27. * Abstraction over the top of an application database accessed via
  28. * <a href="http://www.redbeanphp.com/">RedBean</a>. The base class for
  29. * an MVC model. Replaces the M part of MVC in Yii. Yii maps from the
  30. * database scheme to the objects, (good for database guys, not so good
  31. * for OO guys), this maps from objects to the database schema.
  32. *
  33. * A domain model is created by extending RedBeanModel and supplying
  34. * a getDefaultMetadata() method.
  35. *
  36. * Static getXxxx() methods can be supplied to query for the given domain
  37. * models, and instance methods should supply additional behaviour.
  38. *
  39. * getDefaultMetadata() returns an array of the class name mapped to
  40. * an array containing 'members' mapped to an array of member names,
  41. * (to be accessed as $model->memberName).
  42. *
  43. * It can then optionally have, 'relations' mapped
  44. * to an array of relation names, (to be accessed as $model->relationName),
  45. * mapped to its type, (the extending model class to which it relates).
  46. *
  47. * And it can then optionally have as well, 'rules' mapped to an array of
  48. * attribute names, (attributes are members and relations), a validator name,
  49. * and the parameters to the validator, if any, as per the Yii::CModel::rules()
  50. * method.See http://www.yiiframework.com/wiki/56/reference-model-rules-validation.
  51. *
  52. * These are used to automatically and dynamically create the database
  53. * schema on the fly as opposed to Yii's getting attributes from an
  54. * already existing schema.
  55. */
  56. abstract class RedBeanModel extends ObservableComponent implements Serializable
  57. {
  58. /**
  59. * Models that have not been saved yet have no id as far
  60. * as the database is concerned. Until they are saved they are
  61. * assigned a negative id, so that they have identity.
  62. * @var integer
  63. */
  64. private static $nextPseudoId = -1;
  65. /**
  66. * Array of static models. Used by Observers @see ObservableComponent to add events to a class.
  67. * @var array
  68. */
  69. private static $_models = array();
  70. /*
  71. * The id of an unsaved model.
  72. * @var integer
  73. */
  74. private $pseudoId;
  75. /**
  76. * When creating the class heirarchy for bean creation and maintenence, which class is the last class in the
  77. * lineage to create a bean for? Normally the RedBeanModel is the lastClass in the line, and therefore there
  78. * will not be a table redbeanmodel. Some classes that extend RedBeanModel might want the line to stop before
  79. * RedBeanModel since creating a table with just an 'id' would be pointless. @see OwnedModel
  80. * @var string
  81. */
  82. protected static $lastClassInBeanHeirarchy = 'RedBeanModel';
  83. // A model maps to one or more beans. If Person extends RedBeanModel
  84. // there is one bean, but if User then extends Person a User model
  85. // has two beans, the one holding the person data and the one holding
  86. // the extended User data. In this way in inheritance hierarchy from
  87. // model is normalized over several tables, one for each extending
  88. // class.
  89. private $modelClassNameToBean = array();
  90. private $attributeNameToBeanAndClassName = array();
  91. private $attributeNamesNotBelongsToOrManyMany = array();
  92. private $relationNameToRelationTypeModelClassNameAndOwns = array();
  93. private $relationNameToRelatedModel = array();
  94. private $unlinkedRelationNames = array();
  95. private $validators = array();
  96. private $attributeNameToErrors = array();
  97. private $scenarioName = '';
  98. // An object is automatcally savable if it is new or contains
  99. // modified members or related objects.
  100. // If it is newly created and has never had any data put into it
  101. // it can be saved explicitly but it wont be saved automatically
  102. // when it is a related model and will be redispensed next
  103. // time it is referenced.
  104. protected $modified = false;
  105. protected $deleted = false;
  106. protected $isInIsModified = false;
  107. protected $isInHasErrors = false;
  108. protected $isInGetErrors = false;
  109. protected $isValidating = false;
  110. protected $isSaving = false;
  111. protected $isNewModel = false;
  112. /**
  113. * Can this model be saved when save is called from a related model? True if it can, false if it cannot.
  114. * Setting this value to false can reduce unnecessary queries to the database. If the models of a class do
  115. * not change often then it can make sense to set this to false. An example is @see Currency.
  116. * @var boolean
  117. */
  118. protected $isSavableFromRelation = true;
  119. // Mapping of Yii validators to validators doing things that
  120. // are either required for RedBean, or that simply implement
  121. // The semantics that we want.
  122. private static $yiiValidatorsToRedBeanValidators = array(
  123. 'CDefaultValueValidator' => 'RedBeanModelDefaultValueValidator',
  124. 'CNumberValidator' => 'RedBeanModelNumberValidator',
  125. 'CTypeValidator' => 'RedBeanModelTypeValidator',
  126. 'CRequiredValidator' => 'RedBeanModelRequiredValidator',
  127. 'CUniqueValidator' => 'RedBeanModelUniqueValidator',
  128. 'defaultCalculatedDate' => 'RedBeanModelDefaultCalculatedDateValidator',
  129. 'readOnly' => 'RedBeanModelReadOnlyValidator',
  130. 'dateTimeDefault' => 'RedBeanModelDateTimeDefaultValueValidator',
  131. );
  132. /**
  133. * Can the class have a bean. Some classes do not have beans as they are just used for modeling purposes
  134. * and do not need to store persistant data.
  135. * @var boolean
  136. */
  137. private static $canHaveBean = true;
  138. /**
  139. * Used in an extending class's getDefaultMetadata() method to specify
  140. * that a relation is 1:1 and that the class on the side of the relationship where this is not a column in that
  141. * 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
  142. * HAS_ONE_BELONGS_TO X and there would be no column in the y table.
  143. */
  144. const HAS_ONE_BELONGS_TO = 0;
  145. /**
  146. * Used in an extending class's getDefaultMetadata() method to specify
  147. * that a relation is 1:M and that the class on the M side of the
  148. * relation.
  149. * Note: Currently if you have a relation that is set to HAS_MANY_BELONGS_TO, then that relation name
  150. * must be the strtolower() same as the related model class name. This is the current support for this
  151. * relation type. If something different is set, an exception will be thrown.
  152. */
  153. const HAS_MANY_BELONGS_TO = 1;
  154. /**
  155. * Used in an extending class's getDefaultMetadata() method to specify
  156. * that a relation is 1:1.
  157. */
  158. const HAS_ONE = 2;
  159. /**
  160. * Used in an extending class's getDefaultMetadata() method to specify
  161. * that a relation is 1:M and that the class is on the 1 side of the
  162. * relation.
  163. */
  164. const HAS_MANY = 3;
  165. /**
  166. * Used in an extending class's getDefaultMetadata() method to specify
  167. * that a relation is M:N and that the class on the either side of the
  168. * relation.
  169. */
  170. const MANY_MANY = 4;
  171. /**
  172. * Used in an extending class's getDefaultMetadata() method to specify
  173. * that a 1:1 or 1:M relation is one in which the left side of the relation
  174. * owns the model or models on the right side, meaning that if the model
  175. * is deleted it owns the related models and they are deleted along with it.
  176. * If not specified the related model is independent and is not deleted.
  177. */
  178. const OWNED = true;
  179. /**
  180. * @see const OWNED for more information.
  181. * @var boolean
  182. */
  183. const NOT_OWNED = false;
  184. /**
  185. * Returns the static model of the specified AR class.
  186. * The model returned is a static instance of the AR class.
  187. * It is provided for invoking class-level methods (something similar to static class methods.)
  188. *
  189. * EVERY derived AR class must override this method as follows,
  190. * <pre>
  191. * public static function model($className=__CLASS__)
  192. * {
  193. * return parent::model($className);
  194. * }
  195. * </pre>
  196. *
  197. * @param string $className active record class name.
  198. * @return CActiveRecord active record model instance.
  199. */
  200. public static function model($className = null)
  201. {
  202. if ($className == null)
  203. {
  204. $className = get_called_class();
  205. }
  206. if (isset(self::$_models[$className]))
  207. {
  208. return self::$_models[$className];
  209. }
  210. else
  211. {
  212. $model = self::$_models[$className] = new $className(false);
  213. return $model;
  214. }
  215. }
  216. /**
  217. * Gets all the models from the database of the named model type.
  218. * @param $orderBy TODO
  219. * @param $modelClassName Pass only when getting it at runtime
  220. * gets the wrong name.
  221. * @return An array of models of the type of the extending model.
  222. */
  223. public static function getAll($orderBy = null, $sortDescending = false, $modelClassName = null)
  224. {
  225. assert('$orderBy === null || is_string($orderBy) && $orderBy != ""');
  226. assert('is_bool($sortDescending)');
  227. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  228. $quote = DatabaseCompatibilityUtil::getQuote();
  229. $orderBySql = null;
  230. if ($orderBy !== null)
  231. {
  232. $orderBySql = "$quote$orderBy$quote";
  233. if ($sortDescending)
  234. {
  235. $orderBySql .= ' desc';
  236. }
  237. }
  238. return static::getSubset(null, null, null, null, $orderBySql, $modelClassName);
  239. }
  240. /**
  241. * Gets a range of models from the database of the named model type.
  242. * @param $modelClassName
  243. * @param $joinTablesAdapter null or instance of joinTablesAdapter.
  244. * @param $offset The zero based index of the first model to be returned.
  245. * @param $count The number of models to be returned.
  246. * @param $where
  247. * @param $orderBy - sql string. Example 'a desc' or 'a.b desc'. Currently only supports non-related attributes
  248. * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
  249. * @return An array of models of the type of the extending model.
  250. */
  251. public static function getSubset(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
  252. $offset = null, $count = null,
  253. $where = null, $orderBy = null,
  254. $modelClassName = null,
  255. $selectDistinct = false)
  256. {
  257. assert('$offset === null || is_integer($offset) && $offset >= 0');
  258. assert('$count === null || is_integer($count) && $count >= 1');
  259. assert('$where === null || is_string ($where) && $where != ""');
  260. assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
  261. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  262. if ($modelClassName === null)
  263. {
  264. $modelClassName = get_called_class();
  265. }
  266. if ($joinTablesAdapter == null)
  267. {
  268. $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
  269. }
  270. $tableName = self::getTableName($modelClassName);
  271. $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, $offset, $count, $where,
  272. $orderBy, false, $selectDistinct);
  273. $ids = R::getCol($sql);
  274. $tableName = self::getTableName($modelClassName);
  275. $beans = R::batch ($tableName, $ids);
  276. return self::makeModels($beans, $modelClassName);
  277. }
  278. /**
  279. * @param boolean $selectCount If true then make this a count query. If false, select ids from rows.
  280. * @param array $quotedExtraSelectColumnNameAndAliases - extra columns to select.
  281. * @return string - sql statement.
  282. */
  283. public static function makeSubsetOrCountSqlQuery($tableName,
  284. RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter,
  285. $offset = null, $count = null,
  286. $where = null, $orderBy = null,
  287. $selectCount = false,
  288. $selectDistinct = false,
  289. array $quotedExtraSelectColumnNameAndAliases = array())
  290. {
  291. assert('is_string($tableName) && $tableName != ""');
  292. assert('$offset === null || is_integer($offset) && $offset >= 0');
  293. assert('$count === null || is_integer($count) && $count >= 1');
  294. assert('$where === null || is_string ($where) && $where != ""');
  295. assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
  296. assert('is_bool($selectCount)');
  297. assert('is_bool($selectDistinct)');
  298. $selectQueryAdapter = new RedBeanModelSelectQueryAdapter($selectDistinct);
  299. if ($selectCount)
  300. {
  301. $selectQueryAdapter->addCountClause($tableName);
  302. }
  303. else
  304. {
  305. $selectQueryAdapter->addClause($tableName, 'id', 'id');
  306. }
  307. foreach ($quotedExtraSelectColumnNameAndAliases as $columnName => $columnAlias)
  308. {
  309. $selectQueryAdapter->addClauseWithColumnNameOnlyAndNoEnclosure($columnName, $columnAlias);
  310. }
  311. return SQLQueryUtil::
  312. makeQuery($tableName, $selectQueryAdapter, $joinTablesAdapter, $offset, $count, $where, $orderBy);
  313. }
  314. /**
  315. * @param $modelClassName
  316. * @param $joinTablesAdapter null or instance of joinTablesAdapter.
  317. * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
  318. */
  319. public static function getCount(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
  320. $where = null, $modelClassName = null, $selectDistinct = false)
  321. {
  322. assert('$where === null || is_string($where)');
  323. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  324. if ($modelClassName === null)
  325. {
  326. $modelClassName = get_called_class();
  327. }
  328. if ($joinTablesAdapter == null)
  329. {
  330. $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
  331. }
  332. $tableName = self::getTableName($modelClassName);
  333. $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, null, null, $where, null, true,
  334. $selectDistinct);
  335. $count = R::getCell($sql);
  336. if ($count === null || empty($count))
  337. {
  338. $count = 0;
  339. }
  340. return $count;
  341. }
  342. /**
  343. * Gets a model from the database by Id.
  344. * @param $id Integer Id.
  345. * @param $modelClassName Pass only when getting it at runtime
  346. * gets the wrong name.
  347. * @return A model of the type of the extending model.
  348. */
  349. public static function getById($id, $modelClassName = null)
  350. {
  351. assert('is_integer($id) && $id > 0');
  352. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  353. // I would have thought it was correct to user R::load() and get
  354. // a null, or error or something if the bean doesn't exist, but
  355. // it still returns a bean. So until I've investigated further
  356. // I'm using Finder.
  357. if ($modelClassName === null)
  358. {
  359. $modelClassName = get_called_class();
  360. }
  361. $tableName = self::getTableName($modelClassName);
  362. $beans = R::find($tableName, "id = '$id'");
  363. assert('count($beans) <= 1');
  364. if (count($beans) == 0)
  365. {
  366. throw new NotFoundException();
  367. }
  368. return RedBeanModel::makeModel(end($beans), $modelClassName);
  369. }
  370. public function getIsNewModel()
  371. {
  372. return $this->isNewModel;
  373. }
  374. /**
  375. * Constructs a new model.
  376. * Important:
  377. * Models are only constructed with beans by the RedBeanModel. Beans are
  378. * never used by the application directly.
  379. * The application can construct a new model object by constructing a
  380. * model without specifying a bean. In other words, if Php had
  381. * overloading a constructor with $setDefaults would be public, and
  382. * a constructor taking a $bean and $forceTreatAsCreation would be private.
  383. * @param $setDefaults. If false the default validators will not be run
  384. * on construction. The Yii way is that defaults are
  385. * filled in after the fact, which is counter the usual
  386. * for objects.
  387. * @param $bean A bean. Never specified by an application.
  388. * @param $forceTreatAsCreation. Never specified by an application.
  389. * @see getById()
  390. * @see makeModel()
  391. * @see makeModels()
  392. */
  393. public function __construct($setDefaults = true, RedBean_OODBBean $bean = null, $forceTreatAsCreation = false)
  394. {
  395. $this->pseudoId = self::$nextPseudoId--;
  396. $this->init();
  397. if ($bean === null)
  398. {
  399. foreach (array_reverse(RuntimeUtil::getClassHierarchy(get_class($this), static::$lastClassInBeanHeirarchy)) as $modelClassName)
  400. {
  401. if ($modelClassName::getCanHaveBean())
  402. {
  403. $tableName = self::getTableName($modelClassName);
  404. $newBean = R::dispense($tableName);
  405. $this->modelClassNameToBean[$modelClassName] = $newBean;
  406. $this->mapAndCacheMetadataAndSetHints($modelClassName, $newBean);
  407. }
  408. }
  409. // The yii way of doing defaults is the the default validator
  410. // fills in the defaults on attributes that don't have values
  411. // when you validator, or save. This weird, since when you get
  412. // a model the things with defaults have not been defaulted!
  413. // We want that semantic.
  414. if ($setDefaults)
  415. {
  416. $this->runDefaultValidators();
  417. }
  418. $forceTreatAsCreation = true;
  419. }
  420. else
  421. {
  422. assert('$bean->id > 0');
  423. $first = true;
  424. foreach (RuntimeUtil::getClassHierarchy(get_class($this), static::$lastClassInBeanHeirarchy) as $modelClassName)
  425. {
  426. if ($modelClassName::getCanHaveBean())
  427. {
  428. if ($first)
  429. {
  430. $lastBean = $bean;
  431. $first = false;
  432. }
  433. else
  434. {
  435. $tableName = self::getTableName($modelClassName);
  436. $lastBean = ZurmoRedBeanLinkManager::getBean($lastBean, $tableName);
  437. if ($lastBean === null)
  438. {
  439. throw new MissingBeanException();
  440. }
  441. assert('$lastBean->id > 0');
  442. }
  443. $this->modelClassNameToBean[$modelClassName] = $lastBean;
  444. $this->mapAndCacheMetadataAndSetHints($modelClassName, $lastBean);
  445. }
  446. }
  447. $this->modelClassNameToBean = array_reverse($this->modelClassNameToBean);
  448. }
  449. $this->constructDerived($bean, $setDefaults);
  450. if ($forceTreatAsCreation)
  451. {
  452. $this->onCreated();
  453. }
  454. else
  455. {
  456. $this->onLoaded();
  457. RedBeanModelsCache::cacheModel($this);
  458. }
  459. $this->modified = false;
  460. }
  461. // Derived classes can insert additional steps into the construction.
  462. protected function constructDerived($bean, $setDefaults)
  463. {
  464. assert('$bean === null || $bean instanceof RedBean_OODBBean');
  465. assert('is_bool($setDefaults)');
  466. }
  467. /**
  468. * Utilized when pieces of information need to be constructed on an existing model, that can potentially be
  469. * missing. For example, if a model is created, then a custom field is added, it is possible the cached model
  470. * is missing the custom field customFieldData.
  471. * @param unknown_type $bean
  472. */
  473. protected function constructIncomplete($bean)
  474. {
  475. assert('$bean === null || $bean instanceof RedBean_OODBBean');
  476. $this->init();
  477. }
  478. public function serialize()
  479. {
  480. return serialize(array(
  481. $this->pseudoId,
  482. $this->modelClassNameToBean,
  483. $this->attributeNameToBeanAndClassName,
  484. $this->attributeNamesNotBelongsToOrManyMany,
  485. $this->relationNameToRelationTypeModelClassNameAndOwns,
  486. $this->validators,
  487. ));
  488. }
  489. public function unserialize($data)
  490. {
  491. try
  492. {
  493. $data = unserialize($data);
  494. assert('is_array($data)');
  495. if (count($data) != 6)
  496. {
  497. return null;
  498. }
  499. $this->pseudoId = $data[0];
  500. $this->modelClassNameToBean = $data[1];
  501. $this->attributeNameToBeanAndClassName = $data[2];
  502. $this->attributeNamesNotBelongsToOrManyMany = $data[3];
  503. $this->relationNameToRelationTypeModelClassNameAndOwns = $data[4];
  504. $this->validators = $data[5];
  505. $this->relationNameToRelatedModel = array();
  506. $this->unlinkedRelationNames = array();
  507. $this->attributeNameToErrors = array();
  508. $this->scenarioName = '';
  509. $this->modified = false;
  510. $this->deleted = false;
  511. $this->isInIsModified = false;
  512. $this->isInHasErrors = false;
  513. $this->isInGetErrors = false;
  514. $this->isValidating = false;
  515. $this->isSaving = false;
  516. }
  517. catch (Exception $e)
  518. {
  519. return null;
  520. }
  521. }
  522. /**
  523. * Overriding constructors must call this function to ensure that
  524. * they leave the newly constructed instance not modified since
  525. * anything modifying the class during constructionm will set it
  526. * modified automatically.
  527. */
  528. protected function setNotModified()
  529. {
  530. $this->modified = false; // This sets this class to the right state.
  531. assert('!$this->isModified()'); // This tests that related classes are in the right state.
  532. }
  533. /**
  534. * By default the table name is the lowercased class name. If this
  535. * conflicts with a database keyword override to return true.
  536. * RedBean does not quote table names in most cases.
  537. */
  538. // Public for unit testing.
  539. public static function mangleTableName()
  540. {
  541. return false;
  542. }
  543. /**
  544. * Returns the table name for a class.
  545. * For use by RedBeanModelDataProvider. It will not
  546. * be of any use to an application. Applications
  547. * should not be doing anything table related.
  548. * Derived classes can refer directly to the
  549. * table name.
  550. */
  551. public static function getTableName($modelClassName)
  552. {
  553. assert('is_string($modelClassName) && $modelClassName != ""');
  554. $tableName = strtolower($modelClassName);
  555. if ($modelClassName::mangleTableName())
  556. {
  557. $tableName = '_' . $tableName;
  558. }
  559. return $tableName;
  560. }
  561. /**
  562. * Returns the table names for an array of classes.
  563. * For use by RedBeanModelDataProvider. It will not
  564. * be of any use to an application.
  565. */
  566. public static function getTableNames($classNames)
  567. {
  568. $tableNames = array();
  569. foreach ($classNames as $className)
  570. {
  571. $tableNames[] = self::getTableName($className);
  572. }
  573. return $tableNames;
  574. }
  575. /**
  576. * Used by classes such as containers which use sql to
  577. * optimize getting models from the database.
  578. */
  579. public static function getForeignKeyName($modelClassName, $relationName)
  580. {
  581. assert('is_string($modelClassName)');
  582. assert('$modelClassName != ""');
  583. $metadata = $modelClassName::getMetadata();
  584. foreach ($metadata as $modelClassName => $modelClassMetadata)
  585. {
  586. if (isset($metadata[$modelClassName]["relations"]) &&
  587. array_key_exists($relationName, $metadata[$modelClassName]["relations"]))
  588. {
  589. $relatedModelClassName = $metadata[$modelClassName]['relations'][$relationName][1];
  590. self::resolveModelClassNameForClassesWithoutBeans($relatedModelClassName);
  591. $relatedModelTableName = self::getTableName($relatedModelClassName);
  592. $columnName = '';
  593. if (strtolower($relationName) != strtolower($relatedModelClassName))
  594. {
  595. $columnName = strtolower($relationName) . '_';
  596. }
  597. $columnName .= $relatedModelTableName . '_id';
  598. return $columnName;
  599. }
  600. }
  601. throw new NotSupportedException;
  602. }
  603. /**
  604. * Called on construction when a new model is created.
  605. */
  606. protected function onCreated()
  607. {
  608. }
  609. /**
  610. * Called on construction when a model is loaded.
  611. */
  612. protected function onLoaded()
  613. {
  614. }
  615. /**
  616. * Called when a model is modified.
  617. */
  618. protected function onModified()
  619. {
  620. }
  621. /**
  622. * Used for mixins.
  623. */
  624. protected function mapAndCacheMetadataAndSetHints($modelClassName, RedBean_OODBBean $bean)
  625. {
  626. assert('is_string($modelClassName)');
  627. assert('$modelClassName != ""');
  628. $metadata = $this->getMetadata();
  629. if (isset($metadata[$modelClassName]))
  630. {
  631. $hints = array();
  632. if (isset($metadata[$modelClassName]['members']))
  633. {
  634. foreach ($metadata[$modelClassName]['members'] as $memberName)
  635. {
  636. $this->attributeNameToBeanAndClassName[$memberName] = array($bean, $modelClassName);
  637. $this->attributeNamesNotBelongsToOrManyMany[] = $memberName;
  638. if (substr($memberName, -2) == 'Id')
  639. {
  640. $columnName = strtolower($memberName);
  641. $hints[$columnName] = 'id';
  642. }
  643. }
  644. }
  645. if (isset($metadata[$modelClassName]['relations']))
  646. {
  647. foreach ($metadata[$modelClassName]['relations'] as $relationName => $relationTypeModelClassNameAndOwns)
  648. {
  649. assert('in_array(count($relationTypeModelClassNameAndOwns), array(2, 3, 4))');
  650. $relationType = $relationTypeModelClassNameAndOwns[0];
  651. $relationModelClassName = $relationTypeModelClassNameAndOwns[1];
  652. if ($relationType == self::HAS_MANY_BELONGS_TO &&
  653. strtolower($relationName) != strtolower($relationModelClassName))
  654. {
  655. $label = 'Relations of type HAS_MANY_BELONGS_TO must have the relation name ' .
  656. 'the same as the related model class name. Relation: {relationName} ' .
  657. 'Relation model class name: {relationModelClassName}';
  658. throw new NotSupportedException(Zurmo::t('Core', $label,
  659. array('{relationName}' => $relationName,
  660. '{relationModelClassName}' => $relationModelClassName)));
  661. }
  662. if (count($relationTypeModelClassNameAndOwns) >= 3 &&
  663. $relationTypeModelClassNameAndOwns[2] == self::OWNED)
  664. {
  665. $owns = true;
  666. }
  667. else
  668. {
  669. $owns = false;
  670. }
  671. if (count($relationTypeModelClassNameAndOwns) == 4 && $relationType != self::HAS_MANY)
  672. {
  673. throw new NotSupportedException();
  674. }
  675. if (count($relationTypeModelClassNameAndOwns) == 4)
  676. {
  677. $relationPolyOneToManyName = $relationTypeModelClassNameAndOwns[3];
  678. }
  679. else
  680. {
  681. $relationPolyOneToManyName = null;
  682. }
  683. assert('in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, ' .
  684. 'self::HAS_ONE, self::HAS_MANY, self::MANY_MANY))');
  685. $this->attributeNameToBeanAndClassName[$relationName] = array($bean, $modelClassName);
  686. $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName] = array($relationType,
  687. $relationModelClassName,
  688. $owns,
  689. $relationPolyOneToManyName);
  690. if (!in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, self::MANY_MANY)))
  691. {
  692. $this->attributeNamesNotBelongsToOrManyMany[] = $relationName;
  693. }
  694. }
  695. }
  696. // Add model validators. Parent validators are already applied.
  697. if (isset($metadata[$modelClassName]['rules']))
  698. {
  699. foreach ($metadata[$modelClassName]['rules'] as $validatorMetadata)
  700. {
  701. assert('isset($validatorMetadata[0])');
  702. assert('isset($validatorMetadata[1])');
  703. $attributeName = $validatorMetadata[0];
  704. // Each rule in RedBeanModel must specify one attribute name.
  705. // This was just better style, now it is mandatory.
  706. assert('strpos($attributeName, " ") === false');
  707. $validatorName = $validatorMetadata[1];
  708. $validatorParameters = array_slice($validatorMetadata, 2);
  709. if (isset(CValidator::$builtInValidators[$validatorName]))
  710. {
  711. $validatorName = CValidator::$builtInValidators[$validatorName];
  712. }
  713. if (isset(self::$yiiValidatorsToRedBeanValidators[$validatorName]))
  714. {
  715. $validatorName = self::$yiiValidatorsToRedBeanValidators[$validatorName];
  716. }
  717. $validator = CValidator::createValidator($validatorName, $this, $attributeName, $validatorParameters);
  718. switch ($validatorName)
  719. {
  720. case 'RedBeanModelTypeValidator':
  721. case 'TypeValidator':
  722. $columnName = strtolower($attributeName);
  723. if (array_key_exists($columnName, $hints))
  724. {
  725. unset($hints[$columnName]);
  726. }
  727. if (in_array($validator->type, array('date', 'datetime', 'blob', 'longblob', 'string', 'text', 'longtext')))
  728. {
  729. $hints[$columnName] = $validator->type;
  730. }
  731. break;
  732. case 'CBooleanValidator':
  733. $columnName = strtolower($attributeName);
  734. $hints[$columnName] = 'boolean';
  735. break;
  736. case 'RedBeanModelUniqueValidator':
  737. if (!$this->isRelation($attributeName))
  738. {
  739. $bean->setMeta("buildcommand.unique", array(array($attributeName)));
  740. }
  741. else
  742. {
  743. $relatedModelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][1];
  744. $relatedModelTableName = self::getTableName($relatedModelClassName);
  745. $columnName = strtolower($attributeName);
  746. if ($columnName != $relatedModelTableName)
  747. {
  748. $columnName .= '_' . $relatedModelTableName;
  749. }
  750. $columnName .= '_id';
  751. $bean->setMeta("buildcommand.unique", array(array($columnName)));
  752. }
  753. break;
  754. }
  755. $this->validators[] = $validator;
  756. }
  757. // Check if we need to update string type to long string type, based on validators.
  758. if (isset($metadata[$modelClassName]['members']))
  759. {
  760. foreach ($metadata[$modelClassName]['members'] as $memberName)
  761. {
  762. $allValidators = $this->getValidators($memberName);
  763. if (!empty($allValidators))
  764. {
  765. foreach ($allValidators as $validator)
  766. {
  767. if ((get_class($validator) == 'RedBeanModelTypeValidator' ||
  768. get_class($validator) == 'TypeValidator') &&
  769. $validator->type == 'string')
  770. {
  771. $columnName = strtolower($validator->attributes[0]);
  772. if (count($allValidators) > 1)
  773. {
  774. $haveCStringValidator = false;
  775. foreach ($allValidators as $innerValidator)
  776. {
  777. if (get_class($innerValidator) == 'CStringValidator' &&
  778. isset($innerValidator->max) &&
  779. $innerValidator->max > 0)
  780. {
  781. if ($innerValidator->max > 65535)
  782. {
  783. $hints[$columnName] = 'longtext';
  784. }
  785. elseif ($innerValidator->max < 255)
  786. {
  787. $hints[$columnName] = "string({$innerValidator->max})";
  788. }
  789. else
  790. {
  791. $hints[$columnName] = 'text';
  792. }
  793. }
  794. if (get_class($innerValidator) == 'CStringValidator')
  795. {
  796. $haveCStringValidator = true;
  797. }
  798. }
  799. if (!$haveCStringValidator)
  800. {
  801. $hints[$columnName] = 'text';
  802. }
  803. }
  804. else
  805. {
  806. $hints[$columnName] = 'text';
  807. }
  808. }
  809. }
  810. }
  811. }
  812. }
  813. }
  814. $bean->setMeta('hint', $hints);
  815. }
  816. }
  817. /**
  818. * Used for mixins.
  819. */
  820. protected function runDefaultValidators()
  821. {
  822. foreach ($this->validators as $validator)
  823. {
  824. if ($validator instanceof CDefaultValueValidator)
  825. {
  826. $validator->validate($this);
  827. }
  828. }
  829. }
  830. /**
  831. * For use only by RedBeanModel and RedBeanModels. Beans are
  832. * never used by the application directly.
  833. */
  834. public function getPrimaryBean()
  835. {
  836. return end($this->modelClassNameToBean);
  837. }
  838. /**
  839. * Used for optimization.
  840. */
  841. public function getClassId($modelClassName)
  842. {
  843. assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
  844. return intval($this->getClassBean($modelClassName)->id); // Trying to combat the slop.
  845. }
  846. public function getClassBean($modelClassName)
  847. {
  848. assert('is_string($modelClassName)');
  849. assert('$modelClassName != ""');
  850. self::resolveModelClassNameForClassesWithoutBeans($modelClassName);
  851. assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
  852. return $this->modelClassNameToBean[$modelClassName];
  853. }
  854. /**
  855. * Used for mixins.
  856. */
  857. protected function setClassBean($modelClassName, RedBean_OODBBean $bean)
  858. {
  859. assert('is_string($modelClassName)');
  860. assert('$modelClassName != ""');
  861. assert('!array_key_exists($modelClassName, $this->modelClassNameToBean)');
  862. $this->modelClassNameToBean = array_merge(array($modelClassName => $bean),
  863. $this->modelClassNameToBean);
  864. }
  865. public function getModelIdentifier()
  866. {
  867. return get_class($this) . strval($this->getPrimaryBean()->id);
  868. }
  869. /**
  870. * Returns metadata for the model. Attempts to cache metadata, if it is not already cached.
  871. * @see getDefaultMetadata()
  872. * @returns An array of metadata.
  873. */
  874. public static function getMetadata()
  875. {
  876. try
  877. {
  878. return GeneralCache::getEntry(get_called_class() . 'Metadata');
  879. }
  880. catch (NotFoundException $e)
  881. {
  882. $className = get_called_Class();
  883. $defaultMetadata = $className::getDefaultMetadata();
  884. $metadata = array();
  885. foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy)) as $modelClassName)
  886. {
  887. if ($modelClassName::getCanHaveBean())
  888. {
  889. if ($modelClassName::canSaveMetadata())
  890. {
  891. try
  892. {
  893. $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
  894. $metadata[$modelClassName] = unserialize($globalMetadata->serializedMetadata);
  895. }
  896. catch (NotFoundException $e)
  897. {
  898. if (isset($defaultMetadata[$modelClassName]))
  899. {
  900. $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
  901. }
  902. }
  903. }
  904. else
  905. {
  906. if (isset($defaultMetadata[$modelClassName]))
  907. {
  908. $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
  909. }
  910. }
  911. }
  912. }
  913. if (YII_DEBUG)
  914. {
  915. self::assertMetadataIsValid($metadata);
  916. }
  917. GeneralCache::cacheEntry(get_called_class() . 'Metadata', $metadata);
  918. return $metadata;
  919. }
  920. }
  921. /**
  922. * By default models cannot save their metadata, allowing
  923. * them to be loaded quickly because the loading of of
  924. * metadata can be avoided as much as possible.
  925. * To make a model able to save its metadata override
  926. * this method to return true. PUT it before the
  927. * getDefaultMetadata in the derived class.
  928. */
  929. public static function canSaveMetadata()
  930. {
  931. return false;
  932. }
  933. /**
  934. * Sets metadata for the model.
  935. * @see getDefaultMetadata()
  936. * @returns An array of metadata.
  937. */
  938. public static function setMetadata(array $metadata)
  939. {
  940. if (YII_DEBUG)
  941. {
  942. self::assertMetadataIsValid($metadata);
  943. }
  944. $className = get_called_class();
  945. foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy)) as $modelClassName)
  946. {
  947. if ($modelClassName::getCanHaveBean())
  948. {
  949. if ($modelClassName::canSaveMetadata())
  950. {
  951. if (isset($metadata[$modelClassName]))
  952. {
  953. try
  954. {
  955. $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
  956. }
  957. catch (NotFoundException $e)
  958. {
  959. $globalMetadata = new GlobalMetadata();
  960. $globalMetadata->className = $modelClassName;
  961. }
  962. $globalMetadata->serializedMetadata = serialize($metadata[$modelClassName]);
  963. $saved = $globalMetadata->save();
  964. // TODO: decide how to deal with this properly if it fails.
  965. // ie: throw or return false, or something other than
  966. // this naughty assert.
  967. assert('$saved');
  968. }
  969. }
  970. }
  971. }
  972. RedBeanModelsCache::forgetAllByModelType(get_called_class());
  973. GeneralCache::forgetEntry(get_called_class() . 'Metadata');
  974. }
  975. /**
  976. * Returns the default meta data for the class.
  977. * It must be appended to the meta data
  978. * from the parent model, if any.
  979. */
  980. public static function getDefaultMetadata()
  981. {
  982. return array();
  983. }
  984. protected static function assertMetadataIsValid(array $metadata)
  985. {
  986. $className = get_called_Class();
  987. foreach (RuntimeUtil::getClassHierarchy($className, static::$lastClassInBeanHeirarchy) as $modelClassName)
  988. {
  989. if ($modelClassName::getCanHaveBean())
  990. {
  991. if (isset($metadata[$modelClassName]['members']))
  992. {
  993. assert('is_array($metadata[$modelClassName]["members"])');
  994. foreach ($metadata[$modelClassName]["members"] as $memberName)
  995. {
  996. assert('ctype_lower($memberName{0})');
  997. }
  998. }
  999. if (isset($metadata[$modelClassName]['relations']))
  1000. {
  1001. assert('is_array($metadata[$modelClassName]["relations"])');
  1002. foreach ($metadata[$modelClassName]["relations"] as $relationName => $notUsed)
  1003. {
  1004. assert('ctype_lower($relationName{…

Large files files are truncated, but you can click here to view the full file