PageRenderTime 55ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/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

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. /**
  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. {

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