PageRenderTime 32ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/app/protected/extensions/zurmoinc/framework/models/RedBeanModel.php

https://bitbucket.org/codevarun/zurmo-invoice-example
PHP | 2717 lines | 1960 code | 132 blank | 625 comment | 237 complexity | e7cb68e51e05e9537a4d56521d1cd4c2 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, LGPL-2.1, BSD-2-Clause
  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. $basePath = Yii::app()->getBasePath();
  27. require_once("$basePath/../../redbean/rb.php");
  28. /**
  29. * Abstraction over the top of an application database accessed via
  30. * <a href="http://www.redbeanphp.com/">RedBean</a>. The base class for
  31. * an MVC model. Replaces the M part of MVC in Yii. Yii maps from the
  32. * database scheme to the objects, (good for database guys, not so good
  33. * for OO guys), this maps from objects to the database schema.
  34. *
  35. * A domain model is created by extending RedBeanModel and supplying
  36. * a getDefaultMetadata() method.
  37. *
  38. * Static getXxxx() methods can be supplied to query for the given domain
  39. * models, and instance methods should supply additional behaviour.
  40. *
  41. * getDefaultMetadata() returns an array of the class name mapped to
  42. * an array containing 'members' mapped to an array of member names,
  43. * (to be accessed as $model->memberName).
  44. *
  45. * It can then optionally have, 'relations' mapped
  46. * to an array of relation names, (to be accessed as $model->relationName),
  47. * mapped to its type, (the extending model class to which it relates).
  48. *
  49. * And it can then optionally have as well, 'rules' mapped to an array of
  50. * attribute names, (attributes are members and relations), a validator name,
  51. * and the parameters to the validator, if any, as per the Yii::CModel::rules()
  52. * method.See http://www.yiiframework.com/wiki/56/reference-model-rules-validation.
  53. *
  54. * These are used to automatically and dynamically create the database
  55. * schema on the fly as opposed to Yii's getting attributes from an
  56. * already existing schema.
  57. */
  58. abstract class RedBeanModel extends CComponent implements Serializable
  59. {
  60. // Models that have not been saved yet have no id as far
  61. // as the database is concerned. Until they are saved they are
  62. // assigned a negative id, so that they have identity.
  63. private static $nextPseudoId = -1;
  64. // The id of an unsaved model.
  65. private $pseudoId;
  66. // A model maps to one or more beans. If Person extends RedBeanModel
  67. // there is one bean, but if User then extends Person a User model
  68. // has two beans, the one holding the person data and the one holding
  69. // the extended User data. In this way in inheritance hierarchy from
  70. // model is normalized over several tables, one for each extending
  71. // class.
  72. private $modelClassNameToBean = array();
  73. private $attributeNameToBeanAndClassName = array();
  74. private $attributeNamesNotBelongsToOrManyMany = array();
  75. private $relationNameToRelationTypeModelClassNameAndOwns = array();
  76. private $relationNameToRelatedModel = array();
  77. private $unlinkedRelationNames = array();
  78. private $validators = array();
  79. private $attributeNameToErrors = array();
  80. private $scenarioName = '';
  81. // An object is automatcally savable if it is new or contains
  82. // modified members or related objects.
  83. // If it is newly created and has never had any data put into it
  84. // it can be saved explicitly but it wont be saved automatically
  85. // when it is a related model and will be redispensed next
  86. // time it is referenced.
  87. protected $modified = false;
  88. protected $deleted = false;
  89. protected $isInIsModified = false;
  90. protected $isInHasErrors = false;
  91. protected $isInGetErrors = false;
  92. protected $isValidating = false;
  93. protected $isSaving = false;
  94. // Mapping of Yii validators to validators doing things that
  95. // are either required for RedBean, or that simply implement
  96. // The semantics that we want.
  97. private static $yiiValidatorsToRedBeanValidators = array(
  98. 'CDefaultValueValidator' => 'RedBeanModelDefaultValueValidator',
  99. 'CNumberValidator' => 'RedBeanModelNumberValidator',
  100. 'CTypeValidator' => 'RedBeanModelTypeValidator',
  101. 'CRequiredValidator' => 'RedBeanModelRequiredValidator',
  102. 'CUniqueValidator' => 'RedBeanModelUniqueValidator',
  103. 'defaultCalculatedDate' => 'RedBeanModelDefaultCalculatedDateValidator',
  104. 'readOnly' => 'RedBeanModelReadOnlyValidator',
  105. 'dateTimeDefault' => 'RedBeanModelDateTimeDefaultValueValidator',
  106. );
  107. /**
  108. * Used in an extending class's getDefaultMetadata() method to specify
  109. * that a relation is 1:1 and that the class on the 1 side of the
  110. * relation.
  111. */
  112. const HAS_ONE_BELONGS_TO = 0;
  113. /**
  114. * Used in an extending class's getDefaultMetadata() method to specify
  115. * that a relation is 1:M and that the class on the M side of the
  116. * relation.
  117. * Note: Currently if you have a relation that is set to HAS_MANY_BELONGS_TO, then that relation name
  118. * must be the strtolower() same as the related model class name. This is the current support for this
  119. * relation type. If something different is set, an exception will be thrown.
  120. */
  121. const HAS_MANY_BELONGS_TO = 1;
  122. /**
  123. * Used in an extending class's getDefaultMetadata() method to specify
  124. * that a relation is 1:1.
  125. */
  126. const HAS_ONE = 2;
  127. /**
  128. * Used in an extending class's getDefaultMetadata() method to specify
  129. * that a relation is 1:M and that the class is on the 1 side of the
  130. * relation.
  131. */
  132. const HAS_MANY = 3;
  133. /**
  134. * Used in an extending class's getDefaultMetadata() method to specify
  135. * that a relation is M:N and that the class on the either side of the
  136. * relation.
  137. */
  138. const MANY_MANY = 4;
  139. /**
  140. * Used in an extending class's getDefaultMetadata() method to specify
  141. * that a 1:1 or 1:M relation is one in which the left side of the relation
  142. * owns the model or models on the right side, meaning that if the model
  143. * is deleted it owns the related models and they are deleted along with it.
  144. * If not specified the related model is independent and is not deleted.
  145. */
  146. const OWNED = true;
  147. /**
  148. * Gets all the models from the database of the named model type.
  149. * @param $orderBy TODO
  150. * @param $modelClassName Pass only when getting it at runtime
  151. * gets the wrong name.
  152. * @return An array of models of the type of the extending model.
  153. */
  154. public static function getAll($orderBy = null, $sortDescending = false, $modelClassName = null)
  155. {
  156. assert('$orderBy === null || is_string($orderBy) && $orderBy != ""');
  157. assert('is_bool($sortDescending)');
  158. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  159. $quote = DatabaseCompatibilityUtil::getQuote();
  160. $orderBySql = null;
  161. if ($orderBy !== null)
  162. {
  163. $orderBySql = "$quote$orderBy$quote";
  164. if ($sortDescending)
  165. {
  166. $orderBySql .= ' desc';
  167. }
  168. }
  169. return static::getSubset(null, null, null, null, $orderBySql, $modelClassName);
  170. }
  171. /**
  172. * Gets a range of models from the database of the named model type.
  173. * @param $modelClassName
  174. * @param $joinTablesAdapter null or instance of joinTablesAdapter.
  175. * @param $offset The zero based index of the first model to be returned.
  176. * @param $count The number of models to be returned.
  177. * @param $where
  178. * @param $orderBy - sql string. Example 'a desc' or 'a.b desc'. Currently only supports non-related attributes
  179. * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
  180. * @return An array of models of the type of the extending model.
  181. */
  182. public static function getSubset(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
  183. $offset = null, $count = null,
  184. $where = null, $orderBy = null,
  185. $modelClassName = null,
  186. $selectDistinct = false)
  187. {
  188. assert('$offset === null || is_integer($offset) && $offset >= 0');
  189. assert('$count === null || is_integer($count) && $count >= 1');
  190. assert('$where === null || is_string ($where) && $where != ""');
  191. assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
  192. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  193. if ($modelClassName === null)
  194. {
  195. $modelClassName = get_called_class();
  196. }
  197. if ($joinTablesAdapter == null)
  198. {
  199. $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
  200. }
  201. $tableName = self::getTableName($modelClassName);
  202. $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, $offset, $count, $where,
  203. $orderBy, false, $selectDistinct);
  204. $ids = R::getCol($sql);
  205. $tableName = self::getTableName($modelClassName);
  206. $beans = R::batch ($tableName, $ids);
  207. return self::makeModels($beans, $modelClassName);
  208. }
  209. /**
  210. * @param boolean $selectCount If true then make this a count query. If false, select ids from rows.
  211. * @param array $quotedExtraSelectColumnNameAndAliases - extra columns to select.
  212. * @return string - sql statement.
  213. */
  214. public static function makeSubsetOrCountSqlQuery($tableName,
  215. RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter,
  216. $offset = null, $count = null,
  217. $where = null, $orderBy = null,
  218. $selectCount = false,
  219. $selectDistinct = false,
  220. array $quotedExtraSelectColumnNameAndAliases = array())
  221. {
  222. assert('is_string($tableName) && $tableName != ""');
  223. assert('$offset === null || is_integer($offset) && $offset >= 0');
  224. assert('$count === null || is_integer($count) && $count >= 1');
  225. assert('$where === null || is_string ($where) && $where != ""');
  226. assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
  227. assert('is_bool($selectCount)');
  228. assert('is_bool($selectDistinct)');
  229. $selectQueryAdapter = new RedBeanModelSelectQueryAdapter($selectDistinct);
  230. if ($selectCount)
  231. {
  232. $selectQueryAdapter->addCountClause($tableName);
  233. }
  234. else
  235. {
  236. $selectQueryAdapter->addClause($tableName, 'id', 'id');
  237. }
  238. foreach ($quotedExtraSelectColumnNameAndAliases as $columnName => $columnAlias)
  239. {
  240. $selectQueryAdapter->addClauseWithColumnNameOnlyAndNoEnclosure($columnName, $columnAlias);
  241. }
  242. return SQLQueryUtil::
  243. makeQuery($tableName, $selectQueryAdapter, $joinTablesAdapter, $offset, $count, $where, $orderBy);
  244. }
  245. /**
  246. * @param $modelClassName
  247. * @param $joinTablesAdapter null or instance of joinTablesAdapter.
  248. * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
  249. */
  250. public static function getCount(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
  251. $where = null, $modelClassName = null, $selectDistinct = false)
  252. {
  253. assert('$where === null || is_string($where)');
  254. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  255. if ($modelClassName === null)
  256. {
  257. $modelClassName = get_called_class();
  258. }
  259. if ($joinTablesAdapter == null)
  260. {
  261. $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
  262. }
  263. $tableName = self::getTableName($modelClassName);
  264. $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, null, null, $where, null, true,
  265. $selectDistinct);
  266. $count = R::getCell($sql);
  267. if ($count === null)
  268. {
  269. $count = 0;
  270. }
  271. return $count;
  272. }
  273. /**
  274. * Gets a model from the database by Id.
  275. * @param $id Integer Id.
  276. * @param $modelClassName Pass only when getting it at runtime
  277. * gets the wrong name.
  278. * @return A model of the type of the extending model.
  279. */
  280. public static function getById($id, $modelClassName = null)
  281. {
  282. assert('is_integer($id) && $id > 0');
  283. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  284. // I would have thought it was correct to user R::load() and get
  285. // a null, or error or something if the bean doesn't exist, but
  286. // it still returns a bean. So until I've investigated further
  287. // I'm using Finder.
  288. if ($modelClassName === null)
  289. {
  290. $modelClassName = get_called_class();
  291. }
  292. $tableName = self::getTableName($modelClassName);
  293. $beans = RedBean_Plugin_Finder::where($tableName, "id = '$id'");
  294. assert('count($beans) <= 1');
  295. if (count($beans) == 0)
  296. {
  297. throw new NotFoundException();
  298. }
  299. return RedBeanModel::makeModel(end($beans), $modelClassName);
  300. }
  301. /**
  302. * Constructs a new model.
  303. * Important:
  304. * Models are only constructed with beans by the RedBeanModel. Beans are
  305. * never used by the application directly.
  306. * The application can construct a new model object by constructing a
  307. * model without specifying a bean. In other words, if Php had
  308. * overloading a constructor with $setDefaults would be public, and
  309. * a constructor taking a $bean and $forceTreatAsCreation would be private.
  310. * @param $setDefaults. If false the default validators will not be run
  311. * on construction. The Yii way is that defaults are
  312. * filled in after the fact, which is counter the usual
  313. * for objects.
  314. * @param $bean A bean. Never specified by an application.
  315. * @param $forceTreatAsCreation. Never specified by an application.
  316. * @see getById()
  317. * @see makeModel()
  318. * @see makeModels()
  319. */
  320. public function __construct($setDefaults = true, RedBean_OODBBean $bean = null, $forceTreatAsCreation = false)
  321. {
  322. $this->pseudoId = self::$nextPseudoId--;
  323. if ($bean === null)
  324. {
  325. foreach (array_reverse(RuntimeUtil::getClassHierarchy(get_class($this), 'RedBeanModel')) as $modelClassName)
  326. {
  327. $tableName = self::getTableName($modelClassName);
  328. $newBean = R::dispense($tableName);
  329. $this->modelClassNameToBean[$modelClassName] = $newBean;
  330. $this->mapAndCacheMetadataAndSetHints($modelClassName, $newBean);
  331. }
  332. // The yii way of doing defaults is the the default validator
  333. // fills in the defaults on attributes that don't have values
  334. // when you validator, or save. This weird, since when you get
  335. // a model the things with defaults have not been defaulted!
  336. // We want that semantic.
  337. if ($setDefaults)
  338. {
  339. $this->runDefaultValidators();
  340. }
  341. $forceTreatAsCreation = true;
  342. }
  343. else
  344. {
  345. assert('$bean->id > 0');
  346. $first = true;
  347. foreach (RuntimeUtil::getClassHierarchy(get_class($this), 'RedBeanModel') as $modelClassName)
  348. {
  349. if ($first)
  350. {
  351. $lastBean = $bean;
  352. $first = false;
  353. }
  354. else
  355. {
  356. $tableName = self::getTableName($modelClassName);
  357. $lastBean = R::getBean($lastBean, $tableName);
  358. if ($lastBean === null)
  359. {
  360. throw new MissingBeanException();
  361. }
  362. assert('$lastBean->id > 0');
  363. }
  364. $this->modelClassNameToBean[$modelClassName] = $lastBean;
  365. $this->mapAndCacheMetadataAndSetHints($modelClassName, $lastBean);
  366. }
  367. $this->modelClassNameToBean = array_reverse($this->modelClassNameToBean);
  368. }
  369. $this->constructDerived($bean, $setDefaults);
  370. if ($forceTreatAsCreation)
  371. {
  372. $this->onCreated();
  373. }
  374. else
  375. {
  376. $this->onLoaded();
  377. RedBeanModelsCache::cacheModel($this);
  378. }
  379. $this->modified = false;
  380. }
  381. // Derived classes can insert additional steps into the construction.
  382. protected function constructDerived($bean, $setDefaults)
  383. {
  384. assert('$bean === null || $bean instanceof RedBean_OODBBean');
  385. assert('is_bool($setDefaults)');
  386. }
  387. /**
  388. * Utilized when pieces of information need to be constructed on an existing model, that can potentially be
  389. * missing. For example, if a model is created, then a custom field is added, it is possible the cached model
  390. * is missing the custom field customFieldData.
  391. * @param unknown_type $bean
  392. */
  393. protected function constructIncomplete($bean)
  394. {
  395. assert('$bean === null || $bean instanceof RedBean_OODBBean');
  396. }
  397. public function serialize()
  398. {
  399. return serialize(array(
  400. $this->pseudoId,
  401. $this->modelClassNameToBean,
  402. $this->attributeNameToBeanAndClassName,
  403. $this->attributeNamesNotBelongsToOrManyMany,
  404. $this->relationNameToRelationTypeModelClassNameAndOwns,
  405. $this->validators,
  406. ));
  407. }
  408. public function unserialize($data)
  409. {
  410. try
  411. {
  412. $data = unserialize($data);
  413. assert('is_array($data)');
  414. if (count($data) != 6)
  415. {
  416. return null;
  417. }
  418. $this->pseudoId = $data[0];
  419. $this->modelClassNameToBean = $data[1];
  420. $this->attributeNameToBeanAndClassName = $data[2];
  421. $this->attributeNamesNotBelongsToOrManyMany = $data[3];
  422. $this->relationNameToRelationTypeModelClassNameAndOwns = $data[4];
  423. $this->validators = $data[5];
  424. $this->relationNameToRelatedModel = array();
  425. $this->unlinkedRelationNames = array();
  426. $this->attributeNameToErrors = array();
  427. $this->scenarioName = '';
  428. $this->modified = false;
  429. $this->deleted = false;
  430. $this->isInIsModified = false;
  431. $this->isInHasErrors = false;
  432. $this->isInGetErrors = false;
  433. $this->isValidating = false;
  434. $this->isSaving = false;
  435. }
  436. catch (Exception $e)
  437. {
  438. return null;
  439. }
  440. }
  441. /**
  442. * Overriding constructors must call this function to ensure that
  443. * they leave the newly constructed instance not modified since
  444. * anything modifying the class during constructionm will set it
  445. * modified automatically.
  446. */
  447. protected function setNotModified()
  448. {
  449. $this->modified = false; // This sets this class to the right state.
  450. assert('!$this->isModified()'); // This tests that related classes are in the right state.
  451. }
  452. /**
  453. * By default the table name is the lowercased class name. If this
  454. * conflicts with a database keyword override to return true.
  455. * RedBean does not quote table names in most cases.
  456. */
  457. // Public for unit testing.
  458. public static function mangleTableName()
  459. {
  460. return false;
  461. }
  462. /**
  463. * Returns the table name for a class.
  464. * For use by RedBeanModelDataProvider. It will not
  465. * be of any use to an application. Applications
  466. * should not be doing anything table related.
  467. * Derived classes can refer directly to the
  468. * table name.
  469. */
  470. public static function getTableName($modelClassName)
  471. {
  472. assert('is_string($modelClassName) && $modelClassName != ""');
  473. $tableName = strtolower($modelClassName);
  474. if ($modelClassName::mangleTableName())
  475. {
  476. $tableName = '_' . $tableName;
  477. }
  478. return $tableName;
  479. }
  480. /**
  481. * Returns the table names for an array of classes.
  482. * For use by RedBeanModelDataProvider. It will not
  483. * be of any use to an application.
  484. */
  485. public static function getTableNames($classNames)
  486. {
  487. $tableNames = array();
  488. foreach ($classNames as $className)
  489. {
  490. $tableNames[] = self::getTableName($className);
  491. }
  492. return $tableNames;
  493. }
  494. /**
  495. * Used by classes such as containers which use sql to
  496. * optimize getting models from the database.
  497. */
  498. public static function getForeignKeyName($modelClassName, $relationName)
  499. {
  500. assert('is_string($modelClassName)');
  501. assert('$modelClassName != ""');
  502. $metadata = $modelClassName::getMetadata();
  503. foreach ($metadata as $modelClassName => $modelClassMetadata)
  504. {
  505. if (isset($metadata[$modelClassName]["relations"]) &&
  506. array_key_exists($relationName, $metadata[$modelClassName]["relations"]))
  507. {
  508. $relatedModelClassName = $metadata[$modelClassName]['relations'][$relationName][1];
  509. $relatedModelTableName = self::getTableName($relatedModelClassName);
  510. $columnName = '';
  511. if (strtolower($relationName) != strtolower($relatedModelClassName))
  512. {
  513. $columnName = strtolower($relationName) . '_';
  514. }
  515. $columnName .= $relatedModelTableName . '_id';
  516. return $columnName;
  517. }
  518. }
  519. throw new NotSupportedException;
  520. }
  521. /**
  522. * Called on construction when a new model is created.
  523. */
  524. protected function onCreated()
  525. {
  526. }
  527. /**
  528. * Called on construction when a model is loaded.
  529. */
  530. protected function onLoaded()
  531. {
  532. }
  533. /**
  534. * Called when a model is modified.
  535. */
  536. protected function onModified()
  537. {
  538. }
  539. /**
  540. * Used for mixins.
  541. */
  542. protected function mapAndCacheMetadataAndSetHints($modelClassName, RedBean_OODBBean $bean)
  543. {
  544. assert('is_string($modelClassName)');
  545. assert('$modelClassName != ""');
  546. $metadata = $this->getMetadata();
  547. if (isset($metadata[$modelClassName]))
  548. {
  549. $hints = array();
  550. if (isset($metadata[$modelClassName]['members']))
  551. {
  552. foreach ($metadata[$modelClassName]['members'] as $memberName)
  553. {
  554. $this->attributeNameToBeanAndClassName[$memberName] = array($bean, $modelClassName);
  555. $this->attributeNamesNotBelongsToOrManyMany[] = $memberName;
  556. if (substr($memberName, -2) == 'Id')
  557. {
  558. $columnName = strtolower($memberName);
  559. $hints[$columnName] = 'id';
  560. }
  561. }
  562. }
  563. if (isset($metadata[$modelClassName]['relations']))
  564. {
  565. foreach ($metadata[$modelClassName]['relations'] as $relationName => $relationTypeModelClassNameAndOwns)
  566. {
  567. assert('in_array(count($relationTypeModelClassNameAndOwns), array(2, 3))');
  568. $relationType = $relationTypeModelClassNameAndOwns[0];
  569. $relationModelClassName = $relationTypeModelClassNameAndOwns[1];
  570. if ($relationType == self::HAS_MANY_BELONGS_TO &&
  571. strtolower($relationName) != strtolower($relationModelClassName))
  572. {
  573. $label = 'Relations of type HAS_MANY_BELONGS_TO must have the relation name ' .
  574. 'the same as the related model class name. Relation: {relationName} ' .
  575. 'Relation model class name: {relationModelClassName}';
  576. throw new NotSupportedException(Yii::t('Default', $label,
  577. array('{relationName}' => $relationName,
  578. '{relationModelClassName}' => $relationModelClassName)));
  579. }
  580. if (count($relationTypeModelClassNameAndOwns) == 3)
  581. {
  582. $relationTypeModelClassNameAndOwns[2] == self::OWNED;
  583. $owns = true;
  584. }
  585. else
  586. {
  587. $owns = false;
  588. }
  589. assert('in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, ' .
  590. 'self::HAS_ONE, self::HAS_MANY, self::MANY_MANY))');
  591. $this->attributeNameToBeanAndClassName[$relationName] = array($bean, $modelClassName);
  592. $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName] = array($relationType, $relationModelClassName, $owns);
  593. if (!in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, self::MANY_MANY)))
  594. {
  595. $this->attributeNamesNotBelongsToOrManyMany[] = $relationName;
  596. }
  597. }
  598. }
  599. if (isset($metadata[$modelClassName]['rules']))
  600. {
  601. foreach ($metadata[$modelClassName]['rules'] as $validatorMetadata)
  602. {
  603. assert('isset($validatorMetadata[0])');
  604. assert('isset($validatorMetadata[1])');
  605. $attributeName = $validatorMetadata[0];
  606. // Each rule in RedBeanModel must specify one attribute name.
  607. // This was just better style, now it is mandatory.
  608. assert('strpos($attributeName, " ") === false');
  609. $validatorName = $validatorMetadata[1];
  610. $validatorParameters = array_slice($validatorMetadata, 2);
  611. if (isset(CValidator::$builtInValidators[$validatorName]))
  612. {
  613. $validatorName = CValidator::$builtInValidators[$validatorName];
  614. }
  615. if (isset(self::$yiiValidatorsToRedBeanValidators[$validatorName]))
  616. {
  617. $validatorName = self::$yiiValidatorsToRedBeanValidators[$validatorName];
  618. }
  619. $validator = CValidator::createValidator($validatorName, $this, $attributeName, $validatorParameters);
  620. switch ($validatorName)
  621. {
  622. case 'RedBeanModelTypeValidator':
  623. case 'TypeValidator':
  624. $columnName = strtolower($attributeName);
  625. if (array_key_exists($columnName, $hints))
  626. {
  627. unset($hints[$columnName]);
  628. }
  629. if (in_array($validator->type, array('date', 'datetime', 'blob', 'longblob')))
  630. {
  631. $hints[$columnName] = $validator->type;
  632. }
  633. break;
  634. case 'CBooleanValidator':
  635. $columnName = strtolower($attributeName);
  636. $hints[$columnName] = 'boolean';
  637. break;
  638. case 'RedBeanModelUniqueValidator':
  639. if (!$this->isRelation($attributeName))
  640. {
  641. $bean->setMeta("buildcommand.unique", array(array($attributeName)));
  642. }
  643. else
  644. {
  645. $relatedModelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][1];
  646. $relatedModelTableName = self::getTableName($relatedModelClassName);
  647. $columnName = strtolower($attributeName);
  648. if ($columnName != $relatedModelTableName)
  649. {
  650. $columnName .= '_' . $relatedModelTableName;
  651. }
  652. $columnName .= '_id';
  653. $bean->setMeta("buildcommand.unique", array(array($columnName)));
  654. }
  655. break;
  656. }
  657. $this->validators[] = $validator;
  658. }
  659. }
  660. $bean->setMeta('hint', $hints);
  661. }
  662. }
  663. /**
  664. * Used for mixins.
  665. */
  666. protected function runDefaultValidators()
  667. {
  668. foreach ($this->validators as $validator)
  669. {
  670. if ($validator instanceof CDefaultValueValidator)
  671. {
  672. $validator->validate($this);
  673. }
  674. }
  675. }
  676. /**
  677. * For use only by RedBeanModel and RedBeanModels. Beans are
  678. * never used by the application directly.
  679. */
  680. public function getPrimaryBean()
  681. {
  682. return end($this->modelClassNameToBean);
  683. }
  684. /**
  685. * Used for optimization.
  686. */
  687. public function getClassId($modelClassName)
  688. {
  689. assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
  690. return intval($this->getClassBean($modelClassName)->id); // Trying to combat the slop.
  691. }
  692. public function getClassBean($modelClassName)
  693. {
  694. assert('is_string($modelClassName)');
  695. assert('$modelClassName != ""');
  696. assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
  697. return $this->modelClassNameToBean[$modelClassName];
  698. }
  699. /**
  700. * Used for mixins.
  701. */
  702. protected function setClassBean($modelClassName, RedBean_OODBBean $bean)
  703. {
  704. assert('is_string($modelClassName)');
  705. assert('$modelClassName != ""');
  706. assert('!array_key_exists($modelClassName, $this->modelClassNameToBean)');
  707. $this->modelClassNameToBean = array_merge(array($modelClassName => $bean),
  708. $this->modelClassNameToBean);
  709. }
  710. public function getModelIdentifier()
  711. {
  712. return get_class($this) . strval($this->getPrimaryBean()->id);
  713. }
  714. /**
  715. * Returns metadata for the model. Attempts to cache metadata, if it is not already cached.
  716. * @see getDefaultMetadata()
  717. * @returns An array of metadata.
  718. */
  719. public static function getMetadata()
  720. {
  721. try
  722. {
  723. return GeneralCache::getEntry(get_called_class() . 'Metadata');
  724. }
  725. catch (NotFoundException $e)
  726. {
  727. $className = get_called_Class();
  728. $defaultMetadata = $className::getDefaultMetadata();
  729. $metadata = array();
  730. foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, 'RedBeanModel')) as $modelClassName)
  731. {
  732. if ($modelClassName::canSaveMetadata())
  733. {
  734. try
  735. {
  736. $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
  737. $metadata[$modelClassName] = unserialize($globalMetadata->serializedMetadata);
  738. }
  739. catch (NotFoundException $e)
  740. {
  741. if (isset($defaultMetadata[$modelClassName]))
  742. {
  743. $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
  744. }
  745. }
  746. }
  747. else
  748. {
  749. if (isset($defaultMetadata[$modelClassName]))
  750. {
  751. $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
  752. }
  753. }
  754. }
  755. if (YII_DEBUG)
  756. {
  757. self::assertMetadataIsValid($metadata);
  758. }
  759. GeneralCache::cacheEntry(get_called_class() . 'Metadata', $metadata);
  760. return $metadata;
  761. }
  762. }
  763. /**
  764. * By default models cannot save their metadata, allowing
  765. * them to be loaded quickly because the loading of of
  766. * metadata can be avoided as much as possible.
  767. * To make a model able to save its metadata override
  768. * this method to return true. PUT it before the
  769. * getDefaultMetadata in the derived class.
  770. */
  771. public static function canSaveMetadata()
  772. {
  773. return false;
  774. }
  775. /**
  776. * Sets metadata for the model.
  777. * @see getDefaultMetadata()
  778. * @returns An array of metadata.
  779. */
  780. public static function setMetadata(array $metadata)
  781. {
  782. if (YII_DEBUG)
  783. {
  784. self::assertMetadataIsValid($metadata);
  785. }
  786. $className = get_called_class();
  787. foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, 'RedBeanModel')) as $modelClassName)
  788. {
  789. if ($modelClassName::canSaveMetadata())
  790. {
  791. if (isset($metadata[$modelClassName]))
  792. {
  793. try
  794. {
  795. $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
  796. }
  797. catch (NotFoundException $e)
  798. {
  799. $globalMetadata = new GlobalMetadata();
  800. $globalMetadata->className = $modelClassName;
  801. }
  802. $globalMetadata->serializedMetadata = serialize($metadata[$modelClassName]);
  803. $saved = $globalMetadata->save();
  804. // TODO: decide how to deal with this properly if it fails.
  805. // ie: throw or return false, or something other than
  806. // this naughty assert.
  807. assert('$saved');
  808. }
  809. }
  810. }
  811. RedBeanModelsCache::forgetAllByModelType(get_called_class());
  812. GeneralCache::forgetEntry(get_called_class() . 'Metadata');
  813. }
  814. /**
  815. * Returns the default meta data for the class.
  816. * It must be appended to the meta data
  817. * from the parent model, if any.
  818. */
  819. public static function getDefaultMetadata()
  820. {
  821. return array();
  822. }
  823. protected static function assertMetadataIsValid(array $metadata)
  824. {
  825. $className = get_called_Class();
  826. foreach (RuntimeUtil::getClassHierarchy($className, 'RedBeanModel') as $modelClassName)
  827. {
  828. if (isset($metadata[$modelClassName]['members']))
  829. {
  830. assert('is_array($metadata[$modelClassName]["members"])');
  831. foreach ($metadata[$modelClassName]["members"] as $memberName)
  832. {
  833. assert('ctype_lower($memberName{0})');
  834. }
  835. }
  836. if (isset($metadata[$modelClassName]['relations']))
  837. {
  838. assert('is_array($metadata[$modelClassName]["relations"])');
  839. foreach ($metadata[$modelClassName]["relations"] as $relationName => $notUsed)
  840. {
  841. assert('ctype_lower($relationName{0})');
  842. }
  843. }
  844. if (isset($metadata[$modelClassName]['rules']))
  845. {
  846. assert('is_array($metadata[$modelClassName]["rules"])');
  847. }
  848. if (isset($metadata[$modelClassName]['defaultSortAttribute']))
  849. {
  850. assert('is_string($metadata[$modelClassName]["defaultSortAttribute"])');
  851. }
  852. if (isset($metadata[$modelClassName]['rollupRelations']))
  853. {
  854. assert('is_array($metadata[$modelClassName]["rollupRelations"])');
  855. }
  856. // Todo: add more rules here as I think of them.
  857. }
  858. }
  859. /**
  860. * Downcasting in general is a bad concept, but when pulling
  861. * a Person from the database it would require a lot of
  862. * jumping through hoops to make the RedBeanModel automatically
  863. * figure out if that person is really a User, Contact, Customer
  864. * or whatever might be derived from Person. So to avoid that
  865. * complication and performance hit where it is not necessary
  866. * this method can be used to convert a model to one of
  867. * a given set of derivatives. If model is not one
  868. * of those NotFoundException is thrown.
  869. */
  870. public function castDown(array $derivedModelClassNames)
  871. {
  872. $bean = $this->getPrimaryBean();
  873. $thisModelClassName = get_called_class();
  874. $key = strtolower($thisModelClassName) . '_id';
  875. foreach ($derivedModelClassNames as $modelClassNames)
  876. {
  877. if (is_string($modelClassNames))
  878. {
  879. $nextModelClassName = $modelClassNames;
  880. if (get_class($this) == $nextModelClassName)
  881. {
  882. return $this;
  883. }
  884. $nextBean = self::findNextDerivativeBean($bean, $thisModelClassName, $nextModelClassName);
  885. }
  886. else
  887. {
  888. assert('is_array($modelClassNames)');
  889. $targetModelClassName = end($modelClassNames);
  890. if (get_class($this) == $targetModelClassName)
  891. {
  892. return $this;
  893. }
  894. $currentModelClassName = $thisModelClassName;
  895. $nextBean = $bean;
  896. foreach ($modelClassNames as $nextModelClassName)
  897. {
  898. $nextBean = self::findNextDerivativeBean($nextBean, $currentModelClassName, $nextModelClassName);
  899. if ($nextBean === null)
  900. {
  901. break;
  902. }
  903. $currentModelClassName = $nextModelClassName;
  904. }
  905. }
  906. if ($nextBean !== null)
  907. {
  908. return self::makeModel($nextBean, $nextModelClassName);
  909. }
  910. }
  911. throw new NotFoundException();
  912. }
  913. private static function findNextDerivativeBean($bean, $modelClassName1, $modelClassName2)
  914. {
  915. $key = strtolower($modelClassName1) . '_id';
  916. $tableName = self::getTableName($modelClassName2);
  917. $beans = R::find($tableName, "$key = :id", array('id' => $bean->id));
  918. if (count($beans) == 1)
  919. {
  920. return reset($beans);
  921. }
  922. return null;
  923. }
  924. /**
  925. * Returns whether the given object is of the same type with the
  926. * same id.
  927. */
  928. public function isSame(RedBeanModel $model)
  929. {
  930. // The two models are the same if they have the
  931. // same root model, and if for that model they
  932. // have the same id.
  933. $rootId1 = reset($this ->modelClassNameToBean)->id;
  934. $rootId2 = reset($model->modelClassNameToBean)->id;
  935. if ($rootId1 == 0)
  936. {
  937. $rootId1 = $this->pseudoId;
  938. }
  939. if ($rootId2 == 0)
  940. {
  941. $rootId2 = $model->pseudoId;
  942. }
  943. return $rootId1 == $rootId2 && $rootId1 != 0 &&
  944. key($this ->modelClassNameToBean) ==
  945. key($model->modelClassNameToBean);
  946. }
  947. /**
  948. * Returns the displayable string for the class. Should be
  949. * overridden in any model that can provide a meaningful string
  950. * representation of itself.
  951. * @return A string.
  952. */
  953. public function __toString()
  954. {
  955. return Yii::t('Default', '(None)');
  956. }
  957. /**
  958. * Exposes the members and relations of the model as if
  959. * they were actual attributes of the model. See __set().
  960. * @param $attributeName A non-empty string that is the name of a
  961. * member or relation.
  962. * @see attributeNames()
  963. * @return A value or model of the type specified as valid for the
  964. * member or relation by the meta data supplied by the extending
  965. * class's getMetadata() method.
  966. */
  967. public function __get($attributeName)
  968. {
  969. return $this->unrestrictedGet($attributeName);
  970. }
  971. /**
  972. * A protected version of __get() for models to talk to themselves
  973. * to use their dynamically created members from 'members'
  974. * and 'relations' in its metadata.
  975. */
  976. protected function unrestrictedGet($attributeName)
  977. {
  978. assert('is_string($attributeName)');
  979. assert('$attributeName != ""');
  980. assert("property_exists(\$this, '$attributeName') || \$this->isAttribute('$attributeName')");
  981. if (property_exists($this, $attributeName))
  982. {
  983. return $this->$attributeName;
  984. }
  985. elseif ($attributeName == 'id')
  986. {
  987. $id = intval($this->getPrimaryBean()->id);
  988. assert('$id >= 0');
  989. if ($id == 0)
  990. {
  991. $id = $this->pseudoId;
  992. }
  993. return $id;
  994. }
  995. elseif ($this->isAttribute($attributeName))
  996. {
  997. list($bean, $attributeModelClassName) = $this->attributeNameToBeanAndClassName[$attributeName];
  998. if (!$this->isRelation($attributeName))
  999. {
  1000. $columnName = strtolower($attributeName);
  1001. return $bean->$columnName;
  1002. }
  1003. else
  1004. {
  1005. if (!array_key_exists($attributeName, $this->relationNameToRelatedModel))
  1006. {
  1007. list($relationType, $relatedModelClassName, $owns) = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName];
  1008. $relatedTableName = self::getTableName($relatedModelClassName);
  1009. switch ($relationType)
  1010. {
  1011. case self::HAS_ONE_BELONGS_TO:
  1012. $relatedIds = R::$linkManager->getKeys($bean, $relatedTableName);
  1013. assert('in_array(count($relatedIds), array(0, 1))');
  1014. if (count($relatedIds) != 1)
  1015. {
  1016. return null;
  1017. }
  1018. $relatedBean = R::load($relatedTableName, $relatedIds[0]);
  1019. $this->relationNameToRelatedModel[$attributeName] = self::makeModel($relatedBean, $relatedModelClassName);
  1020. break;
  1021. case self::HAS_ONE:
  1022. case self::HAS_MANY_BELONGS_TO:
  1023. if ($relationType == self::HAS_ONE)
  1024. {
  1025. $linkName = strtolower($attributeName);
  1026. if ($linkName == strtolower($relatedModelClassName))
  1027. {
  1028. $linkName = null;
  1029. }
  1030. }
  1031. else
  1032. {
  1033. $linkName = null;
  1034. }
  1035. if ($bean->id > 0 && !in_array($attributeName, $this->unlinkedRelationNames))
  1036. {
  1037. $linkFieldName = R::$linkManager->getLinkField($relatedTableName, $linkName);
  1038. if ((int)$bean->$linkFieldName > 0)
  1039. {
  1040. $beanIdentifier = $relatedTableName .(int)$bean->$linkFieldName;
  1041. try
  1042. {
  1043. $relatedBean = RedBeansCache::getBean($beanIdentifier);
  1044. }
  1045. catch (NotFoundException $e)
  1046. {
  1047. $relatedBean = R::getBean($bean, $relatedTableName, $linkName);
  1048. RedBeansCache::cacheBean($relatedBean, $beanIdentifier);
  1049. }
  1050. if ($relatedBean !== null && $relatedBean->id > 0)
  1051. {
  1052. $relatedModel = self::makeModel($relatedBean, $relatedModelClassName);
  1053. }
  1054. }
  1055. }
  1056. if (!isset($relatedModel))
  1057. {
  1058. $relatedModel = new $relatedModelClassName();
  1059. }
  1060. $this->relationNameToRelatedModel[$attributeName] = $relatedModel;
  1061. break;
  1062. case self::HAS_MANY:
  1063. $this->relationNameToRelatedModel[$attributeName] = new RedBeanOneToManyRelatedModels($bean, $relatedModelClassName, $attributeModelClassName, $owns);
  1064. break;
  1065. case self::MANY_MANY:
  1066. $this->relationNameToRelatedModel[$attributeName] = new RedBeanManyToManyRelatedModels($bean, $relatedModelClassName);
  1067. break;
  1068. default:
  1069. throw new NotSupportedException();
  1070. }
  1071. }
  1072. return $this->relationNameToRelatedModel[$attributeName];
  1073. }
  1074. }
  1075. else
  1076. {
  1077. throw new NotSupportedException();
  1078. }
  1079. }
  1080. /**
  1081. * Sets the members and relations of the model as if
  1082. * they were actual attributes of the model. For example, if Account
  1083. * extends RedBeanModel and its attributeNames() returns that one it has
  1084. * a member 'name' and a relation 'owner' they are simply
  1085. * accessed as:
  1086. * @code
  1087. * $account = new Account();
  1088. * $account->name = 'International Corp';
  1089. * $account->owner = User::getByUsername('bill');
  1090. * $account->save();
  1091. * @endcode
  1092. * @param $attributeName A non-empty string that is the name of a
  1093. * member or relation of the model.
  1094. * @param $value A value or model of the type specified as valid for the
  1095. * member or relation by the meta data supplied by the extending
  1096. * class's getMetadata() method.
  1097. */
  1098. public function __set($attributeName, $value)
  1099. {
  1100. if ($attributeName == 'id' ||
  1101. ($this->isAttributeReadOnly($attributeName) && !$this->isAllowedToSetReadOnlyAttribute($attributeName)))
  1102. {
  1103. throw new NotSupportedException();
  1104. }
  1105. else
  1106. {
  1107. if ($this->unrestrictedSet($attributeName, $value))
  1108. {
  1109. $this->modified = true;
  1110. $this->onModified();
  1111. }
  1112. }
  1113. }
  1114. /**
  1115. * A protected version of __set() for models to talk to themselves
  1116. * to use their dynamically created members from 'members'
  1117. * and 'relations' in its metadata.
  1118. */
  1119. protected function unrestrictedSet($attributeName, $value)
  1120. {
  1121. assert('is_string($attributeName)');
  1122. assert('$attributeName != ""');
  1123. assert("property_exists(\$this, '$attributeName') || \$this->isAttribute('$attributeName')");
  1124. if (property_exists($this, $attributeName))
  1125. {
  1126. $this->$attributeName = $value;
  1127. }
  1128. elseif ($this->isAttribute($attributeName))
  1129. {
  1130. $bean = $this->attributeNameToBeanAndClassName[$attributeName][0];
  1131. if (!$this->isRelation($attributeName))
  1132. {
  1133. $columnName = strtolower($attributeName);
  1134. if ($bean->$columnName !== $value)
  1135. {
  1136. $bean->$columnName = $value;
  1137. return true;
  1138. }
  1139. }
  1140. else
  1141. {
  1142. list($relationType, $relatedModelClassName, $owns) = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName];
  1143. $relatedTableName = self::getTableName($relatedModelClassName);
  1144. $linkName = strtolower($attributeName);
  1145. if ($linkName == strtolower($relatedModelClassName))
  1146. {
  1147. $linkName = null;
  1148. }
  1149. switch ($relationType)
  1150. {
  1151. case self::HAS_MANY:
  1152. case self::MANY_MANY:
  1153. // The many sides of a relation cannot
  1154. // be assigned, they are changed by the using the
  1155. // RedBeanOneToManyRelatedModels or
  1156. // RedBeanManyToManyRelatedModels object
  1157. // on the 1 or other side of the relationship
  1158. // respectively.
  1159. throw new NotSupportedException();
  1160. }
  1161. // If the value is null we need to get the related model so that
  1162. // if there is none we can ignore the null and if there is one
  1163. // we can act on it.
  1164. if ($value === null &&
  1165. !in_array($attributeName, $this->unlinkedRelationNames) &&
  1166. !isset($this->relationNameToRelatedModel[$attributeName]))
  1167. {
  1168. $this->unrestrictedGet($attributeName);
  1169. }
  1170. if (isset($this->relationNameToRelatedModel[$attributeName]) &&
  1171. $value !== null &&
  1172. $this->relationNameToRelatedModel[$attributeName]->isSame($value))
  1173. {
  1174. // If there is a current related model and it is the same
  1175. // as the one being set then do nothing.
  1176. }
  1177. else
  1178. {
  1179. if (!in_array($attributeName, $this->unlinkedRelationNames) &&
  1180. isset($this->relationNameToRelatedModel[$attributeName]))
  1181. {
  1182. $this->unlinkedRelationNames[] = $attributeName;
  1183. }
  1184. if ($value === null)
  1185. {
  1186. unset($this->relationNameToRelatedModel[$attributeName]);
  1187. }
  1188. else
  1189. {
  1190. assert("\$value instanceof $relatedModelClassName");
  1191. $this->relationNameToRelatedModel[$attributeName] = $value;
  1192. }
  1193. }
  1194. return true;
  1195. }
  1196. }
  1197. else
  1198. {
  1199. throw new NotSupportedException();
  1200. }
  1201. return false;
  1202. }
  1203. /**
  1204. * Allows testing of the members and relations of the model as if
  1205. * they were actual attributes of the model.
  1206. */
  1207. public function __isset($attributeName)
  1208. {
  1209. assert('is_string($attributeName)');
  1210. assert('$attributeName != ""');
  1211. return $this->isAttribute($attributeName) &&
  1212. $this->$attributeName !== null ||
  1213. !$this->isAttribute($attributeName) &&
  1214. isset($this->$attributeName);
  1215. }
  1216. /**
  1217. * Allows unsetting of the members and relations of the model as if
  1218. * they were actual attributes of the model.
  1219. */
  1220. public function __unset($attributeName)
  1221. {
  1222. assert('is_string($attributeName)');
  1223. assert('$attributeName != ""');
  1224. $this->$attributeName = null;
  1225. }
  1226. /**
  1227. * Returns the member and relation names defined by the extending
  1228. * class's getMetadata() method.
  1229. */
  1230. public function attributeNames()
  1231. {
  1232. return array_keys($this->attributeNameToBeanAndClassName);
  1233. }
  1234. /**
  1235. * Returns true if the named attribute is one of the member or
  1236. * relation names defined by the extending
  1237. * class's getMetadata() method.
  1238. */
  1239. public function isAttribute($attributeName)
  1240. {
  1241. assert('is_string($attributeName)');
  1242. assert('$attributeName != ""');
  1243. return $attributeName == 'id' ||
  1244. array_key_exists($attributeName, $this->attributeNameToBeanAndClassName);
  1245. }
  1246. /**
  1247. * Returns true if the attribute is read-only.
  1248. */
  1249. public function isAttributeReadOnly($attributeName)
  1250. {
  1251. assert("\$this->isAttribute(\"$attributeName\")");
  1252. foreach ($this->validators as $validator)
  1253. {
  1254. if ($validator instanceof RedBeanModelReadOnlyValidator)
  1255. {
  1256. if (in_array($attributeName, $validator->attributes, true))
  1257. {
  1258. return true;
  1259. }
  1260. }
  1261. }
  1262. return false;
  1263. }
  1264. /**
  1265. * @param boolean $attributeName
  1266. * @return true/false whether the attributeName specified, it is allowed to be set externally even though it is
  1267. * a read-only attribute.
  1268. */
  1269. public function isAllowedToSetReadOnlyAttribute($attributeName)
  1270. {
  1271. return false;
  1272. }
  1273. /**
  1274. * Given an attribute return the column name.
  1275. * @param string $attributeName
  1276. */
  1277. public function getColumnNameByAttribute($attributeName)
  1278. {
  1279. assert('is_string($attributeName)');
  1280. if ($this->isRelation($attributeName))
  1281. {
  1282. $modelClassName = get_class($this);
  1283. $columnName = $modelClassName::getForeignKeyName($modelClassName, $attributeName);
  1284. }
  1285. else
  1286. {
  1287. $columnName = strtolower($attributeName);
  1288. }
  1289. return $columnName;
  1290. }
  1291. /**
  1292. * This method is needed to interpret when the attributeName is 'id'. Since id is not an attribute
  1293. * on the model, we manaully check for this and return the appropriate class name.
  1294. * @param string $attributeName
  1295. * @return the model class name for the attribute. This could be a casted up model class name.
  1296. */
  1297. public function resolveAttributeModelClassName($attributeName)
  1298. {
  1299. assert('is_string($attributeName)');
  1300. if ($attributeName == 'id')
  1301. {
  1302. return get_class($this);
  1303. }
  1304. return $this->getAttributeModelClassName($attributeName);
  1305. }
  1306. /**
  1307. * Returns the model class name for an
  1308. * attribute name defined by the extending class's getMetadata() method.
  1309. * For use by RedBeanModelDataProvider. Is unlikely to be of any
  1310. * use to an application.
  1311. */
  1312. public function getAttributeModelClassName($attributeName)
  1313. {
  1314. assert("\$this->isAttribute(\"$attributeName\")");
  1315. return $this->attributeNameToBeanAndClassName[$attributeName][1];
  1316. }
  1317. /**
  1318. * Returns true if the named attribute is one of the
  1319. * relation names defined by the extending
  1320. * class's getMetadata() method.
  1321. */
  1322. public function isRelation($attributeName)
  1323. {
  1324. assert("\$this->isAttribute('$attributeName')");
  1325. return array_key_exists($attributeName, $this->relationNameToRelationTypeModelClassNameAndOwns);
  1326. }
  1327. /**
  1328. * Returns true if the named attribute is one of the
  1329. * relation names defined by the extending
  1330. * class's getMetadata() method, and specifies RedBeanModel::OWNED.
  1331. */
  1332. public function isOwnedRelation($attributeName)
  1333. {
  1334. assert("\$this->isAttribute('$attributeName')");
  1335. return array_key_exists($attributeName, $this->relationNameToRelationTypeModelClassNameAndOwns) &&
  1336. $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][2];
  1337. }
  1338. /**
  1339. * Returns the relation type
  1340. * relation name defined by the extending class's getMetadata() method.
  1341. */
  1342. public function getRelationType($relationName)
  1343. {
  1344. assert("\$this->isRelation('$relationName')");
  1345. return $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][0];
  1346. }
  1347. /**
  1348. * Returns the model class name for a
  1349. * relation name defined by the extending class's getMetadata() method.
  1350. * For use by RedBeanModelDataProvider. Is unlikely to be of any
  1351. * use to an application.
  1352. */
  1353. public function getRelationModelClassName($relationName)
  1354. {
  1355. assert("\$this->isRelation('$relationName')");
  1356. return $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][1];
  1357. }
  1358. /**
  1359. * See the yii documentation. Not used by RedBeanModel.
  1360. * @see getMetadata()
  1361. */
  1362. public function rules()
  1363. {
  1364. throw new NotImplementedException();
  1365. }
  1366. /**
  1367. * See the yii documentation.
  1368. */
  1369. public function behaviors()
  1370. {
  1371. return array();
  1372. }
  1373. /**
  1374. * See the yii documentation.
  1375. * RedBeanModels utilize untranslatedAttributeLabels to store any attribute information, which
  1376. * can then be translated in this method.
  1377. */
  1378. public function attributeLabels()
  1379. {
  1380. $attributeLabels = array();
  1381. foreach ($this->untranslatedAttributeLabels() as $attributeName => $label)
  1382. {
  1383. $attributeLabels[$attributeName] = Yii::t('Default', $label);
  1384. }
  1385. return $attributeLabels;
  1386. }
  1387. /**
  1388. * Array of untranslated attribute labels.
  1389. */
  1390. protected function untranslatedAttributeLabels()
  1391. {
  1392. return array();
  1393. }
  1394. /**
  1395. * Public for message checker only.
  1396. */
  1397. public function getUntranslatedAttributeLabels()
  1398. {
  1399. return $this->untranslatedAttributeLabels();
  1400. }
  1401. /**
  1402. * Performs validation using the validators specified in the 'rules'
  1403. * meta data by the extending class's getMetadata() method.
  1404. * Validation occurs on a new model or a modified model, but only
  1405. * proceeds to modified related models. Once validated a model
  1406. * will pass validation without revalidating until it is modified.
  1407. * Related models are only validated if the model validates.
  1408. * Cyclic relationships are prevented from causing problems by the
  1409. * validation either stopping at a non-validating model and only
  1410. * proceeding to non-validated models.
  1411. * @see RedBeanModel
  1412. * @param $ignoreRequiredValidator - set to true in scenarios where you want to validate everything but the
  1413. * the required validator. An example is a search form.
  1414. */
  1415. public function validate(array $attributeNames = null, $ignoreRequiredValidator = false)
  1416. {
  1417. if ($this->isValidating) // Prevent cycles.
  1418. {
  1419. return true;
  1420. }
  1421. $this->isValidating = true;
  1422. try
  1423. {
  1424. $this->clearErrors();
  1425. if ($this->beforeValidate())
  1426. {
  1427. $hasErrors = false;
  1428. if ($attributeNames === null)
  1429. {
  1430. $attributeNames = $this->attributeNamesNotBelongsToOrManyMany;
  1431. }
  1432. foreach ($this->getValidators() as $validator)
  1433. {
  1434. if ($validator instanceof RedBeanModelRequiredValidator && $validator->applyTo($this->scenarioName))
  1435. {
  1436. if (!$ignoreRequiredValidator)
  1437. {
  1438. $validator->validate($this, $attributeNames);
  1439. }
  1440. }
  1441. elseif (!$validator instanceof CDefaultValueValidator && $validator->applyTo($this->scenarioName))
  1442. {
  1443. $validator->validate($this, $attributeNames);
  1444. }
  1445. }
  1446. $relatedModelsHaveErrors = false;
  1447. foreach ($this->relationNameToRelatedModel as $relationName => $relatedModel)
  1448. {
  1449. if ((!$this->$relationName instanceof RedBeanModel) ||
  1450. !$this->$relationName->isSame($this))
  1451. {
  1452. if (in_array($relationName, $attributeNames) &&
  1453. ($this->$relationName->isModified() ||
  1454. ($this->isAttributeRequired($relationName) && !$ignoreRequiredValidator) &&
  1455. !$this->isSame($this->$relationName))) // Prevent cycles.
  1456. {
  1457. if (!$this->$relationName->validate(null, $ignoreRequiredValidator))
  1458. {
  1459. $hasErrors = true;
  1460. }
  1461. }
  1462. }
  1463. }
  1464. $this->afterValidate();
  1465. $hasErrors = $hasErrors || count($this->attributeNameToErrors) > 0;
  1466. // Put these asserts back if there are suspitions about validate/hasErrors/getErrors
  1467. // producing inconsistent results. But for now it is commented out because
  1468. // it makes too big an impact.
  1469. //assert('$hasErrors == (count($this->getErrors()) > 0)');
  1470. //assert('$hasErrors == $this->hasErrors()');
  1471. $this->isValidating = false;
  1472. return !$hasErrors;
  1473. }
  1474. $this->isValidating = false;
  1475. return false;
  1476. }
  1477. catch (Exception $e)
  1478. {
  1479. $this->isValidating = false;
  1480. throw $e;
  1481. }
  1482. }
  1483. /**
  1484. * See the yii documentation.
  1485. */
  1486. protected function beforeValidate()
  1487. {
  1488. $event = new CModelEvent($this);
  1489. $this->onBeforeValidate($event);
  1490. return $event->isValid;
  1491. }
  1492. /**
  1493. * See the yii documentation.
  1494. */
  1495. protected function afterValidate()
  1496. {
  1497. $this->onAfterValidate(new CEvent($this));
  1498. }
  1499. /**
  1500. * See the yii documentation.
  1501. */
  1502. public function onBeforeValidate(CModelEvent $event)
  1503. {
  1504. $this->raiseEvent('onBeforeValidate', $event);
  1505. }
  1506. /**
  1507. * See the yii documentation.
  1508. */
  1509. public function onAfterValidate($event)
  1510. {
  1511. $this->raiseEvent('onAfterValidate', $event);
  1512. }
  1513. /**
  1514. * See the yii documentation.
  1515. */
  1516. public function getValidatorList()
  1517. {
  1518. return $this->validators;
  1519. }
  1520. /**
  1521. * See the yii documentation.
  1522. */
  1523. public function getValidators($attributeName = null)
  1524. {
  1525. assert("\$attributeName === null || \$this->isAttribute('$attributeName')");
  1526. $validators = array();
  1527. $scenarioName = $this->scenarioName;
  1528. foreach ($this->validators as $validator)
  1529. {
  1530. if ($scenarioName === null || $validator->applyTo($scenarioName))
  1531. {
  1532. if ($attributeName === null || in_array($attributeName, $validator->attributes, true))
  1533. {
  1534. $validators[] = $validator;
  1535. }
  1536. }
  1537. }
  1538. return $validators;
  1539. }
  1540. /**
  1541. * See the yii documentation.
  1542. */
  1543. public function createValidators()
  1544. {
  1545. throw new NotImplementedException();
  1546. }
  1547. /**
  1548. * Returns true if the attribute value does not already exist in
  1549. * the database. This is used in the unique validator, but on saving
  1550. * RedBean can still throw because the unique constraint on the column
  1551. * has been violated because it was concurrently updated between the
  1552. * Yii validator being called and the save actually occuring.
  1553. */
  1554. public function isUniqueAttributeValue($attributeName, $value)
  1555. {
  1556. assert("\$this->isAttribute('$attributeName')");
  1557. assert('$value !== null');
  1558. if (!$this->isRelation($attributeName))
  1559. {
  1560. $modelClassName = $this->attributeNameToBeanAndClassName[$attributeName][1];
  1561. $tableName = self::getTableName($modelClassName);
  1562. $rows = R::getAll('select id from ' . $tableName . " where $attributeName = ?", array($value));
  1563. return count($rows) == 0 || count($rows) == 1 && $rows[0]['id'] == $this->id;
  1564. }
  1565. else
  1566. {
  1567. $model = $this->$attributeName;
  1568. if ($model->id == 0)
  1569. {
  1570. return true;
  1571. }
  1572. $modelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][1];
  1573. $tableName = self::getTableName($modelClassName);
  1574. $rows = R::getAll('select id from ' . $tableName . ' where id = ?', array($model->id));
  1575. return count($rows) == 0 || count($rows) == 1 && $rows[0]['id'] == $this->id;
  1576. }
  1577. }
  1578. /**
  1579. * Saves the model to the database. Models are only saved if they have been
  1580. * modified and related models are saved before this model. If a related model
  1581. * is modified and needs saving the deems the model to be modified and need
  1582. * saving, which ensures that keys are updated.
  1583. * Cyclic relationships are prevented from causing problems by the
  1584. * save only proceeding to non-saved models.
  1585. */
  1586. public function save($runValidation = true, array $attributeNames = null)
  1587. {
  1588. if ($attributeNames !== null)
  1589. {
  1590. throw new NotSupportedException();
  1591. }
  1592. if ($this->isSaving) // Prevent cycles.
  1593. {
  1594. return true;
  1595. }
  1596. $this->isSaving = true;
  1597. try
  1598. {
  1599. if (!$runValidation || $this->validate())
  1600. {
  1601. if ($this->beforeSave())
  1602. {
  1603. $beans = array_values($this->modelClassNameToBean);
  1604. $this->linkBeans();
  1605. // The breakLink/link is deferred until the save to avoid
  1606. // disconnecting or creating an empty row if the model was
  1607. // never actually saved.
  1608. foreach ($this->unlinkedRelationNames as $key => $relationName)
  1609. {
  1610. $bean = $this->attributeNameToBeanAndClassName [$relationName][0];
  1611. $relatedModelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][1];
  1612. $relatedTableName = self::getTableName($relatedModelClassName);
  1613. $linkName = strtolower($relationName);
  1614. if ($linkName == strtolower($relatedModelClassName))
  1615. {
  1616. $linkName = null;
  1617. }
  1618. R::$linkManager->breakLink($bean, $relatedTableName, $linkName);
  1619. unset($this->unlinkedRelationNames[$key]);
  1620. }
  1621. assert('count($this->unlinkedRelationNames) == 0');
  1622. foreach ($this->relationNameToRelatedModel as $relationName => $relatedModel)
  1623. {
  1624. $relationType = $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][0];
  1625. if ($relatedModel instanceof RedBeanModel)
  1626. {
  1627. $bean = $this->attributeNameToBeanAndClassName [$relationName][0];
  1628. $relatedModelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][1];
  1629. $linkName = strtolower($relationName);
  1630. if (strtolower($linkName) == strtolower($relatedModelClassName))
  1631. {
  1632. $linkName = null;
  1633. }
  1634. elseif ($relationType == RedBeanModel::HAS_MANY_BELONGS_TO)
  1635. {
  1636. $label = 'Relations of type HAS_MANY_BELONGS_TO must have the relation name ' .
  1637. 'the same as the related model class name. Relation: {relationName} ' .
  1638. 'Relation model class name: {relationModelClassName}';
  1639. throw new NotSupportedException(Yii::t('Default', $label,
  1640. array('{relationName}' => $linkName,
  1641. '{relationModelClassName}' => $relatedModelClassName)));
  1642. }
  1643. if ($relatedModel->isModified() ||
  1644. $relatedModel->id > 0 ||
  1645. $this->isAttributeRequired($relationName))
  1646. {
  1647. $relatedModel = $this->relationNameToRelatedModel[$relationName];
  1648. $relatedBean = $relatedModel->getClassBean($relatedModelClassName);
  1649. R::$linkManager->link($bean, $relatedBean, $linkName);
  1650. if (!RedBeanDatabase::isFrozen())
  1651. {
  1652. $tableName = self::getTableName($this->getAttributeModelClassName($relationName));
  1653. $columnName = self::getForeignKeyName(get_class($this), $relationName);
  1654. RedBean_Plugin_Optimizer_Id::ensureIdColumnIsINT11($tableName, $columnName);
  1655. }
  1656. }
  1657. }
  1658. if (!in_array($relationType, array(self::HAS_ONE_BELONGS_TO,
  1659. self::HAS_MANY_BELONGS_TO)))
  1660. {
  1661. if ($relatedModel->isModified() ||
  1662. ($this->isAttributeRequired($relationName) ))
  1663. {
  1664. // Validation of this model has already done.
  1665. if (!$relatedModel->save(false))
  1666. {
  1667. $this->isSaving = false;
  1668. return false;
  1669. }
  1670. }
  1671. }
  1672. }
  1673. $baseModelClassName = null;
  1674. foreach ($this->modelClassNameToBean as $modelClassName => $bean)
  1675. {
  1676. R::store($bean);
  1677. assert('$bean->id > 0');
  1678. if (!RedBeanDatabase::isFrozen())
  1679. {
  1680. static::resolveMixinsOnSaveForEnsuringColumnsAreCorrectlyFormed($baseModelClassName,
  1681. $modelClassName);
  1682. $baseModelClassName = $modelClassName;
  1683. }
  1684. }
  1685. $this->modified = false;
  1686. $this->afterSave();
  1687. RedBeanModelsCache::cacheModel($this);
  1688. $this->isSaving = false;
  1689. return true;
  1690. }
  1691. }
  1692. $this->isSaving = false;
  1693. return false;
  1694. }
  1695. catch (Exception $e)
  1696. {
  1697. $this->isSaving = false;
  1698. throw $e;
  1699. }
  1700. }
  1701. /**
  1702. * Resolve that the id columns are properly formed as integers.
  1703. * @param string or null $baseModelClassName
  1704. * @param string $modelClassName
  1705. */
  1706. protected static function resolveMixinsOnSaveForEnsuringColumnsAreCorrectlyFormed($baseModelClassName, $modelClassName)
  1707. {
  1708. assert('$baseModelClassName == null || is_string($baseModelClassName)');
  1709. assert('is_string($modelClassName)');
  1710. if ($baseModelClassName !== null)
  1711. {
  1712. $tableName = self::getTableName($modelClassName);
  1713. $columnName = self::getTableName($baseModelClassName) . '_id';
  1714. RedBean_Plugin_Optimizer_Id::ensureIdColumnIsINT11($tableName, $columnName);
  1715. }
  1716. }
  1717. protected function beforeSave()
  1718. {
  1719. return true;
  1720. }
  1721. protected function afterSave()
  1722. {
  1723. }
  1724. protected function linkBeans()
  1725. {
  1726. $baseModelClassName = null;
  1727. $baseBean = null;
  1728. foreach ($this->modelClassNameToBean as $modelClassName => $bean)
  1729. {
  1730. if ($baseBean !== null)
  1731. {
  1732. R::$linkManager->link($bean, $baseBean);
  1733. if (!RedBeanDatabase::isFrozen())
  1734. {
  1735. $tableName = self::getTableName($modelClassName);
  1736. $columnName = self::getTableName($baseModelClassName) . '_id';
  1737. RedBean_Plugin_Optimizer_Id::ensureIdColumnIsINT11($tableName, $columnName);
  1738. }
  1739. }
  1740. $baseModelClassName = $modelClassName;
  1741. $baseBean = $bean;
  1742. }
  1743. }
  1744. /**
  1745. * Returns true if the model has been modified since it was saved
  1746. * or constructed.
  1747. */
  1748. public function isModified()
  1749. {
  1750. if ($this->modified)
  1751. {
  1752. return true;
  1753. }
  1754. if ($this->isInIsModified) // Prevent cycles.
  1755. {
  1756. return false;
  1757. }
  1758. $this->isInIsModified = true;
  1759. try
  1760. {
  1761. foreach ($this->relationNameToRelatedModel as $relationName => $relatedModel)
  1762. {
  1763. if ((!$this->$relationName instanceof RedBeanModel) ||
  1764. !$this->$relationName->isSame($this))
  1765. {
  1766. if (!in_array($this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][0],
  1767. array(self::HAS_ONE_BELONGS_TO,
  1768. self::HAS_MANY_BELONGS_TO,
  1769. self::MANY_MANY)))
  1770. {
  1771. if ($this->$relationName->isModified() ||
  1772. $this->isAttributeRequired($relationName) &&
  1773. $this->$relationName->id <= 0)
  1774. {
  1775. $this->isInIsModified = false;
  1776. return true;
  1777. }
  1778. }
  1779. }
  1780. }
  1781. $this->isInIsModified = false;
  1782. return false;
  1783. }
  1784. catch (Exception $e)
  1785. {
  1786. $this->isInIsModified = false;
  1787. throw $e;
  1788. }
  1789. }
  1790. /**
  1791. * Deletes the model from the database.
  1792. */
  1793. public function delete()
  1794. {
  1795. if ($this->id < 0)
  1796. {
  1797. // If the model was never saved
  1798. // then it doesn't need to be deleted.
  1799. return;
  1800. }
  1801. $modelClassName = get_called_class();
  1802. if (!$modelClassName::isTypeDeletable() ||
  1803. !$this->isDeletable())
  1804. {
  1805. // See comments below on isDeletable.
  1806. throw new NotSupportedException();
  1807. }
  1808. $this->beforeDelete();
  1809. $this->unrestrictedDelete();
  1810. $this->afterDelete();
  1811. }
  1812. protected function beforeDelete()
  1813. {
  1814. }
  1815. protected function afterDelete()
  1816. {
  1817. }
  1818. protected function unrestrictedDelete()
  1819. {
  1820. $this->forget();
  1821. // RedBeanModel only supports cascaded deletes on associations,
  1822. // not on links. So for now at least they are done the slow way.
  1823. foreach (RuntimeUtil::getClassHierarchy(get_class($this), 'RedBeanModel') as $modelClassName)
  1824. {
  1825. $this->deleteOwnedRelatedModels ($modelClassName);
  1826. $this->deleteForeignRelatedModels($modelClassName);
  1827. }
  1828. foreach ($this->modelClassNameToBean as $modelClassName => $bean)
  1829. {
  1830. R::trash($bean);
  1831. }
  1832. // The model cannot be used anymore.
  1833. $this->deleted = true;
  1834. }
  1835. public function isDeleted()
  1836. {
  1837. return $this->deleted;
  1838. }
  1839. protected function deleteOwnedRelatedModels($modelClassName)
  1840. {
  1841. foreach ($this->relationNameToRelationTypeModelClassNameAndOwns as $relationName => $relationTypeModelClassNameAndOwns)
  1842. {
  1843. assert('count($relationTypeModelClassNameAndOwns) == 3');
  1844. $relationType = $relationTypeModelClassNameAndOwns[0];
  1845. $owns = $relationTypeModelClassNameAndOwns[2];
  1846. if ($owns)
  1847. {
  1848. if ((!$this->$relationName instanceof RedBeanModel) ||
  1849. !$this->$relationName->isSame($this))
  1850. {
  1851. assert('in_array($relationType, array(self::HAS_ONE, self::HAS_MANY))');
  1852. if ($relationType == self::HAS_ONE)
  1853. {
  1854. if ($this->$relationName->id > 0)
  1855. {
  1856. $this->$relationName->unrestrictedDelete();
  1857. }
  1858. }
  1859. else
  1860. {
  1861. foreach ($this->$relationName as $model)
  1862. {
  1863. $model->unrestrictedDelete();
  1864. }
  1865. }
  1866. }
  1867. }
  1868. }
  1869. }
  1870. protected function deleteForeignRelatedModels($modelClassName)
  1871. {
  1872. $metadata = $this->getMetadata();
  1873. if (isset($metadata[$modelClassName]['foreignRelations']))
  1874. {
  1875. foreach ($metadata[$modelClassName]['foreignRelations'] as $relatedModelClassName)
  1876. {
  1877. $relatedModels = $relatedModelClassName::
  1878. getByRelatedClassId($relatedModelClassName,
  1879. $this->getClassId($modelClassName),
  1880. $modelClassName);
  1881. foreach ($relatedModels as $relatedModel)
  1882. {
  1883. $relatedModel->unrestrictedDelete();
  1884. }
  1885. }
  1886. }
  1887. }
  1888. protected static function getByRelatedClassId($relatedModelClassName, $id, $modelClassName = null)
  1889. {
  1890. assert('is_string($relatedModelClassName)');
  1891. assert('$relatedModelClassName != ""');
  1892. assert('is_int($id)');
  1893. assert('$id > 0');
  1894. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  1895. if ($modelClassName === null)
  1896. {
  1897. $modelClassName = get_called_class();
  1898. }
  1899. $tableName = self::getTableName($relatedModelClassName);
  1900. $foreignKeyName = strtolower($modelClassName) . '_id';
  1901. $beans = RedBean_Plugin_Finder::where($tableName, "$foreignKeyName = $id");
  1902. return self::makeModels($beans, $relatedModelClassName);
  1903. }
  1904. /**
  1905. * To be overriden on intermediate derived classes
  1906. * to return false so that deletes are not done on
  1907. * intermediate classes because the object relational
  1908. * mapping will not clean up properly.
  1909. * For example if User is a Person, and Person is
  1910. * a RedBeanModel delete should be called only on User,
  1911. * not on Person. So User must override isDeletable
  1912. * to return false.
  1913. */
  1914. public static function isTypeDeletable()
  1915. {
  1916. return true;
  1917. }
  1918. /**
  1919. * To be overridden by derived classes to prevent
  1920. * deletion.
  1921. */
  1922. public function isDeletable()
  1923. {
  1924. return true;
  1925. }
  1926. /**
  1927. * Forgets about all of the objects so that when they are retrieved
  1928. * again they will be recreated from the database. For use in testing.
  1929. */
  1930. public static function forgetAll()
  1931. {
  1932. RedBeanModelsCache::forgetAll();
  1933. RedBeansCache::forgetAll();
  1934. }
  1935. /**
  1936. * Forgets about the object so that if it is retrieved
  1937. * again it will be recreated from the database. For use in testing.
  1938. */
  1939. public function forget()
  1940. {
  1941. RedBeanModelsCache::forgetModel($this);
  1942. RedBeansCache::forgetBean(self::getTableName(get_called_class()) . $this->id);
  1943. }
  1944. /**
  1945. * See the yii documentation.
  1946. */
  1947. public function isAttributeRequired($attributeName)
  1948. {
  1949. assert("\$this->isAttribute('$attributeName')");
  1950. foreach ($this->getValidators($attributeName) as $validator)
  1951. {
  1952. if ($validator instanceof CRequiredValidator)
  1953. {
  1954. return true;
  1955. }
  1956. }
  1957. return false;
  1958. }
  1959. /**
  1960. * See the yii documentation.
  1961. */
  1962. public function isAttributeSafe($attributeName)
  1963. {
  1964. $attributeNames = $this->getSafeAttributeNames();
  1965. return in_array($attributeName, $attributeNames);
  1966. }
  1967. public static function getModelLabelByTypeAndLanguage($type, $language = null)
  1968. {
  1969. assert('in_array($type, array("Singular", "SingularLowerCase", "Plural", "PluralLowerCase"))');
  1970. if ($type == 'Singular')
  1971. {
  1972. return Yii::t('Default', static::getLabel(),
  1973. LabelUtil::getTranslationParamsForAllModules(), null, $language);
  1974. }
  1975. if ($type == 'SingularLowerCase')
  1976. {
  1977. return strtolower(Yii::t('Default', static::getLabel(),
  1978. LabelUtil::getTranslationParamsForAllModules(), null, $language));
  1979. }
  1980. if ($type == 'Plural')
  1981. {
  1982. return Yii::t('Default', static::getPluralLabel(),
  1983. LabelUtil::getTranslationParamsForAllModules(), null, $language);
  1984. }
  1985. if ($type == 'PluralLowerCase')
  1986. {
  1987. return strtolower(Yii::t('Default', static::getPluralLabel(),
  1988. LabelUtil::getTranslationParamsForAllModules(), null, $language));
  1989. }
  1990. }
  1991. protected static function getLabel()
  1992. {
  1993. return get_called_class();
  1994. }
  1995. protected static function getPluralLabel()
  1996. {
  1997. return static::getLabel() . 's';
  1998. }
  1999. /**
  2000. * See the yii documentation.
  2001. */
  2002. public function getAttributeLabel($attributeName)
  2003. {
  2004. return $this->getAttributeLabelByLanguage($attributeName, Yii::app()->language);
  2005. }
  2006. /**
  2007. * Given an attributeName and a language, retrieve the translated attribute label. Attempts to find a customized
  2008. * label in the metadata first, before falling back on the standard attribute label for the specified attribute.
  2009. * @return string - translated attribute label
  2010. */
  2011. protected function getAttributeLabelByLanguage($attributeName, $language)
  2012. {
  2013. assert('is_string($attributeName)');
  2014. assert('is_string($language)');
  2015. $labels = $this->untranslatedAttributeLabels();
  2016. $customLabel = $this->getTranslatedCustomAttributeLabelByLanguage($attributeName, $language);
  2017. if ($customLabel != null)
  2018. {
  2019. return $customLabel;
  2020. }
  2021. elseif (isset($labels[$attributeName]))
  2022. {
  2023. return Yii::t('Default', $labels[$attributeName],
  2024. LabelUtil::getTranslationParamsForAllModules(), null, $language);
  2025. }
  2026. else
  2027. {
  2028. //should do a T:: wrapper here too.
  2029. return Yii::t('Default', $this->generateAttributeLabel($attributeName), array(), null, $language);
  2030. }
  2031. }
  2032. /**
  2033. * Given an attributeName, attempt to find in the metadata a custom attribute label for the given language.
  2034. * @return string - translated attribute label, if not found return null.
  2035. */
  2036. protected function getTranslatedCustomAttributeLabelByLanguage($attributeName, $language)
  2037. {
  2038. assert('is_string($attributeName)');
  2039. assert('is_string($language)');
  2040. $metadata = $this->getMetadata();
  2041. foreach ($metadata as $modelClassName => $modelClassMetadata)
  2042. {
  2043. if (isset($modelClassMetadata['labels']) &&
  2044. isset($modelClassMetadata['labels'][$attributeName]) &&
  2045. isset($modelClassMetadata['labels'][$attributeName][$language]))
  2046. {
  2047. return $modelClassMetadata['labels'][$attributeName][$language];
  2048. }
  2049. }
  2050. return null;
  2051. }
  2052. /**
  2053. * Given an attributeName, return an array of all attribute labels for each language available.
  2054. * @return array - attribute labels by language for the given attributeName.
  2055. */
  2056. public function getAttributeLabelsForAllSupportedLanguagesByAttributeName($attributeName)
  2057. {
  2058. assert('is_string($attributeName)');
  2059. $attirbuteLabelData = array();
  2060. foreach (Yii::app()->languageHelper->getSupportedLanguagesData() as $language => $name)
  2061. {
  2062. $attirbuteLabelData[$language] = $this->getAttributeLabelByLanguage($attributeName, $language);
  2063. }
  2064. return $attirbuteLabelData;
  2065. }
  2066. /**
  2067. * See the yii documentation. The yii hasErrors() takes an optional
  2068. * attribute name. RedBeanModel's hasErrors() takes an optional attribute
  2069. * name or array of attribute names. See getErrors() for an explanation
  2070. * of this difference.
  2071. */
  2072. public function hasErrors($attributeNameOrNames = null)
  2073. {
  2074. assert('$attributeNameOrNames === null || ' .
  2075. 'is_string($attributeNameOrNames) || ' .
  2076. 'is_array ($attributeNameOrNames) && AssertUtil::all($attributeNameOrNames, "is_string")');
  2077. if ($this->isInHasErrors) // Prevent cycles.
  2078. {
  2079. return false;
  2080. }
  2081. $this->isInHasErrors = true;
  2082. try
  2083. {
  2084. if (is_string($attributeNameOrNames))
  2085. {
  2086. $attributeName = $attributeNameOrNames;
  2087. $relatedAttributeNames = null;
  2088. }
  2089. elseif (is_array($attributeNameOrNames))
  2090. {
  2091. $attributeName = $attributeNameOrNames[0];
  2092. if (count($attributeNameOrNames) > 1)
  2093. {
  2094. $relatedAttributeNames = array_slice($attributeNameOrNames, 1);
  2095. }
  2096. else
  2097. {
  2098. $relatedAttributeNames = null;
  2099. }
  2100. }
  2101. else
  2102. {
  2103. $attributeName = null;
  2104. $relatedAttributeNames = null;
  2105. }
  2106. assert("\$attributeName === null || is_string('$attributeName')");
  2107. assert('$relatedAttributeNames === null || is_array($relatedAttributeNames)');
  2108. assert('!($attributeName === null && $relatedAttributeNames !== null)');
  2109. if ($attributeName === null)
  2110. {
  2111. if (count($this->attributeNameToErrors) > 0)
  2112. {
  2113. $this->isInHasErrors = false;
  2114. return true;
  2115. }
  2116. foreach ($this->relationNameToRelatedModel as $relationName => $relatedModelOrModels)
  2117. {
  2118. if ((!$this->$relationName instanceof RedBeanModel) ||
  2119. !$this->$relationName->isSame($this))
  2120. {
  2121. if (in_array($relationName, $this->attributeNamesNotBelongsToOrManyMany))
  2122. {
  2123. if ($relatedModelOrModels->hasErrors($relatedAttributeNames))
  2124. {
  2125. $this->isInHasErrors = false;
  2126. return true;
  2127. }
  2128. }
  2129. }
  2130. }
  2131. $this->isInHasErrors = false;
  2132. return false;
  2133. }
  2134. else
  2135. {
  2136. if (!$this->isRelation($attributeName))
  2137. {
  2138. $this->isInHasErrors = false;
  2139. return array_key_exists($attributeName, $this->attributeNameToErrors);
  2140. }
  2141. else
  2142. {
  2143. if (in_array($attributeName, $this->attributeNamesNotBelongsToOrManyMany))
  2144. {
  2145. $this->isInHasErrors = false;
  2146. return isset($this->relationNameToRelatedModel[$attributeName]) &&
  2147. count($this->relationNameToRelatedModel[$attributeName]->getErrors($relatedAttributeNames)) > 0;
  2148. }
  2149. }
  2150. }
  2151. $this->isInHasErrors = false;
  2152. return false;
  2153. }
  2154. catch (Exception $e)
  2155. {
  2156. $this->isInHasErrors = false;
  2157. throw $e;
  2158. }
  2159. }
  2160. /**
  2161. * See the yii documentation. The yii getErrors() takes an optional
  2162. * attribute name. RedBeanModel's getErrors() takes an optional attribute
  2163. * name or array of attribute names.
  2164. * @param @attributeNameOrNames Either null, return all errors on the
  2165. * model and its related models, an attribute name on the model, return
  2166. * errors on that attribute, or an array of relation and attribute names,
  2167. * return errors on a related model's attribute.
  2168. */
  2169. public function getErrors($attributeNameOrNames = null)
  2170. {
  2171. assert('$attributeNameOrNames === null || ' .
  2172. 'is_string($attributeNameOrNames) || ' .
  2173. 'is_array ($attributeNameOrNames) && AssertUtil::all($attributeNameOrNames, "is_string")');
  2174. if ($this->isInGetErrors) // Prevent cycles.
  2175. {
  2176. return array();
  2177. }
  2178. $this->isInGetErrors = true;
  2179. try
  2180. {
  2181. if (is_string($attributeNameOrNames))
  2182. {
  2183. $attributeName = $attributeNameOrNames;
  2184. $relatedAttributeNames = null;
  2185. }
  2186. elseif (is_array($attributeNameOrNames))
  2187. {
  2188. $attributeName = $attributeNameOrNames[0];
  2189. if (count($attributeNameOrNames) > 1)
  2190. {
  2191. $relatedAttributeNames = array_slice($attributeNameOrNames, 1);
  2192. }
  2193. else
  2194. {
  2195. $relatedAttributeNames = null;
  2196. }
  2197. }
  2198. else
  2199. {
  2200. $attributeName = null;
  2201. $relatedAttributeNames = null;
  2202. }
  2203. assert("\$attributeName === null || is_string('$attributeName')");
  2204. assert('$relatedAttributeNames === null || is_array($relatedAttributeNames)');
  2205. assert('!($attributeName === null && $relatedAttributeNames !== null)');
  2206. if ($attributeName === null)
  2207. {
  2208. $errors = $this->attributeNameToErrors;
  2209. foreach ($this->relationNameToRelatedModel as $relationName => $relatedModelOrModels)
  2210. {
  2211. if ((!$this->$relationName instanceof RedBeanModel) ||
  2212. !$this->$relationName->isSame($this))
  2213. {
  2214. if (!in_array($this->relationNameToRelationTypeModelClassNameAndOwns[$relationName][0],
  2215. array(self::HAS_ONE_BELONGS_TO,
  2216. self::HAS_MANY_BELONGS_TO,
  2217. self::MANY_MANY)))
  2218. {
  2219. $relatedErrors = $relatedModelOrModels->getErrors($relatedAttributeNames);
  2220. if (count($relatedErrors) > 0)
  2221. {
  2222. $errors[$relationName] = $relatedErrors;
  2223. }
  2224. }
  2225. }
  2226. }
  2227. $this->isInGetErrors = false;
  2228. return $errors;
  2229. }
  2230. else
  2231. {
  2232. if (isset($this->attributeNameToErrors[$attributeName]))
  2233. {
  2234. $this->isInGetErrors = false;
  2235. return $this->attributeNameToErrors[$attributeName];
  2236. }
  2237. elseif (isset($this->relationNameToRelatedModel[$attributeName]))
  2238. {
  2239. if (!in_array($this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][0],
  2240. array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO)))
  2241. {
  2242. $this->isInGetErrors = false;
  2243. return $this->relationNameToRelatedModel[$attributeName]->getErrors($relatedAttributeNames);
  2244. }
  2245. }
  2246. }
  2247. $this->isInGetErrors = false;
  2248. return array();
  2249. }
  2250. catch (Exception $e)
  2251. {
  2252. $this->isInGetErrors = false;
  2253. throw $e;
  2254. }
  2255. }
  2256. /**
  2257. * See the yii documentation.
  2258. */
  2259. public function getError($attributeName)
  2260. {
  2261. assert("\$this->isAttribute('$attributeName')");
  2262. return isset($this->attributeNameToErrors[$attributeName]) ? reset($this->attributeNameToErrors[$attributeName]) : null;
  2263. }
  2264. /**
  2265. * See the yii documentation.
  2266. */
  2267. public function addError($attributeName, $errorMessage)
  2268. {
  2269. assert("\$this->isAttribute('$attributeName')");
  2270. if (!isset($this->attributeNameToErrors[$attributeName]))
  2271. {
  2272. $this->attributeNameToErrors[$attributeName] = array();
  2273. }
  2274. $this->attributeNameToErrors[$attributeName][] = $errorMessage;
  2275. }
  2276. /**
  2277. * See the yii documentation.
  2278. */
  2279. public function addErrors(array $errors)
  2280. {
  2281. foreach ($errors as $attributeName => $error)
  2282. {
  2283. assert("\$this->isAttribute('$attributeName')");
  2284. assert('is_array($error) || is_string($error)');
  2285. if (is_array($error))
  2286. {
  2287. if (!isset($this->attributeNameToErrors[$attributeName]))
  2288. {
  2289. $this->attributeNameToErrors[$attributeName] = array();
  2290. }
  2291. $this->attributeNameToErrors[$attributeName] =
  2292. array_merge($this->attributeNameToErrors[$attributeName], $error);
  2293. }
  2294. else
  2295. {
  2296. $this->attributeNameToErrors[$attributeName][] = $error;
  2297. }
  2298. }
  2299. }
  2300. /**
  2301. * See the yii documentation.
  2302. */
  2303. public function clearErrors($attributeName = null)
  2304. {
  2305. assert("\$attributeName === null || \$this->isAttribute('$attributeName')");
  2306. if ($attributeName === null)
  2307. {
  2308. $this->attributeNameToErrors = array();
  2309. }
  2310. else
  2311. {
  2312. unset($this->attributeNameToErrors[$attributeName]);
  2313. }
  2314. }
  2315. /**
  2316. * See the yii documentation.
  2317. */
  2318. public function generateAttributeLabel($attributeName)
  2319. {
  2320. assert("\$this->isAttribute('$attributeName')");
  2321. return ucfirst(preg_replace('/([A-Z0-9])/', ' \1', $attributeName));
  2322. }
  2323. /**
  2324. * See the yii documentation.
  2325. */
  2326. public function getAttributes(array $attributeNames = null)
  2327. {
  2328. $values = array();
  2329. if (is_array($attributeNames))
  2330. {
  2331. $values2 = array();
  2332. $allModelAttributeNames = $this->attributeNames();
  2333. foreach ($attributeNames as $attributeName)
  2334. {
  2335. if (in_array($attributeName, $allModelAttributeNames))
  2336. {
  2337. $values2[$attributeName] = $this->$attributeName;
  2338. }
  2339. }
  2340. return $values2;
  2341. }
  2342. else
  2343. {
  2344. foreach ($this->attributeNames() as $attributeName)
  2345. {
  2346. $values[$attributeName] = $this->$attributeName;
  2347. }
  2348. return $values;
  2349. }
  2350. }
  2351. /**
  2352. * See the yii documentation.
  2353. */
  2354. public function setAttributes(array $values, $safeOnly = true)
  2355. {
  2356. assert('is_bool($safeOnly)');
  2357. $attributeNames = array_flip($safeOnly ? $this->getSafeAttributeNames() : $this->attributeNames());
  2358. foreach ($values as $attributeName => $value)
  2359. {
  2360. if ($value !== null)
  2361. {
  2362. if (!is_array($value))
  2363. {
  2364. assert('$attributeName != "id"');
  2365. if ($attributeName != 'id' && $this->isAttribute($attributeName))
  2366. {
  2367. if ($this->isAttributeSafe($attributeName) || !$safeOnly)
  2368. {
  2369. $this->$attributeName = $value;
  2370. }
  2371. else
  2372. {
  2373. $this->onUnsafeAttribute($attributeName, $value);
  2374. }
  2375. }
  2376. }
  2377. else
  2378. {
  2379. if ($this->isRelation($attributeName))
  2380. {
  2381. if (count($value) == 1 && array_key_exists('id', $value))
  2382. {
  2383. if (empty($value['id']))
  2384. {
  2385. $this->$attributeName = null;
  2386. }
  2387. else
  2388. {
  2389. $relatedModelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][1];
  2390. $this->$attributeName = self::getById(intval($value['id']), $relatedModelClassName);
  2391. }
  2392. }
  2393. else
  2394. {
  2395. $setAttributeMethodName = 'set' . ucfirst($attributeName);
  2396. if ($this->$attributeName instanceof RedBeanOneToManyRelatedModels &&
  2397. method_exists($this, $setAttributeMethodName))
  2398. {
  2399. $this->$setAttributeMethodName($value);
  2400. }
  2401. else
  2402. {
  2403. $this->$attributeName->setAttributes($value);
  2404. }
  2405. }
  2406. }
  2407. }
  2408. }
  2409. }
  2410. }
  2411. /**
  2412. * See the yii documentation.
  2413. */
  2414. public function unsetAttributes($attributeNames = null)
  2415. {
  2416. if ($attributeNames === null)
  2417. {
  2418. $attributeNames = $this->attributeNames();
  2419. }
  2420. foreach ($attributeNames as $attributeName)
  2421. {
  2422. $this->$attributeNames = null;
  2423. }
  2424. }
  2425. /**
  2426. * See the yii documentation.
  2427. */
  2428. public function onUnsafeAttribute($name, $value)
  2429. {
  2430. if (YII_DEBUG)
  2431. {
  2432. Yii::log(Yii::t('yii', 'Failed to set unsafe attribute "{attribute}".', array('{attribute}' => $name)), CLogger::LEVEL_WARNING);
  2433. }
  2434. }
  2435. /**
  2436. * See the yii documentation.
  2437. */
  2438. public function getScenario()
  2439. {
  2440. return $this->scenarioName;
  2441. }
  2442. /**
  2443. * See the yii documentation.
  2444. */
  2445. public function setScenario($scenarioName)
  2446. {
  2447. assert('is_string($scenarioName)');
  2448. $this->scenarioName = $scenarioName;
  2449. }
  2450. /**
  2451. * See the yii documentation.
  2452. */
  2453. public function getSafeAttributeNames()
  2454. {
  2455. $attributeNamesToIsSafe = array();
  2456. $unsafeAttributeNames = array();
  2457. foreach ($this->getValidators() as $validator)
  2458. {
  2459. if (!$validator->safe)
  2460. {
  2461. foreach ($validator->attributes as $attributeName)
  2462. {
  2463. $unsafeAttributeNames[] = $attributeName;
  2464. }
  2465. }
  2466. else
  2467. {
  2468. foreach ($validator->attributes as $attributeName)
  2469. {
  2470. $attributeNamesToIsSafe[$attributeName] = true;
  2471. }
  2472. }
  2473. }
  2474. foreach ($unsafeAttributeNames as $attributeName)
  2475. {
  2476. unset($attributeNamesToIsSafe[$attributeName]);
  2477. }
  2478. return array_keys($attributeNamesToIsSafe);
  2479. }
  2480. /**
  2481. * See the yii documentation.
  2482. */
  2483. public function getIterator()
  2484. {
  2485. throw new NotImplementedException();
  2486. }
  2487. /**
  2488. * See the yii documentation.
  2489. */
  2490. public function offsetExists($offset)
  2491. {
  2492. throw new NotImplementedException();
  2493. }
  2494. /**
  2495. * See the yii documentation.
  2496. */
  2497. public function offsetGet($offset)
  2498. {
  2499. throw new NotImplementedException();
  2500. }
  2501. /**
  2502. * See the yii documentation.
  2503. */
  2504. public function offsetSet($offset, $item)
  2505. {
  2506. throw new NotImplementedException();
  2507. }
  2508. /**
  2509. * See the yii documentation.
  2510. */
  2511. public function offsetUnset($offset)
  2512. {
  2513. throw new NotImplementedException();
  2514. }
  2515. /**
  2516. * Creates an instance of the extending model wrapping the given
  2517. * bean. For use only by models. Beans are never used by the
  2518. * application directly.
  2519. * @param $bean A <a href="http://www.redbeanphp.com/">RedBean</a>
  2520. * bean.
  2521. * @param $modelClassName Pass only when getting it at runtime
  2522. * gets the wrong name.
  2523. * @return An instance of the type of the extending model.
  2524. */
  2525. public static function makeModel(RedBean_OODBBean $bean, $modelClassName = null, $forceTreatAsCreation = false)
  2526. {
  2527. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  2528. if ($modelClassName === null)
  2529. {
  2530. $modelClassName = get_called_class();
  2531. }
  2532. $modelIdentifier = $modelClassName . strval($bean->id);
  2533. try
  2534. {
  2535. $model = RedBeanModelsCache::getModel($modelIdentifier);
  2536. $model->constructIncomplete($bean, false);
  2537. return $model;
  2538. }
  2539. catch (NotFoundException $e)
  2540. {
  2541. return new $modelClassName(true, $bean, $forceTreatAsCreation);
  2542. }
  2543. }
  2544. /**
  2545. * Creates an array of instances of the named model type wrapping the
  2546. * given beans. For use only by models. Beans are never used by the
  2547. * application directly.
  2548. * @param $beans An array of <a href="http://www.redbeanphp.com/">RedBean</a>
  2549. * beans.
  2550. * @param $modelClassName Pass only when getting it at runtime
  2551. * gets the wrong name.
  2552. * @return An array of instances of the type of the extending model.
  2553. */
  2554. public static function makeModels(array $beans, $modelClassName = null)
  2555. {
  2556. if ($modelClassName === null)
  2557. {
  2558. $modelClassName = get_called_class();
  2559. }
  2560. $models = array();
  2561. foreach ($beans as $bean)
  2562. {
  2563. assert('$bean instanceof RedBean_OODBBean');
  2564. try
  2565. {
  2566. $models[] = self::makeModel($bean, $modelClassName);
  2567. }
  2568. catch (MissingBeanException $e)
  2569. {
  2570. }
  2571. }
  2572. return $models;
  2573. }
  2574. /**
  2575. * Given an array of data, create stringified content.
  2576. * @param array $values
  2577. */
  2578. public function stringifyOneToManyRelatedModelsValues($values)
  2579. {
  2580. assert('is_array($values)');
  2581. return ArrayUtil::stringify($values);
  2582. }
  2583. }
  2584. ?>