PageRenderTime 98ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

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

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