PageRenderTime 154ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

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

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