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

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

https://bitbucket.org/codevarun/zurmo-invoice-example
PHP | 2717 lines | 1960 code | 132 blank | 625 comment | 237 complexity | e7cb68e51e05e9537a4d56521d1cd4c2 MD5 | raw file
Possible License(s): GPL-3.0, BSD-3-Clause, LGPL-2.1, BSD-2-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*********************************************************************************
  3. * Zurmo is a customer relationship management program developed by
  4. * Zurmo, Inc. Copyright (C) 2012 Zurmo Inc.
  5. *
  6. * Zurmo is free software; you can redistribute it and/or modify it under
  7. * the terms of the GNU General Public License version 3 as published by the
  8. * Free Software Foundation with the addition of the following permission added
  9. * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
  10. * IN WHICH THE COPYRIGHT IS OWNED BY ZURMO, ZURMO DISCLAIMS THE WARRANTY
  11. * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
  12. *
  13. * Zurmo is distributed in the hope that it will be useful, but WITHOUT
  14. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  15. * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  16. * details.
  17. *
  18. * You should have received a copy of the GNU General Public License along with
  19. * this program; if not, see http://www.gnu.org/licenses or write to the Free
  20. * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  21. * 02110-1301 USA.
  22. *
  23. * You can contact Zurmo, Inc. with a mailing address at 113 McHenry Road Suite 207,
  24. * Buffalo Grove, IL 60089, USA. or at email address contact@zurmo.com.
  25. ********************************************************************************/
  26. $basePath = Yii::app()->getBasePath();
  27. require_once("$basePath/../../redbean/rb.php");
  28. /**
  29. * Abstraction over the top of an application database accessed via
  30. * <a href="http://www.redbeanphp.com/">RedBean</a>. The base class for
  31. * an MVC model. Replaces the M part of MVC in Yii. Yii maps from the
  32. * database scheme to the objects, (good for database guys, not so good
  33. * for OO guys), this maps from objects to the database schema.
  34. *
  35. * A domain model is created by extending RedBeanModel and supplying
  36. * a getDefaultMetadata() method.
  37. *
  38. * Static getXxxx() methods can be supplied to query for the given domain
  39. * models, and instance methods should supply additional behaviour.
  40. *
  41. * getDefaultMetadata() returns an array of the class name mapped to
  42. * an array containing 'members' mapped to an array of member names,
  43. * (to be accessed as $model->memberName).
  44. *
  45. * It can then optionally have, 'relations' mapped
  46. * to an array of relation names, (to be accessed as $model->relationName),
  47. * mapped to its type, (the extending model class to which it relates).
  48. *
  49. * And it can then optionally have as well, 'rules' mapped to an array of
  50. * attribute names, (attributes are members and relations), a validator name,
  51. * and the parameters to the validator, if any, as per the Yii::CModel::rules()
  52. * method.See http://www.yiiframework.com/wiki/56/reference-model-rules-validation.
  53. *
  54. * These are used to automatically and dynamically create the database
  55. * schema on the fly as opposed to Yii's getting attributes from an
  56. * already existing schema.
  57. */
  58. abstract class RedBeanModel extends CComponent implements Serializable
  59. {
  60. // Models that have not been saved yet have no id as far
  61. // as the database is concerned. Until they are saved they are
  62. // assigned a negative id, so that they have identity.
  63. private static $nextPseudoId = -1;
  64. // The id of an unsaved model.
  65. private $pseudoId;
  66. // A model maps to one or more beans. If Person extends RedBeanModel
  67. // there is one bean, but if User then extends Person a User model
  68. // has two beans, the one holding the person data and the one holding
  69. // the extended User data. In this way in inheritance hierarchy from
  70. // model is normalized over several tables, one for each extending
  71. // class.
  72. private $modelClassNameToBean = array();
  73. private $attributeNameToBeanAndClassName = array();
  74. private $attributeNamesNotBelongsToOrManyMany = array();
  75. private $relationNameToRelationTypeModelClassNameAndOwns = array();
  76. private $relationNameToRelatedModel = array();
  77. private $unlinkedRelationNames = array();
  78. private $validators = array();
  79. private $attributeNameToErrors = array();
  80. private $scenarioName = '';
  81. // An object is automatcally savable if it is new or contains
  82. // modified members or related objects.
  83. // If it is newly created and has never had any data put into it
  84. // it can be saved explicitly but it wont be saved automatically
  85. // when it is a related model and will be redispensed next
  86. // time it is referenced.
  87. protected $modified = false;
  88. protected $deleted = false;
  89. protected $isInIsModified = false;
  90. protected $isInHasErrors = false;
  91. protected $isInGetErrors = false;
  92. protected $isValidating = false;
  93. protected $isSaving = false;
  94. // Mapping of Yii validators to validators doing things that
  95. // are either required for RedBean, or that simply implement
  96. // The semantics that we want.
  97. private static $yiiValidatorsToRedBeanValidators = array(
  98. 'CDefaultValueValidator' => 'RedBeanModelDefaultValueValidator',
  99. 'CNumberValidator' => 'RedBeanModelNumberValidator',
  100. 'CTypeValidator' => 'RedBeanModelTypeValidator',
  101. 'CRequiredValidator' => 'RedBeanModelRequiredValidator',
  102. 'CUniqueValidator' => 'RedBeanModelUniqueValidator',
  103. 'defaultCalculatedDate' => 'RedBeanModelDefaultCalculatedDateValidator',
  104. 'readOnly' => 'RedBeanModelReadOnlyValidator',
  105. 'dateTimeDefault' => 'RedBeanModelDateTimeDefaultValueValidator',
  106. );
  107. /**
  108. * Used in an extending class's getDefaultMetadata() method to specify
  109. * that a relation is 1:1 and that the class on the 1 side of the
  110. * relation.
  111. */
  112. const HAS_ONE_BELONGS_TO = 0;
  113. /**
  114. * Used in an extending class's getDefaultMetadata() method to specify
  115. * that a relation is 1:M and that the class on the M side of the
  116. * relation.
  117. * Note: Currently if you have a relation that is set to HAS_MANY_BELONGS_TO, then that relation name
  118. * must be the strtolower() same as the related model class name. This is the current support for this
  119. * relation type. If something different is set, an exception will be thrown.
  120. */
  121. const HAS_MANY_BELONGS_TO = 1;
  122. /**
  123. * Used in an extending class's getDefaultMetadata() method to specify
  124. * that a relation is 1:1.
  125. */
  126. const HAS_ONE = 2;
  127. /**
  128. * Used in an extending class's getDefaultMetadata() method to specify
  129. * that a relation is 1:M and that the class is on the 1 side of the
  130. * relation.
  131. */
  132. const HAS_MANY = 3;
  133. /**
  134. * Used in an extending class's getDefaultMetadata() method to specify
  135. * that a relation is M:N and that the class on the either side of the
  136. * relation.
  137. */
  138. const MANY_MANY = 4;
  139. /**
  140. * Used in an extending class's getDefaultMetadata() method to specify
  141. * that a 1:1 or 1:M relation is one in which the left side of the relation
  142. * owns the model or models on the right side, meaning that if the model
  143. * is deleted it owns the related models and they are deleted along with it.
  144. * If not specified the related model is independent and is not deleted.
  145. */
  146. const OWNED = true;
  147. /**
  148. * Gets all the models from the database of the named model type.
  149. * @param $orderBy TODO
  150. * @param $modelClassName Pass only when getting it at runtime
  151. * gets the wrong name.
  152. * @return An array of models of the type of the extending model.
  153. */
  154. public static function getAll($orderBy = null, $sortDescending = false, $modelClassName = null)
  155. {
  156. assert('$orderBy === null || is_string($orderBy) && $orderBy != ""');
  157. assert('is_bool($sortDescending)');
  158. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  159. $quote = DatabaseCompatibilityUtil::getQuote();
  160. $orderBySql = null;
  161. if ($orderBy !== null)
  162. {
  163. $orderBySql = "$quote$orderBy$quote";
  164. if ($sortDescending)
  165. {
  166. $orderBySql .= ' desc';
  167. }
  168. }
  169. return static::getSubset(null, null, null, null, $orderBySql, $modelClassName);
  170. }
  171. /**
  172. * Gets a range of models from the database of the named model type.
  173. * @param $modelClassName
  174. * @param $joinTablesAdapter null or instance of joinTablesAdapter.
  175. * @param $offset The zero based index of the first model to be returned.
  176. * @param $count The number of models to be returned.
  177. * @param $where
  178. * @param $orderBy - sql string. Example 'a desc' or 'a.b desc'. Currently only supports non-related attributes
  179. * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
  180. * @return An array of models of the type of the extending model.
  181. */
  182. public static function getSubset(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
  183. $offset = null, $count = null,
  184. $where = null, $orderBy = null,
  185. $modelClassName = null,
  186. $selectDistinct = false)
  187. {
  188. assert('$offset === null || is_integer($offset) && $offset >= 0');
  189. assert('$count === null || is_integer($count) && $count >= 1');
  190. assert('$where === null || is_string ($where) && $where != ""');
  191. assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
  192. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  193. if ($modelClassName === null)
  194. {
  195. $modelClassName = get_called_class();
  196. }
  197. if ($joinTablesAdapter == null)
  198. {
  199. $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
  200. }
  201. $tableName = self::getTableName($modelClassName);
  202. $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, $offset, $count, $where,
  203. $orderBy, false, $selectDistinct);
  204. $ids = R::getCol($sql);
  205. $tableName = self::getTableName($modelClassName);
  206. $beans = R::batch ($tableName, $ids);
  207. return self::makeModels($beans, $modelClassName);
  208. }
  209. /**
  210. * @param boolean $selectCount If true then make this a count query. If false, select ids from rows.
  211. * @param array $quotedExtraSelectColumnNameAndAliases - extra columns to select.
  212. * @return string - sql statement.
  213. */
  214. public static function makeSubsetOrCountSqlQuery($tableName,
  215. RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter,
  216. $offset = null, $count = null,
  217. $where = null, $orderBy = null,
  218. $selectCount = false,
  219. $selectDistinct = false,
  220. array $quotedExtraSelectColumnNameAndAliases = array())
  221. {
  222. assert('is_string($tableName) && $tableName != ""');
  223. assert('$offset === null || is_integer($offset) && $offset >= 0');
  224. assert('$count === null || is_integer($count) && $count >= 1');
  225. assert('$where === null || is_string ($where) && $where != ""');
  226. assert('$orderBy === null || is_string ($orderBy) && $orderBy != ""');
  227. assert('is_bool($selectCount)');
  228. assert('is_bool($selectDistinct)');
  229. $selectQueryAdapter = new RedBeanModelSelectQueryAdapter($selectDistinct);
  230. if ($selectCount)
  231. {
  232. $selectQueryAdapter->addCountClause($tableName);
  233. }
  234. else
  235. {
  236. $selectQueryAdapter->addClause($tableName, 'id', 'id');
  237. }
  238. foreach ($quotedExtraSelectColumnNameAndAliases as $columnName => $columnAlias)
  239. {
  240. $selectQueryAdapter->addClauseWithColumnNameOnlyAndNoEnclosure($columnName, $columnAlias);
  241. }
  242. return SQLQueryUtil::
  243. makeQuery($tableName, $selectQueryAdapter, $joinTablesAdapter, $offset, $count, $where, $orderBy);
  244. }
  245. /**
  246. * @param $modelClassName
  247. * @param $joinTablesAdapter null or instance of joinTablesAdapter.
  248. * @param $modelClassName Pass only when getting it at runtime gets the wrong name.
  249. */
  250. public static function getCount(RedBeanModelJoinTablesQueryAdapter $joinTablesAdapter = null,
  251. $where = null, $modelClassName = null, $selectDistinct = false)
  252. {
  253. assert('$where === null || is_string($where)');
  254. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  255. if ($modelClassName === null)
  256. {
  257. $modelClassName = get_called_class();
  258. }
  259. if ($joinTablesAdapter == null)
  260. {
  261. $joinTablesAdapter = new RedBeanModelJoinTablesQueryAdapter($modelClassName);
  262. }
  263. $tableName = self::getTableName($modelClassName);
  264. $sql = static::makeSubsetOrCountSqlQuery($tableName, $joinTablesAdapter, null, null, $where, null, true,
  265. $selectDistinct);
  266. $count = R::getCell($sql);
  267. if ($count === null)
  268. {
  269. $count = 0;
  270. }
  271. return $count;
  272. }
  273. /**
  274. * Gets a model from the database by Id.
  275. * @param $id Integer Id.
  276. * @param $modelClassName Pass only when getting it at runtime
  277. * gets the wrong name.
  278. * @return A model of the type of the extending model.
  279. */
  280. public static function getById($id, $modelClassName = null)
  281. {
  282. assert('is_integer($id) && $id > 0');
  283. assert('$modelClassName === null || is_string($modelClassName) && $modelClassName != ""');
  284. // I would have thought it was correct to user R::load() and get
  285. // a null, or error or something if the bean doesn't exist, but
  286. // it still returns a bean. So until I've investigated further
  287. // I'm using Finder.
  288. if ($modelClassName === null)
  289. {
  290. $modelClassName = get_called_class();
  291. }
  292. $tableName = self::getTableName($modelClassName);
  293. $beans = RedBean_Plugin_Finder::where($tableName, "id = '$id'");
  294. assert('count($beans) <= 1');
  295. if (count($beans) == 0)
  296. {
  297. throw new NotFoundException();
  298. }
  299. return RedBeanModel::makeModel(end($beans), $modelClassName);
  300. }
  301. /**
  302. * Constructs a new model.
  303. * Important:
  304. * Models are only constructed with beans by the RedBeanModel. Beans are
  305. * never used by the application directly.
  306. * The application can construct a new model object by constructing a
  307. * model without specifying a bean. In other words, if Php had
  308. * overloading a constructor with $setDefaults would be public, and
  309. * a constructor taking a $bean and $forceTreatAsCreation would be private.
  310. * @param $setDefaults. If false the default validators will not be run
  311. * on construction. The Yii way is that defaults are
  312. * filled in after the fact, which is counter the usual
  313. * for objects.
  314. * @param $bean A bean. Never specified by an application.
  315. * @param $forceTreatAsCreation. Never specified by an application.
  316. * @see getById()
  317. * @see makeModel()
  318. * @see makeModels()
  319. */
  320. public function __construct($setDefaults = true, RedBean_OODBBean $bean = null, $forceTreatAsCreation = false)
  321. {
  322. $this->pseudoId = self::$nextPseudoId--;
  323. if ($bean === null)
  324. {
  325. foreach (array_reverse(RuntimeUtil::getClassHierarchy(get_class($this), 'RedBeanModel')) as $modelClassName)
  326. {
  327. $tableName = self::getTableName($modelClassName);
  328. $newBean = R::dispense($tableName);
  329. $this->modelClassNameToBean[$modelClassName] = $newBean;
  330. $this->mapAndCacheMetadataAndSetHints($modelClassName, $newBean);
  331. }
  332. // The yii way of doing defaults is the the default validator
  333. // fills in the defaults on attributes that don't have values
  334. // when you validator, or save. This weird, since when you get
  335. // a model the things with defaults have not been defaulted!
  336. // We want that semantic.
  337. if ($setDefaults)
  338. {
  339. $this->runDefaultValidators();
  340. }
  341. $forceTreatAsCreation = true;
  342. }
  343. else
  344. {
  345. assert('$bean->id > 0');
  346. $first = true;
  347. foreach (RuntimeUtil::getClassHierarchy(get_class($this), 'RedBeanModel') as $modelClassName)
  348. {
  349. if ($first)
  350. {
  351. $lastBean = $bean;
  352. $first = false;
  353. }
  354. else
  355. {
  356. $tableName = self::getTableName($modelClassName);
  357. $lastBean = R::getBean($lastBean, $tableName);
  358. if ($lastBean === null)
  359. {
  360. throw new MissingBeanException();
  361. }
  362. assert('$lastBean->id > 0');
  363. }
  364. $this->modelClassNameToBean[$modelClassName] = $lastBean;
  365. $this->mapAndCacheMetadataAndSetHints($modelClassName, $lastBean);
  366. }
  367. $this->modelClassNameToBean = array_reverse($this->modelClassNameToBean);
  368. }
  369. $this->constructDerived($bean, $setDefaults);
  370. if ($forceTreatAsCreation)
  371. {
  372. $this->onCreated();
  373. }
  374. else
  375. {
  376. $this->onLoaded();
  377. RedBeanModelsCache::cacheModel($this);
  378. }
  379. $this->modified = false;
  380. }
  381. // Derived classes can insert additional steps into the construction.
  382. protected function constructDerived($bean, $setDefaults)
  383. {
  384. assert('$bean === null || $bean instanceof RedBean_OODBBean');
  385. assert('is_bool($setDefaults)');
  386. }
  387. /**
  388. * Utilized when pieces of information need to be constructed on an existing model, that can potentially be
  389. * missing. For example, if a model is created, then a custom field is added, it is possible the cached model
  390. * is missing the custom field customFieldData.
  391. * @param unknown_type $bean
  392. */
  393. protected function constructIncomplete($bean)
  394. {
  395. assert('$bean === null || $bean instanceof RedBean_OODBBean');
  396. }
  397. public function serialize()
  398. {
  399. return serialize(array(
  400. $this->pseudoId,
  401. $this->modelClassNameToBean,
  402. $this->attributeNameToBeanAndClassName,
  403. $this->attributeNamesNotBelongsToOrManyMany,
  404. $this->relationNameToRelationTypeModelClassNameAndOwns,
  405. $this->validators,
  406. ));
  407. }
  408. public function unserialize($data)
  409. {
  410. try
  411. {
  412. $data = unserialize($data);
  413. assert('is_array($data)');
  414. if (count($data) != 6)
  415. {
  416. return null;
  417. }
  418. $this->pseudoId = $data[0];
  419. $this->modelClassNameToBean = $data[1];
  420. $this->attributeNameToBeanAndClassName = $data[2];
  421. $this->attributeNamesNotBelongsToOrManyMany = $data[3];
  422. $this->relationNameToRelationTypeModelClassNameAndOwns = $data[4];
  423. $this->validators = $data[5];
  424. $this->relationNameToRelatedModel = array();
  425. $this->unlinkedRelationNames = array();
  426. $this->attributeNameToErrors = array();
  427. $this->scenarioName = '';
  428. $this->modified = false;
  429. $this->deleted = false;
  430. $this->isInIsModified = false;
  431. $this->isInHasErrors = false;
  432. $this->isInGetErrors = false;
  433. $this->isValidating = false;
  434. $this->isSaving = false;
  435. }
  436. catch (Exception $e)
  437. {
  438. return null;
  439. }
  440. }
  441. /**
  442. * Overriding constructors must call this function to ensure that
  443. * they leave the newly constructed instance not modified since
  444. * anything modifying the class during constructionm will set it
  445. * modified automatically.
  446. */
  447. protected function setNotModified()
  448. {
  449. $this->modified = false; // This sets this class to the right state.
  450. assert('!$this->isModified()'); // This tests that related classes are in the right state.
  451. }
  452. /**
  453. * By default the table name is the lowercased class name. If this
  454. * conflicts with a database keyword override to return true.
  455. * RedBean does not quote table names in most cases.
  456. */
  457. // Public for unit testing.
  458. public static function mangleTableName()
  459. {
  460. return false;
  461. }
  462. /**
  463. * Returns the table name for a class.
  464. * For use by RedBeanModelDataProvider. It will not
  465. * be of any use to an application. Applications
  466. * should not be doing anything table related.
  467. * Derived classes can refer directly to the
  468. * table name.
  469. */
  470. public static function getTableName($modelClassName)
  471. {
  472. assert('is_string($modelClassName) && $modelClassName != ""');
  473. $tableName = strtolower($modelClassName);
  474. if ($modelClassName::mangleTableName())
  475. {
  476. $tableName = '_' . $tableName;
  477. }
  478. return $tableName;
  479. }
  480. /**
  481. * Returns the table names for an array of classes.
  482. * For use by RedBeanModelDataProvider. It will not
  483. * be of any use to an application.
  484. */
  485. public static function getTableNames($classNames)
  486. {
  487. $tableNames = array();
  488. foreach ($classNames as $className)
  489. {
  490. $tableNames[] = self::getTableName($className);
  491. }
  492. return $tableNames;
  493. }
  494. /**
  495. * Used by classes such as containers which use sql to
  496. * optimize getting models from the database.
  497. */
  498. public static function getForeignKeyName($modelClassName, $relationName)
  499. {
  500. assert('is_string($modelClassName)');
  501. assert('$modelClassName != ""');
  502. $metadata = $modelClassName::getMetadata();
  503. foreach ($metadata as $modelClassName => $modelClassMetadata)
  504. {
  505. if (isset($metadata[$modelClassName]["relations"]) &&
  506. array_key_exists($relationName, $metadata[$modelClassName]["relations"]))
  507. {
  508. $relatedModelClassName = $metadata[$modelClassName]['relations'][$relationName][1];
  509. $relatedModelTableName = self::getTableName($relatedModelClassName);
  510. $columnName = '';
  511. if (strtolower($relationName) != strtolower($relatedModelClassName))
  512. {
  513. $columnName = strtolower($relationName) . '_';
  514. }
  515. $columnName .= $relatedModelTableName . '_id';
  516. return $columnName;
  517. }
  518. }
  519. throw new NotSupportedException;
  520. }
  521. /**
  522. * Called on construction when a new model is created.
  523. */
  524. protected function onCreated()
  525. {
  526. }
  527. /**
  528. * Called on construction when a model is loaded.
  529. */
  530. protected function onLoaded()
  531. {
  532. }
  533. /**
  534. * Called when a model is modified.
  535. */
  536. protected function onModified()
  537. {
  538. }
  539. /**
  540. * Used for mixins.
  541. */
  542. protected function mapAndCacheMetadataAndSetHints($modelClassName, RedBean_OODBBean $bean)
  543. {
  544. assert('is_string($modelClassName)');
  545. assert('$modelClassName != ""');
  546. $metadata = $this->getMetadata();
  547. if (isset($metadata[$modelClassName]))
  548. {
  549. $hints = array();
  550. if (isset($metadata[$modelClassName]['members']))
  551. {
  552. foreach ($metadata[$modelClassName]['members'] as $memberName)
  553. {
  554. $this->attributeNameToBeanAndClassName[$memberName] = array($bean, $modelClassName);
  555. $this->attributeNamesNotBelongsToOrManyMany[] = $memberName;
  556. if (substr($memberName, -2) == 'Id')
  557. {
  558. $columnName = strtolower($memberName);
  559. $hints[$columnName] = 'id';
  560. }
  561. }
  562. }
  563. if (isset($metadata[$modelClassName]['relations']))
  564. {
  565. foreach ($metadata[$modelClassName]['relations'] as $relationName => $relationTypeModelClassNameAndOwns)
  566. {
  567. assert('in_array(count($relationTypeModelClassNameAndOwns), array(2, 3))');
  568. $relationType = $relationTypeModelClassNameAndOwns[0];
  569. $relationModelClassName = $relationTypeModelClassNameAndOwns[1];
  570. if ($relationType == self::HAS_MANY_BELONGS_TO &&
  571. strtolower($relationName) != strtolower($relationModelClassName))
  572. {
  573. $label = 'Relations of type HAS_MANY_BELONGS_TO must have the relation name ' .
  574. 'the same as the related model class name. Relation: {relationName} ' .
  575. 'Relation model class name: {relationModelClassName}';
  576. throw new NotSupportedException(Yii::t('Default', $label,
  577. array('{relationName}' => $relationName,
  578. '{relationModelClassName}' => $relationModelClassName)));
  579. }
  580. if (count($relationTypeModelClassNameAndOwns) == 3)
  581. {
  582. $relationTypeModelClassNameAndOwns[2] == self::OWNED;
  583. $owns = true;
  584. }
  585. else
  586. {
  587. $owns = false;
  588. }
  589. assert('in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, ' .
  590. 'self::HAS_ONE, self::HAS_MANY, self::MANY_MANY))');
  591. $this->attributeNameToBeanAndClassName[$relationName] = array($bean, $modelClassName);
  592. $this->relationNameToRelationTypeModelClassNameAndOwns[$relationName] = array($relationType, $relationModelClassName, $owns);
  593. if (!in_array($relationType, array(self::HAS_ONE_BELONGS_TO, self::HAS_MANY_BELONGS_TO, self::MANY_MANY)))
  594. {
  595. $this->attributeNamesNotBelongsToOrManyMany[] = $relationName;
  596. }
  597. }
  598. }
  599. if (isset($metadata[$modelClassName]['rules']))
  600. {
  601. foreach ($metadata[$modelClassName]['rules'] as $validatorMetadata)
  602. {
  603. assert('isset($validatorMetadata[0])');
  604. assert('isset($validatorMetadata[1])');
  605. $attributeName = $validatorMetadata[0];
  606. // Each rule in RedBeanModel must specify one attribute name.
  607. // This was just better style, now it is mandatory.
  608. assert('strpos($attributeName, " ") === false');
  609. $validatorName = $validatorMetadata[1];
  610. $validatorParameters = array_slice($validatorMetadata, 2);
  611. if (isset(CValidator::$builtInValidators[$validatorName]))
  612. {
  613. $validatorName = CValidator::$builtInValidators[$validatorName];
  614. }
  615. if (isset(self::$yiiValidatorsToRedBeanValidators[$validatorName]))
  616. {
  617. $validatorName = self::$yiiValidatorsToRedBeanValidators[$validatorName];
  618. }
  619. $validator = CValidator::createValidator($validatorName, $this, $attributeName, $validatorParameters);
  620. switch ($validatorName)
  621. {
  622. case 'RedBeanModelTypeValidator':
  623. case 'TypeValidator':
  624. $columnName = strtolower($attributeName);
  625. if (array_key_exists($columnName, $hints))
  626. {
  627. unset($hints[$columnName]);
  628. }
  629. if (in_array($validator->type, array('date', 'datetime', 'blob', 'longblob')))
  630. {
  631. $hints[$columnName] = $validator->type;
  632. }
  633. break;
  634. case 'CBooleanValidator':
  635. $columnName = strtolower($attributeName);
  636. $hints[$columnName] = 'boolean';
  637. break;
  638. case 'RedBeanModelUniqueValidator':
  639. if (!$this->isRelation($attributeName))
  640. {
  641. $bean->setMeta("buildcommand.unique", array(array($attributeName)));
  642. }
  643. else
  644. {
  645. $relatedModelClassName = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName][1];
  646. $relatedModelTableName = self::getTableName($relatedModelClassName);
  647. $columnName = strtolower($attributeName);
  648. if ($columnName != $relatedModelTableName)
  649. {
  650. $columnName .= '_' . $relatedModelTableName;
  651. }
  652. $columnName .= '_id';
  653. $bean->setMeta("buildcommand.unique", array(array($columnName)));
  654. }
  655. break;
  656. }
  657. $this->validators[] = $validator;
  658. }
  659. }
  660. $bean->setMeta('hint', $hints);
  661. }
  662. }
  663. /**
  664. * Used for mixins.
  665. */
  666. protected function runDefaultValidators()
  667. {
  668. foreach ($this->validators as $validator)
  669. {
  670. if ($validator instanceof CDefaultValueValidator)
  671. {
  672. $validator->validate($this);
  673. }
  674. }
  675. }
  676. /**
  677. * For use only by RedBeanModel and RedBeanModels. Beans are
  678. * never used by the application directly.
  679. */
  680. public function getPrimaryBean()
  681. {
  682. return end($this->modelClassNameToBean);
  683. }
  684. /**
  685. * Used for optimization.
  686. */
  687. public function getClassId($modelClassName)
  688. {
  689. assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
  690. return intval($this->getClassBean($modelClassName)->id); // Trying to combat the slop.
  691. }
  692. public function getClassBean($modelClassName)
  693. {
  694. assert('is_string($modelClassName)');
  695. assert('$modelClassName != ""');
  696. assert('array_key_exists($modelClassName, $this->modelClassNameToBean)');
  697. return $this->modelClassNameToBean[$modelClassName];
  698. }
  699. /**
  700. * Used for mixins.
  701. */
  702. protected function setClassBean($modelClassName, RedBean_OODBBean $bean)
  703. {
  704. assert('is_string($modelClassName)');
  705. assert('$modelClassName != ""');
  706. assert('!array_key_exists($modelClassName, $this->modelClassNameToBean)');
  707. $this->modelClassNameToBean = array_merge(array($modelClassName => $bean),
  708. $this->modelClassNameToBean);
  709. }
  710. public function getModelIdentifier()
  711. {
  712. return get_class($this) . strval($this->getPrimaryBean()->id);
  713. }
  714. /**
  715. * Returns metadata for the model. Attempts to cache metadata, if it is not already cached.
  716. * @see getDefaultMetadata()
  717. * @returns An array of metadata.
  718. */
  719. public static function getMetadata()
  720. {
  721. try
  722. {
  723. return GeneralCache::getEntry(get_called_class() . 'Metadata');
  724. }
  725. catch (NotFoundException $e)
  726. {
  727. $className = get_called_Class();
  728. $defaultMetadata = $className::getDefaultMetadata();
  729. $metadata = array();
  730. foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, 'RedBeanModel')) as $modelClassName)
  731. {
  732. if ($modelClassName::canSaveMetadata())
  733. {
  734. try
  735. {
  736. $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
  737. $metadata[$modelClassName] = unserialize($globalMetadata->serializedMetadata);
  738. }
  739. catch (NotFoundException $e)
  740. {
  741. if (isset($defaultMetadata[$modelClassName]))
  742. {
  743. $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
  744. }
  745. }
  746. }
  747. else
  748. {
  749. if (isset($defaultMetadata[$modelClassName]))
  750. {
  751. $metadata[$modelClassName] = $defaultMetadata[$modelClassName];
  752. }
  753. }
  754. }
  755. if (YII_DEBUG)
  756. {
  757. self::assertMetadataIsValid($metadata);
  758. }
  759. GeneralCache::cacheEntry(get_called_class() . 'Metadata', $metadata);
  760. return $metadata;
  761. }
  762. }
  763. /**
  764. * By default models cannot save their metadata, allowing
  765. * them to be loaded quickly because the loading of of
  766. * metadata can be avoided as much as possible.
  767. * To make a model able to save its metadata override
  768. * this method to return true. PUT it before the
  769. * getDefaultMetadata in the derived class.
  770. */
  771. public static function canSaveMetadata()
  772. {
  773. return false;
  774. }
  775. /**
  776. * Sets metadata for the model.
  777. * @see getDefaultMetadata()
  778. * @returns An array of metadata.
  779. */
  780. public static function setMetadata(array $metadata)
  781. {
  782. if (YII_DEBUG)
  783. {
  784. self::assertMetadataIsValid($metadata);
  785. }
  786. $className = get_called_class();
  787. foreach (array_reverse(RuntimeUtil::getClassHierarchy($className, 'RedBeanModel')) as $modelClassName)
  788. {
  789. if ($modelClassName::canSaveMetadata())
  790. {
  791. if (isset($metadata[$modelClassName]))
  792. {
  793. try
  794. {
  795. $globalMetadata = GlobalMetadata::getByClassName($modelClassName);
  796. }
  797. catch (NotFoundException $e)
  798. {
  799. $globalMetadata = new GlobalMetadata();
  800. $globalMetadata->className = $modelClassName;
  801. }
  802. $globalMetadata->serializedMetadata = serialize($metadata[$modelClassName]);
  803. $saved = $globalMetadata->save();
  804. // TODO: decide how to deal with this properly if it fails.
  805. // ie: throw or return false, or something other than
  806. // this naughty assert.
  807. assert('$saved');
  808. }
  809. }
  810. }
  811. RedBeanModelsCache::forgetAllByModelType(get_called_class());
  812. GeneralCache::forgetEntry(get_called_class() . 'Metadata');
  813. }
  814. /**
  815. * Returns the default meta data for the class.
  816. * It must be appended to the meta data
  817. * from the parent model, if any.
  818. */
  819. public static function getDefaultMetadata()
  820. {
  821. return array();
  822. }
  823. protected static function assertMetadataIsValid(array $metadata)
  824. {
  825. $className = get_called_Class();
  826. foreach (RuntimeUtil::getClassHierarchy($className, 'RedBeanModel') as $modelClassName)
  827. {
  828. if (isset($metadata[$modelClassName]['members']))
  829. {
  830. assert('is_array($metadata[$modelClassName]["members"])');
  831. foreach ($metadata[$modelClassName]["members"] as $memberName)
  832. {
  833. assert('ctype_lower($memberName{0})');
  834. }
  835. }
  836. if (isset($metadata[$modelClassName]['relations']))
  837. {
  838. assert('is_array($metadata[$modelClassName]["relations"])');
  839. foreach ($metadata[$modelClassName]["relations"] as $relationName => $notUsed)
  840. {
  841. assert('ctype_lower($relationName{0})');
  842. }
  843. }
  844. if (isset($metadata[$modelClassName]['rules']))
  845. {
  846. assert('is_array($metadata[$modelClassName]["rules"])');
  847. }
  848. if (isset($metadata[$modelClassName]['defaultSortAttribute']))
  849. {
  850. assert('is_string($metadata[$modelClassName]["defaultSortAttribute"])');
  851. }
  852. if (isset($metadata[$modelClassName]['rollupRelations']))
  853. {
  854. assert('is_array($metadata[$modelClassName]["rollupRelations"])');
  855. }
  856. // Todo: add more rules here as I think of them.
  857. }
  858. }
  859. /**
  860. * Downcasting in general is a bad concept, but when pulling
  861. * a Person from the database it would require a lot of
  862. * jumping through hoops to make the RedBeanModel automatically
  863. * figure out if that person is really a User, Contact, Customer
  864. * or whatever might be derived from Person. So to avoid that
  865. * complication and performance hit where it is not necessary
  866. * this method can be used to convert a model to one of
  867. * a given set of derivatives. If model is not one
  868. * of those NotFoundException is thrown.
  869. */
  870. public function castDown(array $derivedModelClassNames)
  871. {
  872. $bean = $this->getPrimaryBean();
  873. $thisModelClassName = get_called_class();
  874. $key = strtolower($thisModelClassName) . '_id';
  875. foreach ($derivedModelClassNames as $modelClassNames)
  876. {
  877. if (is_string($modelClassNames))
  878. {
  879. $nextModelClassName = $modelClassNames;
  880. if (get_class($this) == $nextModelClassName)
  881. {
  882. return $this;
  883. }
  884. $nextBean = self::findNextDerivativeBean($bean, $thisModelClassName, $nextModelClassName);
  885. }
  886. else
  887. {
  888. assert('is_array($modelClassNames)');
  889. $targetModelClassName = end($modelClassNames);
  890. if (get_class($this) == $targetModelClassName)
  891. {
  892. return $this;
  893. }
  894. $currentModelClassName = $thisModelClassName;
  895. $nextBean = $bean;
  896. foreach ($modelClassNames as $nextModelClassName)
  897. {
  898. $nextBean = self::findNextDerivativeBean($nextBean, $currentModelClassName, $nextModelClassName);
  899. if ($nextBean === null)
  900. {
  901. break;
  902. }
  903. $currentModelClassName = $nextModelClassName;
  904. }
  905. }
  906. if ($nextBean !== null)
  907. {
  908. return self::makeModel($nextBean, $nextModelClassName);
  909. }
  910. }
  911. throw new NotFoundException();
  912. }
  913. private static function findNextDerivativeBean($bean, $modelClassName1, $modelClassName2)
  914. {
  915. $key = strtolower($modelClassName1) . '_id';
  916. $tableName = self::getTableName($modelClassName2);
  917. $beans = R::find($tableName, "$key = :id", array('id' => $bean->id));
  918. if (count($beans) == 1)
  919. {
  920. return reset($beans);
  921. }
  922. return null;
  923. }
  924. /**
  925. * Returns whether the given object is of the same type with the
  926. * same id.
  927. */
  928. public function isSame(RedBeanModel $model)
  929. {
  930. // The two models are the same if they have the
  931. // same root model, and if for that model they
  932. // have the same id.
  933. $rootId1 = reset($this ->modelClassNameToBean)->id;
  934. $rootId2 = reset($model->modelClassNameToBean)->id;
  935. if ($rootId1 == 0)
  936. {
  937. $rootId1 = $this->pseudoId;
  938. }
  939. if ($rootId2 == 0)
  940. {
  941. $rootId2 = $model->pseudoId;
  942. }
  943. return $rootId1 == $rootId2 && $rootId1 != 0 &&
  944. key($this ->modelClassNameToBean) ==
  945. key($model->modelClassNameToBean);
  946. }
  947. /**
  948. * Returns the displayable string for the class. Should be
  949. * overridden in any model that can provide a meaningful string
  950. * representation of itself.
  951. * @return A string.
  952. */
  953. public function __toString()
  954. {
  955. return Yii::t('Default', '(None)');
  956. }
  957. /**
  958. * Exposes the members and relations of the model as if
  959. * they were actual attributes of the model. See __set().
  960. * @param $attributeName A non-empty string that is the name of a
  961. * member or relation.
  962. * @see attributeNames()
  963. * @return A value or model of the type specified as valid for the
  964. * member or relation by the meta data supplied by the extending
  965. * class's getMetadata() method.
  966. */
  967. public function __get($attributeName)
  968. {
  969. return $this->unrestrictedGet($attributeName);
  970. }
  971. /**
  972. * A protected version of __get() for models to talk to themselves
  973. * to use their dynamically created members from 'members'
  974. * and 'relations' in its metadata.
  975. */
  976. protected function unrestrictedGet($attributeName)
  977. {
  978. assert('is_string($attributeName)');
  979. assert('$attributeName != ""');
  980. assert("property_exists(\$this, '$attributeName') || \$this->isAttribute('$attributeName')");
  981. if (property_exists($this, $attributeName))
  982. {
  983. return $this->$attributeName;
  984. }
  985. elseif ($attributeName == 'id')
  986. {
  987. $id = intval($this->getPrimaryBean()->id);
  988. assert('$id >= 0');
  989. if ($id == 0)
  990. {
  991. $id = $this->pseudoId;
  992. }
  993. return $id;
  994. }
  995. elseif ($this->isAttribute($attributeName))
  996. {
  997. list($bean, $attributeModelClassName) = $this->attributeNameToBeanAndClassName[$attributeName];
  998. if (!$this->isRelation($attributeName))
  999. {
  1000. $columnName = strtolower($attributeName);
  1001. return $bean->$columnName;
  1002. }
  1003. else
  1004. {
  1005. if (!array_key_exists($attributeName, $this->relationNameToRelatedModel))
  1006. {
  1007. list($relationType, $relatedModelClassName, $owns) = $this->relationNameToRelationTypeModelClassNameAndOwns[$attributeName];
  1008. $relatedTableName = self::getTableName($relatedModelClassName);
  1009. switch ($relationType)
  1010. {
  1011. case self::HAS_ONE_BELONGS_TO:
  1012. $relatedIds = R::$linkManager->getKeys($bean, $relatedTableName);
  1013. assert('in_array(count($relatedIds), array(0, 1))');
  1014. if (count($relatedIds) != 1)
  1015. {
  1016. return null;
  1017. }
  1018. $relatedBean = R::load($relatedTableName, $relatedIds[0]);
  1019. $this->relationNameToRelatedModel[$attributeName] = self::makeModel($relatedBean, $relatedModelClassName);
  1020. break;
  1021. case self::HAS_ONE:
  1022. case self::HAS_MANY_BELONGS_TO:
  1023. if ($relationType == self::HAS_ONE)
  1024. {
  1025. $linkName = strtolower($attributeName);
  1026. if ($linkName == strtolower($relatedModelClassName))
  1027. {
  1028. $linkName = null;
  1029. }
  1030. }
  1031. else
  1032. {
  1033. $linkName = null;
  1034. }
  1035. if ($bean->id > 0 && !in_array($attributeName, $this->unlinkedRelationNames))
  1036. {
  1037. $linkFieldName = R::$linkManager->getLinkField($relatedTableName, $linkName);
  1038. if ((int)$bean->$linkFieldName > 0)
  1039. {
  1040. $beanIdentifier = $relatedTableName .(int)$bean->$linkField

Large files files are truncated, but you can click here to view the full file