PageRenderTime 136ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 1ms

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

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