PageRenderTime 141ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 1ms

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

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