entity.wrapper.inc

  1. cis7 sites/all/modules/ulmus/entity/includes/entity.wrapper.inc
  2. cle7 sites/all/modules/ulmus/entity/includes/entity.wrapper.inc
  3. ecd7 sites/all/modules/ulmus/entity/includes/entity.wrapper.inc
  4. elmsmedia7 sites/all/modules/ulmus/entity/includes/entity.wrapper.inc
  5. harmony7 sites/all/modules/ulmus/entity/includes/entity.wrapper.inc
  6. icor7 sites/all/modules/ulmus/entity/includes/entity.wrapper.inc
  7. meedjum_blog7 sites/all/modules/ulmus/entity/includes/entity.wrapper.inc
  8. mooc7 sites/all/modules/ulmus/entity/includes/entity.wrapper.inc

Provides wrappers allowing easy usage of the entity metadata.

Classes

Namesort descending Description
EntityDrupalWrapper Provides a wrapper for entities registrered in hook_entity_info().
EntityListWrapper Wraps a list of values.
EntityMetadataArrayObject An array object implementation keeping the reference on the given array so changes to the object are reflected in the passed array.
EntityMetadataWrapper A common base class for all wrappers.
EntityMetadataWrapperException Provide a separate Exception so it can be caught separately.
EntityMetadataWrapperIterator Allows to easily iterate over existing child wrappers.
EntityStructureWrapper Provides a general wrapper for any data structure. For this to work the metadata has to be passed during construction.
EntityValueWrapper Wraps a single value.

File

sites/all/modules/ulmus/entity/includes/entity.wrapper.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Provides wrappers allowing easy usage of the entity metadata.
  5. */
  6. /**
  7. * A common base class for all wrappers.
  8. */
  9. abstract class EntityMetadataWrapper {
  10. protected $type;
  11. protected $data;
  12. protected $info;
  13. protected $cache = array();
  14. /**
  15. * Construct a new wrapper object.
  16. *
  17. * @param $type
  18. * The type of the passed data.
  19. * @param $data
  20. * Optional. The data to wrap.
  21. * @param $info
  22. * Optional. Used internally to pass info about properties down the tree.
  23. */
  24. public function __construct($type, $data = NULL, $info = array()) {
  25. $this->type = $type;
  26. $this->info = $info + array(
  27. 'langcode' => NULL,
  28. );
  29. $this->info['type'] = $type;
  30. if (isset($data)) {
  31. $this->set($data);
  32. }
  33. }
  34. /**
  35. * Gets info about the wrapped data.
  36. *
  37. * @return Array
  38. * Keys set are all keys as specified for a property in hook_entity_info()
  39. * as well as possible the following keys:
  40. * - name: If this wraps a property, the name of the property.
  41. * - parent: The parent wrapper, if any.
  42. * - langcode: The language code, if this data is language specific.
  43. */
  44. public function info() {
  45. return $this->info;
  46. }
  47. /**
  48. * Gets the (entity)type of the wrapped data.
  49. */
  50. public function type() {
  51. return $this->type;
  52. }
  53. /**
  54. * Returns the wrapped data. If no options are given the data is returned as
  55. * described in the info.
  56. *
  57. * @param $options
  58. * (optional) A keyed array of options:
  59. * - sanitize: A boolean flag indicating that textual properties should be
  60. * sanitized for display to a web browser. Defaults to FALSE.
  61. * - decode: If set to TRUE and some textual data is already sanitized, it
  62. * strips HTML tags and decodes HTML entities. Defaults to FALSE.
  63. *
  64. * @return
  65. * The value of the wrapped data. If the data property is not set, NULL
  66. * is returned.
  67. *
  68. * @throws EntityMetadataWrapperException
  69. * In case there are no data values available to the wrapper, an exception
  70. * is thrown. E.g. if the value for an entity property is to be retrieved
  71. * and there is no entity available, the exception is thrown. However, if
  72. * an entity is available but the property is not set, NULL is returned.
  73. */
  74. public function value(array $options = array()) {
  75. if (!$this->dataAvailable() && isset($this->info['parent'])) {
  76. throw new EntityMetadataWrapperException('Missing data values.');
  77. }
  78. if (!isset($this->data) && isset($this->info['name'])) {
  79. $this->data = $this->info['parent']->getPropertyValue($this->info['name'], $this->info);
  80. }
  81. return $this->data;
  82. }
  83. /**
  84. * Returns the raw, unprocessed data. Most times this is the same as returned
  85. * by value(), however for already processed and sanitized textual data, this
  86. * will return the unprocessed data in contrast to value().
  87. */
  88. public function raw() {
  89. if (!$this->dataAvailable()) {
  90. throw new EntityMetadataWrapperException('Missing data values.');
  91. }
  92. if (isset($this->info['name']) && isset($this->info['parent'])) {
  93. return $this->info['parent']->getPropertyRaw($this->info['name'], $this->info);
  94. }
  95. // Else return the usual value, which should be raw in this case.
  96. return $this->value();
  97. }
  98. /**
  99. * Returns whether data is available to work with.
  100. *
  101. * @return
  102. * If we operate without any data FALSE, else TRUE.
  103. */
  104. protected function dataAvailable() {
  105. return isset($this->data) || (isset($this->info['parent']) && $this->info['parent']->dataAvailable());
  106. }
  107. /**
  108. * Set a new data value.
  109. */
  110. public function set($value) {
  111. if (!$this->validate($value)) {
  112. throw new EntityMetadataWrapperException('Invalid data value given. Be sure it matches the required data type and format.');
  113. }
  114. $this->clear();
  115. $this->data = $value;
  116. $this->updateParent($value);
  117. return $this;
  118. }
  119. /**
  120. * Updates the parent data structure of a data property with the latest data value.
  121. */
  122. protected function updateParent($value) {
  123. if (isset($this->info['parent'])) {
  124. $this->info['parent']->setProperty($this->info['name'], $value);
  125. }
  126. }
  127. /**
  128. * Returns whether $value is a valid value to set.
  129. */
  130. public function validate($value) {
  131. if (isset($value) && !entity_property_verify_data_type($value, $this->type)) {
  132. return FALSE;
  133. }
  134. // Only proceed with further checks if this is not a list item. If this is
  135. // a list item, the checks are performed on the list property level.
  136. if (isset($this->info['parent']) && $this->info['parent'] instanceof EntityListWrapper) {
  137. return TRUE;
  138. }
  139. if (!isset($value) && !empty($this->info['required'])) {
  140. // Do not allow NULL values if the property is required.
  141. return FALSE;
  142. }
  143. return !isset($this->info['validation callback']) || call_user_func($this->info['validation callback'], $value, $this->info);
  144. }
  145. public function __toString() {
  146. return isset($this->info) ? 'Property ' . $this->info['name'] : $this->type;
  147. }
  148. /**
  149. * Clears the data value and the wrapper cache.
  150. */
  151. protected function clear() {
  152. $this->data = NULL;
  153. foreach ($this->cache as $wrapper) {
  154. $wrapper->clear();
  155. }
  156. }
  157. /**
  158. * Returns the options list specifying possible values for the property, if
  159. * defined.
  160. *
  161. * @param $op
  162. * (optional) One of 'edit' or 'view'. In case the list of possible values
  163. * a user could set for a property differs from the list of values a
  164. * property could have, $op determines which options should be returned.
  165. * Defaults to 'edit'.
  166. * E.g. all possible roles a user could have include the anonymous and the
  167. * authenticated user roles, while those roles cannot be added to a user
  168. * account. So their options would be included for 'view', but for 'edit'
  169. * not.
  170. *
  171. * @return
  172. * An array as used by hook_options_list() or FALSE.
  173. */
  174. public function optionsList($op = 'edit') {
  175. if (isset($this->info['options list']) && is_callable($this->info['options list'])) {
  176. $name = isset($this->info['name']) ? $this->info['name'] : NULL;
  177. return call_user_func($this->info['options list'], $name, $this->info, $op);
  178. }
  179. return FALSE;
  180. }
  181. /**
  182. * Returns the label for the currently set property value if there is one
  183. * available, i.e. if an options list has been specified.
  184. */
  185. public function label() {
  186. if ($options = $this->optionsList('view')) {
  187. $options = entity_property_options_flatten($options);
  188. $value = $this->value();
  189. if (is_scalar($value) && isset($options[$value])) {
  190. return $options[$value];
  191. }
  192. }
  193. }
  194. /**
  195. * Determines whether the given user has access to view or edit this property.
  196. * Apart from relying on access metadata of properties, this takes into
  197. * account information about entity level access, if available:
  198. * - Referenced entities can only be viewed, when the user also has
  199. * permission to view the entity.
  200. * - A property may be only edited, if the user has permission to update the
  201. * entity containing the property.
  202. *
  203. * @param $op
  204. * The operation being performed. One of 'view' or 'edit.
  205. * @param $account
  206. * The user to check for. Leave it to NULL to check for the global user.
  207. * @return boolean
  208. * Whether access to entity property is allowed for the given operation.
  209. * However if we wrap no data, it returns whether access is allowed to the
  210. * property of all entities of this type.
  211. * If there is no access information for this property, TRUE is returned.
  212. */
  213. public function access($op, $account = NULL) {
  214. return !empty($this->info['parent']) ? $this->info['parent']->propertyAccess($this->info['name'], $op, $account) : TRUE;
  215. }
  216. /**
  217. * Prepare for serializiation.
  218. */
  219. public function __sleep() {
  220. $vars = get_object_vars($this);
  221. unset($vars['cache']);
  222. return drupal_map_assoc(array_keys($vars));
  223. }
  224. }
  225. /**
  226. * Wraps a single value.
  227. */
  228. class EntityValueWrapper extends EntityMetadataWrapper {
  229. /**
  230. * Overrides EntityMetadataWrapper#value().
  231. * Sanitizes or decode textual data if necessary.
  232. */
  233. public function value(array $options = array()) {
  234. $data = parent::value();
  235. if ($this->type == 'text' && isset($data)) {
  236. $info = $this->info + array('sanitized' => FALSE, 'sanitize' => 'check_plain');
  237. $options += array('sanitize' => FALSE, 'decode' => FALSE);
  238. if ($options['sanitize'] && !$info['sanitized']) {
  239. return call_user_func($info['sanitize'], $data);
  240. }
  241. elseif ($options['decode'] && $info['sanitized']) {
  242. return decode_entities(strip_tags($data));
  243. }
  244. }
  245. return $data;
  246. }
  247. }
  248. /**
  249. * Provides a general wrapper for any data structure. For this to work the
  250. * metadata has to be passed during construction.
  251. */
  252. class EntityStructureWrapper extends EntityMetadataWrapper implements IteratorAggregate {
  253. protected $propertyInfo = array(), $propertyInfoAltered = FALSE;
  254. protected $langcode = LANGUAGE_NONE;
  255. protected $propertyInfoDefaults = array(
  256. 'type' => 'text',
  257. 'getter callback' => 'entity_property_verbatim_get',
  258. 'clear' => array(),
  259. );
  260. /**
  261. * Construct a new EntityStructureWrapper object.
  262. *
  263. * @param $type
  264. * The type of the passed data.
  265. * @param $data
  266. * Optional. The data to wrap.
  267. * @param $info
  268. * Used to for specifying metadata about the data and internally to pass
  269. * info about properties down the tree. For specifying metadata known keys
  270. * are:
  271. * - property info: An array of info about the properties of the wrapped
  272. * data structure. It has to contain an array of property info in the same
  273. * structure as used by hook_entity_property_info().
  274. */
  275. public function __construct($type, $data = NULL, $info = array()) {
  276. parent::__construct($type, $data, $info);
  277. $this->info += array('property defaults' => array());
  278. $info += array('property info' => array());
  279. $this->propertyInfo['properties'] = $info['property info'];
  280. }
  281. /**
  282. * May be used to lazy-load additional info about the data, depending on the
  283. * concrete passed data.
  284. */
  285. protected function spotInfo() {
  286. // Apply the callback if set, such that the caller may alter the info.
  287. if (!empty($this->info['property info alter']) && !$this->propertyInfoAltered) {
  288. $this->propertyInfo = call_user_func($this->info['property info alter'], $this, $this->propertyInfo);
  289. $this->propertyInfoAltered = TRUE;
  290. }
  291. }
  292. /**
  293. * Gets the info about the given property.
  294. *
  295. * @param $name
  296. * The name of the property. If not given, info about all properties will
  297. * be returned.
  298. * @throws EntityMetadataWrapperException
  299. * If there is no such property.
  300. * @return
  301. * An array of info about the property.
  302. */
  303. public function getPropertyInfo($name = NULL) {
  304. $this->spotInfo();
  305. if (!isset($name)) {
  306. return $this->propertyInfo['properties'];
  307. }
  308. if (!isset($this->propertyInfo['properties'][$name])) {
  309. throw new EntityMetadataWrapperException('Unknown data property ' . check_plain($name) . '.');
  310. }
  311. return $this->propertyInfo['properties'][$name] + $this->info['property defaults'] + $this->propertyInfoDefaults;
  312. }
  313. /**
  314. * Returns a reference on the property info.
  315. *
  316. * If possible, use the property info alter callback for spotting metadata.
  317. * The reference may be used to alter the property info for any remaining
  318. * cases, e.g. if additional metadata has been asserted.
  319. */
  320. public function &refPropertyInfo() {
  321. return $this->propertyInfo;
  322. }
  323. /**
  324. * Sets a new language to use for retrieving properties.
  325. *
  326. * @param $langcode
  327. * The language code of the language to set.
  328. * @return EntityWrapper
  329. */
  330. public function language($langcode = LANGUAGE_NONE) {
  331. if ($langcode != $this->langcode) {
  332. $this->langcode = $langcode;
  333. $this->cache = array();
  334. }
  335. return $this;
  336. }
  337. /**
  338. * Gets the language used for retrieving properties.
  339. *
  340. * @return String
  341. * The language object of the language or NULL for the default language.
  342. *
  343. * @see EntityStructureWrapper::language()
  344. */
  345. public function getPropertyLanguage() {
  346. if ($this->langcode != LANGUAGE_NONE && $list = language_list()) {
  347. if (isset($list[$this->langcode])) {
  348. return $list[$this->langcode];
  349. }
  350. }
  351. return NULL;
  352. }
  353. /**
  354. * Get the wrapper for a property.
  355. *
  356. * @return
  357. * An instance of EntityMetadataWrapper.
  358. */
  359. public function get($name) {
  360. // Look it up in the cache if possible.
  361. if (!array_key_exists($name, $this->cache)) {
  362. if ($info = $this->getPropertyInfo($name)) {
  363. $info += array('parent' => $this, 'name' => $name, 'langcode' => $this->langcode, 'property defaults' => array());
  364. $info['property defaults'] += $this->info['property defaults'];
  365. $this->cache[$name] = entity_metadata_wrapper($info['type'], NULL, $info);
  366. }
  367. else {
  368. throw new EntityMetadataWrapperException('There is no property ' . check_plain($name) . " for this entity.");
  369. }
  370. }
  371. return $this->cache[$name];
  372. }
  373. /**
  374. * Magic method: Get a wrapper for a property.
  375. */
  376. public function __get($name) {
  377. if (strpos($name, 'krumo') === 0) {
  378. // #914934 Ugly workaround to allow krumo to write its recursion property.
  379. // This is necessary to make dpm() work without throwing exceptions.
  380. return NULL;
  381. }
  382. $get = $this->get($name);
  383. return $get;
  384. }
  385. /**
  386. * Magic method: Set a property.
  387. */
  388. public function __set($name, $value) {
  389. if (strpos($name, 'krumo') === 0) {
  390. // #914934 Ugly workaround to allow krumo to write its recursion property.
  391. // This is necessary to make dpm() work without throwing exceptions.
  392. $this->$name = $value;
  393. }
  394. else {
  395. $this->get($name)->set($value);
  396. }
  397. }
  398. /**
  399. * Gets the value of a property.
  400. */
  401. protected function getPropertyValue($name, &$info) {
  402. $options = array('language' => $this->getPropertyLanguage(), 'absolute' => TRUE);
  403. $data = $this->value();
  404. if (!isset($data)) {
  405. throw new EntityMetadataWrapperException('Unable to get the data property ' . check_plain($name) . ' as the parent data structure is not set.');
  406. }
  407. return $info['getter callback']($data, $options, $name, $this->type, $info);
  408. }
  409. /**
  410. * Gets the raw value of a property.
  411. */
  412. protected function getPropertyRaw($name, &$info) {
  413. if (!empty($info['raw getter callback'])) {
  414. $options = array('language' => $this->getPropertyLanguage(), 'absolute' => TRUE);
  415. $data = $this->value();
  416. if (!isset($data)) {
  417. throw new EntityMetadataWrapperException('Unable to get the data property ' . check_plain($name) . ' as the parent data structure is not set.');
  418. }
  419. return $info['raw getter callback']($data, $options, $name, $this->type, $info);
  420. }
  421. return $this->getPropertyValue($name, $info);
  422. }
  423. /**
  424. * Sets a property.
  425. */
  426. protected function setProperty($name, $value) {
  427. $info = $this->getPropertyInfo($name);
  428. if (!empty($info['setter callback'])) {
  429. $data = $this->value();
  430. // In case the data structure is not set, support simple auto-creation
  431. // for arrays. Else an exception is thrown.
  432. if (!isset($data)) {
  433. if (!empty($this->info['auto creation']) && !($this instanceof EntityDrupalWrapper)) {
  434. $data = $this->info['auto creation']($name, $this->info);
  435. }
  436. else {
  437. throw new EntityMetadataWrapperException('Unable to set the data property ' . check_plain($name) . ' as the parent data structure is not set.');
  438. }
  439. }
  440. // Invoke the setter callback for updating our data.
  441. $info['setter callback']($data, $name, $value, $this->langcode, $this->type, $info);
  442. // If the setter has not thrown any exceptions, proceed and apply the
  443. // update to the current and any parent wrappers as necessary.
  444. $data = $this->info['type'] == 'entity' ? $this : $data;
  445. $this->set($data);
  446. // Clear the cache of properties dependent on this value.
  447. foreach ($info['clear'] as $name) {
  448. if (isset($this->cache[$name])) {
  449. $this->cache[$name]->clear();
  450. }
  451. }
  452. }
  453. else {
  454. throw new EntityMetadataWrapperException('Entity property ' . check_plain($name) . " doesn't support writing.");
  455. }
  456. }
  457. protected function propertyAccess($name, $op, $account = NULL) {
  458. $info = $this->getPropertyInfo($name);
  459. // If a property should be edited and this is part of an entity, make sure
  460. // the user has update access for this entity.
  461. if ($op == 'edit') {
  462. $entity = $this;
  463. while (!($entity instanceof EntityDrupalWrapper) && isset($entity->info['parent'])) {
  464. $entity = $entity->info['parent'];
  465. }
  466. if ($entity instanceof EntityDrupalWrapper && !$entity->entityAccess('update', $account)) {
  467. return FALSE;
  468. }
  469. }
  470. if (!empty($info['access callback'])) {
  471. $data = $this->dataAvailable() ? $this->value() : NULL;
  472. return call_user_func($info['access callback'], $op, $name, $data, $account, $this->type);
  473. }
  474. elseif ($op == 'edit' && isset($info['setter permission'])) {
  475. return user_access($info['setter permission'], $account);
  476. }
  477. return TRUE;
  478. }
  479. /**
  480. * Magic method: Can be used to check if a property is known.
  481. */
  482. public function __isset($name) {
  483. $this->spotInfo();
  484. return isset($this->propertyInfo['properties'][$name]);
  485. }
  486. public function getIterator() {
  487. $this->spotInfo();
  488. return new EntityMetadataWrapperIterator($this, array_keys($this->propertyInfo['properties']));
  489. }
  490. /**
  491. * Returns the identifier of the data structure. If there is none, NULL is
  492. * returned.
  493. */
  494. public function getIdentifier() {
  495. return isset($this->id) && $this->dataAvailable() ? $this->id->value() : NULL;
  496. }
  497. /**
  498. * Prepare for serializiation.
  499. */
  500. public function __sleep() {
  501. $vars = parent::__sleep();
  502. unset($vars['propertyInfoDefaults']);
  503. return $vars;
  504. }
  505. public function clear() {
  506. $this->propertyInfoAltered = FALSE;
  507. parent::clear();
  508. }
  509. }
  510. /**
  511. * Provides a wrapper for entities registrered in hook_entity_info().
  512. *
  513. * The wrapper eases applying getter and setter callbacks of entity properties
  514. * specified in hook_entity_property_info().
  515. */
  516. class EntityDrupalWrapper extends EntityStructureWrapper {
  517. /**
  518. * Contains the entity id.
  519. */
  520. protected $id = FALSE;
  521. protected $bundle;
  522. protected $entityInfo;
  523. /**
  524. * Construct a new EntityDrupalWrapper object.
  525. *
  526. * @param $type
  527. * The type of the passed data.
  528. * @param $data
  529. * Optional. The entity to wrap or its identifier.
  530. * @param $info
  531. * Optional. Used internally to pass info about properties down the tree.
  532. */
  533. public function __construct($type, $data = NULL, $info = array()) {
  534. parent::__construct($type, $data, $info);
  535. $this->setUp();
  536. }
  537. protected function setUp() {
  538. $this->propertyInfo = entity_get_property_info($this->type) + array('properties' => array());
  539. $info = $this->info + array('property info' => array(), 'bundle' => NULL);
  540. $this->propertyInfo['properties'] += $info['property info'];
  541. $this->bundle = $info['bundle'];
  542. $this->entityInfo = entity_get_info($this->type);
  543. if (isset($this->bundle)) {
  544. $this->spotBundleInfo(FALSE);
  545. }
  546. }
  547. /**
  548. * Sets the entity internally accepting both the entity id and object.
  549. */
  550. protected function setEntity($data) {
  551. // For entities we allow getter callbacks to return FALSE, which we
  552. // interpret like NULL values as unset properties.
  553. if (isset($data) && $data !== FALSE && !is_object($data)) {
  554. $this->id = $data;
  555. $this->data = FALSE;
  556. }
  557. elseif (is_object($data) && $data instanceof EntityDrupalWrapper) {
  558. // We got a wrapped entity passed, so take over its values.
  559. $this->id = $data->id;
  560. $this->data = $data->data;
  561. // For generic entity references, also update the entity type accordingly.
  562. if ($this->info['type'] == 'entity') {
  563. $this->type = $data->type;
  564. }
  565. }
  566. elseif (is_object($data)) {
  567. // We got the entity object passed.
  568. $this->data = $data;
  569. $id = entity_id($this->type, $data);
  570. $this->id = isset($id) ? $id : FALSE;
  571. }
  572. else {
  573. $this->id = FALSE;
  574. $this->data = NULL;
  575. }
  576. }
  577. /**
  578. * Used to lazy-load bundle info. So the wrapper can be loaded e.g. just
  579. * for setting without the data being loaded.
  580. */
  581. protected function spotInfo() {
  582. if (!$this->propertyInfoAltered) {
  583. if ($this->info['type'] == 'entity' && $this->dataAvailable() && $this->value()) {
  584. // Add in entity-type specific details.
  585. $this->setUp();
  586. }
  587. $this->spotBundleInfo(TRUE);
  588. parent::spotInfo();
  589. $this->propertyInfoAltered = TRUE;
  590. }
  591. }
  592. /**
  593. * Tries to determine the bundle and adds in the according property info.
  594. *
  595. * @param $load
  596. * Whether the entity should be loaded to spot the info if necessary.
  597. */
  598. protected function spotBundleInfo($load = TRUE) {
  599. // Like entity_extract_ids() assume the entity type if no key is given.
  600. if (empty($this->entityInfo['entity keys']['bundle']) && $this->type != 'entity') {
  601. $this->bundle = $this->type;
  602. }
  603. // Detect the bundle if not set yet and add in properties from the bundle.
  604. elseif (!$this->bundle && $load && $this->dataAvailable()) {
  605. try {
  606. if ($entity = $this->value()) {
  607. list($id, $vid, $bundle) = entity_extract_ids($this->type, $entity);
  608. $this->bundle = $bundle;
  609. }
  610. }
  611. catch (EntityMetadataWrapperException $e) {
  612. // Loading data failed, so we cannot derive the used bundle.
  613. }
  614. }
  615. if ($this->bundle && isset($this->propertyInfo['bundles'][$this->bundle])) {
  616. $bundle_info = (array) $this->propertyInfo['bundles'][$this->bundle] + array('properties' => array());
  617. // Allow bundles to re-define existing properties, such that the bundle
  618. // can add in more bundle-specific details like the bundle of a referenced
  619. // entity.
  620. $this->propertyInfo['properties'] = $bundle_info['properties'] + $this->propertyInfo['properties'];
  621. }
  622. }
  623. /**
  624. * Returns the identifier of the wrapped entity.
  625. *
  626. * @see entity_id()
  627. */
  628. public function getIdentifier() {
  629. return $this->dataAvailable() ? $this->value(array('identifier' => TRUE)) : NULL;
  630. }
  631. /**
  632. * Returns the bundle of an entity, or FALSE if it has no bundles.
  633. */
  634. public function getBundle() {
  635. if ($this->dataAvailable()) {
  636. $this->spotInfo();
  637. return $this->bundle;
  638. }
  639. }
  640. /**
  641. * Overridden.
  642. *
  643. * @param $options
  644. * An array of options. Known keys:
  645. * - identifier: If set to TRUE, the entity identifier is returned.
  646. */
  647. public function value(array $options = array()) {
  648. // Try loading the data via the getter callback if there is none yet.
  649. if (!isset($this->data)) {
  650. $this->setEntity(parent::value());
  651. }
  652. if (!empty($options['identifier'])) {
  653. return $this->id;
  654. }
  655. elseif (!$this->data && !empty($this->id)) {
  656. // Lazy load the entity if necessary.
  657. $return = entity_load($this->type, array($this->id));
  658. // In case the entity cannot be loaded, we return NULL just as for empty
  659. // properties.
  660. $this->data = $return ? reset($return) : NULL;
  661. }
  662. return $this->data;
  663. }
  664. /**
  665. * Returns the entity prepared for rendering.
  666. *
  667. * @see entity_view()
  668. */
  669. public function view($view_mode = 'full', $langcode = NULL, $page = NULL) {
  670. return entity_view($this->type(), array($this->value()), $view_mode, $langcode, $page);
  671. }
  672. /**
  673. * Overridden to support setting the entity by either the object or the id.
  674. */
  675. public function set($value) {
  676. if (!$this->validate($value)) {
  677. throw new EntityMetadataWrapperException('Invalid data value given. Be sure it matches the required data type and format.');
  678. }
  679. if ($this->info['type'] == 'entity' && $value === $this) {
  680. // Nothing to do.
  681. return $this;
  682. }
  683. $previous_id = $this->id;
  684. $previous_type = $this->type;
  685. // Set value, so we get the identifier and pass it to the normal setter.
  686. $this->clear();
  687. $this->setEntity($value);
  688. // Generally, we have to update the parent only if the entity reference
  689. // has changed. In case of a generic entity reference, we pass the entity
  690. // wrapped. Else we just pass the id of the entity to the setter callback.
  691. if ($this->info['type'] == 'entity' && ($previous_id != $this->id || $previous_type != $this->type)) {
  692. // We need to clone the wrapper we pass through as value, so it does not
  693. // get cleared when the current wrapper instance gets cleared.
  694. $this->updateParent(clone $this);
  695. }
  696. // In case the entity has been unset, we cannot properly detect changes as
  697. // the previous id defaults to FALSE for unloaded entities too. So in that
  698. // case we just always update the parent.
  699. elseif ($this->id === FALSE && !$this->data) {
  700. $this->updateParent(NULL);
  701. }
  702. elseif ($previous_id !== $this->id) {
  703. $this->updateParent($this->id);
  704. }
  705. return $this;
  706. }
  707. /**
  708. * Overridden.
  709. */
  710. public function clear() {
  711. $this->id = NULL;
  712. $this->bundle = isset($this->info['bundle']) ? $this->info['bundle'] : NULL;
  713. if ($this->type != $this->info['type']) {
  714. // Reset entity info / property info based upon the info provided during
  715. // the creation of the wrapper.
  716. $this->type = $this->info['type'];
  717. $this->setUp();
  718. }
  719. parent::clear();
  720. }
  721. /**
  722. * Overridden.
  723. */
  724. public function type() {
  725. // In case of a generic entity wrapper, load the data first to determine
  726. // the type of the concrete entity.
  727. if ($this->dataAvailable() && $this->info['type'] == 'entity') {
  728. try {
  729. $this->value(array('identifier' => TRUE));
  730. }
  731. catch (EntityMetadataWrapperException $e) {
  732. // If loading data fails, we cannot determine the concrete entity type.
  733. }
  734. }
  735. return $this->type;
  736. }
  737. /**
  738. * {@inheritdoc}
  739. *
  740. * Note that this method checks property access, but can be used for checking
  741. * entity access *only* if the wrapper is not a property (i.e. has no parent
  742. * wrapper).
  743. * To be safe, better use EntityDrupalWrapper::entityAccess() for checking
  744. * entity access.
  745. */
  746. public function access($op, $account = NULL) {
  747. if (!empty($this->info['parent'])) {
  748. // If this is a property, make sure the user is able to view the
  749. // currently referenced entity also.
  750. return $this->entityAccess('view', $account) && parent::access($op, $account);
  751. }
  752. else {
  753. // This is not a property, so fallback on entity access.
  754. return $this->entityAccess($op == 'edit' ? 'update' : 'view', $account);
  755. }
  756. }
  757. /**
  758. * Checks whether the operation $op is allowed on the entity.
  759. *
  760. * @see entity_access()
  761. */
  762. public function entityAccess($op, $account = NULL) {
  763. $entity = $this->dataAvailable() ? $this->value() : NULL;
  764. // The value() method could return FALSE on entities such as user 0, so we
  765. // need to use NULL instead to conform to the expectations of
  766. // entity_access().
  767. if ($entity === FALSE) {
  768. $entity = NULL;
  769. }
  770. return entity_access($op, $this->type, $entity, $account);
  771. }
  772. /**
  773. * Permanently save the wrapped entity.
  774. *
  775. * @throws EntityMetadataWrapperException
  776. * If the entity type does not support saving.
  777. *
  778. * @return EntityDrupalWrapper
  779. */
  780. public function save() {
  781. if ($this->data) {
  782. if (!entity_type_supports($this->type, 'save')) {
  783. throw new EntityMetadataWrapperException("There is no information about how to save entities of type " . check_plain($this->type) . '.');
  784. }
  785. entity_save($this->type, $this->data);
  786. // On insert, update the identifier afterwards.
  787. if (!$this->id) {
  788. list($this->id, , ) = entity_extract_ids($this->type, $this->data);
  789. }
  790. }
  791. // If the entity hasn't been loaded yet, don't bother saving it.
  792. return $this;
  793. }
  794. /**
  795. * Permanently delete the wrapped entity.
  796. *
  797. * @return EntityDrupalWrapper
  798. */
  799. public function delete() {
  800. if ($this->dataAvailable() && $this->value()) {
  801. $return = entity_delete($this->type, $this->id);
  802. if ($return === FALSE) {
  803. throw new EntityMetadataWrapperException("There is no information about how to delete entities of type " . check_plain($this->type) . '.');
  804. }
  805. }
  806. return $this;
  807. }
  808. /**
  809. * Gets the info about the wrapped entity.
  810. */
  811. public function entityInfo() {
  812. return $this->entityInfo;
  813. }
  814. /**
  815. * Returns the name of the key used by the entity for given entity key.
  816. *
  817. * @param $name
  818. * One of 'id', 'name', 'bundle' or 'revision'.
  819. * @return
  820. * The name of the key used by the entity.
  821. */
  822. public function entityKey($name) {
  823. return isset($this->entityInfo['entity keys'][$name]) ? $this->entityInfo['entity keys'][$name] : FALSE;
  824. }
  825. /**
  826. * Returns the entity label.
  827. *
  828. * @see entity_label()
  829. */
  830. public function label() {
  831. if ($entity = $this->value()) {
  832. return entity_label($this->type, $entity);
  833. }
  834. }
  835. /**
  836. * Prepare for serializiation.
  837. */
  838. public function __sleep() {
  839. $vars = parent::__sleep();
  840. // Don't serialize the loaded entity and its property info.
  841. unset($vars['data'], $vars['propertyInfo'], $vars['propertyInfoAltered'], $vars['entityInfo']);
  842. // In case the entity is not saved yet, serialize the unsaved data.
  843. if ($this->dataAvailable() && $this->id === FALSE) {
  844. $vars['data'] = 'data';
  845. }
  846. return $vars;
  847. }
  848. public function __wakeup() {
  849. $this->setUp();
  850. if ($this->id !== FALSE) {
  851. // Make sure data is set, so the entity will be loaded when needed.
  852. $this->data = FALSE;
  853. }
  854. }
  855. }
  856. /**
  857. * Wraps a list of values.
  858. *
  859. * If the wrapped data is a list of data, its numerical indexes may be used to
  860. * retrieve wrappers for the list items. For that this wrapper implements
  861. * ArrayAccess so it may be used like a usual numerically indexed array.
  862. */
  863. class EntityListWrapper extends EntityMetadataWrapper implements IteratorAggregate, ArrayAccess, Countable {
  864. /**
  865. * The type of contained items.
  866. */
  867. protected $itemType;
  868. /**
  869. * Whether this is a list of entities with a known entity type, i.e. for
  870. * generic list of entities (list<entity>) this is FALSE.
  871. */
  872. protected $isEntityList;
  873. public function __construct($type, $data = NULL, $info = array()) {
  874. parent::__construct($type, NULL, $info);
  875. $this->itemType = entity_property_list_extract_type($this->type);
  876. if (!$this->itemType) {
  877. $this->itemType = 'unknown';
  878. }
  879. $this->isEntityList = (bool) entity_get_info($this->itemType);
  880. if (isset($data)) {
  881. $this->set($data);
  882. }
  883. }
  884. /**
  885. * Get the wrapper for a single item.
  886. *
  887. * @return
  888. * An instance of EntityMetadataWrapper.
  889. */
  890. public function get($delta) {
  891. // Look it up in the cache if possible.
  892. if (!array_key_exists($delta, $this->cache)) {
  893. if (!isset($delta)) {
  894. // The [] operator has been used so point at a new entry.
  895. $values = parent::value();
  896. $delta = $values ? max(array_keys($values)) + 1 : 0;
  897. }
  898. if (is_numeric($delta)) {
  899. $info = array('parent' => $this, 'name' => $delta) + $this->info;
  900. $this->cache[$delta] = entity_metadata_wrapper($this->itemType, NULL, $info);
  901. }
  902. else {
  903. throw new EntityMetadataWrapperException('There can be only numerical keyed items in a list.');
  904. }
  905. }
  906. return $this->cache[$delta];
  907. }
  908. protected function getPropertyValue($delta) {
  909. // Make use parent::value() to easily by-pass any entity-loading.
  910. $data = parent::value();
  911. if (isset($data[$delta])) {
  912. return $data[$delta];
  913. }
  914. }
  915. protected function getPropertyRaw($delta) {
  916. return $this->getPropertyValue($delta);
  917. }
  918. protected function setProperty($delta, $value) {
  919. $data = parent::value();
  920. if (is_numeric($delta)) {
  921. $data[$delta] = $value;
  922. $this->set($data);
  923. }
  924. }
  925. protected function propertyAccess($delta, $op, $account = NULL) {
  926. return $this->access($op, $account);
  927. }
  928. /**
  929. * Returns the list as numerically indexed array.
  930. *
  931. * Note that a list of entities might contain stale entity references. In
  932. * that case the wrapper and the identifier of a stale reference would be
  933. * still accessible, however the entity object value would be NULL. That way,
  934. * there may be NULL values in lists of entity objects due to stale entity
  935. * references.
  936. *
  937. * @param $options
  938. * An array of options. Known keys:
  939. * - identifier: If set to TRUE for a list of entities, it won't be returned
  940. * as list of fully loaded entity objects, but as a list of entity ids.
  941. * Note that this list may contain ids of stale entity references.
  942. */
  943. public function value(array $options = array()) {
  944. // For lists of entities fetch full entity objects before returning.
  945. // Generic entity-wrappers need to be handled separately though.
  946. if ($this->isEntityList && empty($options['identifier']) && $this->dataAvailable()) {
  947. $list = parent::value();
  948. $entities = $list ? entity_load($this->get(0)->type, $list) : array();
  949. // Make sure to keep the array keys as present in the list.
  950. foreach ($list as $key => $id) {
  951. // In case the entity cannot be loaded, we return NULL just as for empty
  952. // properties.
  953. $list[$key] = isset($entities[$id]) ? $entities[$id] : NULL;
  954. }
  955. return $list;
  956. }
  957. return parent::value();
  958. }
  959. public function set($values) {
  960. // Support setting lists of fully loaded entities.
  961. if ($this->isEntityList && $values && is_object(reset($values))) {
  962. foreach ($values as $key => $value) {
  963. // Ignore outdated NULL value references in lists of entities.
  964. if (isset($value)) {
  965. list($id, $vid, $bundle) = entity_extract_ids($this->itemType, $value);
  966. $values[$key] = $id;
  967. }
  968. }
  969. }
  970. return parent::set($values);
  971. }
  972. /**
  973. * If we wrap a list, we return an iterator over the data list.
  974. */
  975. public function getIterator() {
  976. // In case there is no data available, just iterate over the first item.
  977. return new EntityMetadataWrapperIterator($this, $this->dataAvailable() ? array_keys(parent::value()) : array(0));
  978. }
  979. /**
  980. * Implements the ArrayAccess interface.
  981. */
  982. public function offsetGet($delta) {
  983. return $this->get($delta);
  984. }
  985. public function offsetExists($delta) {
  986. return $this->dataAvailable() && ($data = $this->value()) && array_key_exists($delta, $data);
  987. }
  988. public function offsetSet($delta, $value) {
  989. $this->get($delta)->set($value);
  990. }
  991. public function offsetUnset($delta) {
  992. if ($this->offsetExists($delta)) {
  993. unset($this->data[$delta]);
  994. $this->set($this->data);
  995. }
  996. }
  997. public function count() {
  998. return $this->dataAvailable() ? count($this->value()) : 0;
  999. }
  1000. /**
  1001. * Overridden.
  1002. */
  1003. public function validate($value) {
  1004. // Required lists may not be empty or unset.
  1005. if (!empty($this->info['required']) && empty($value)) {
  1006. return FALSE;
  1007. }
  1008. return parent::validate($value);
  1009. }
  1010. /**
  1011. * Returns the label for the list of set values if available.
  1012. */
  1013. public function label() {
  1014. if ($options = $this->optionsList('view')) {
  1015. $options = entity_property_options_flatten($options);
  1016. $labels = array_intersect_key($options, array_flip((array) parent::value()));
  1017. }
  1018. else {
  1019. // Get each label on its own, e.g. to support getting labels of a list
  1020. // of entities.
  1021. $labels = array();
  1022. foreach ($this as $key => $property) {
  1023. $label = $property->label();
  1024. if (!$label) {
  1025. return NULL;
  1026. }
  1027. $labels[] = $label;
  1028. }
  1029. }
  1030. return isset($labels) ? implode(', ', $labels) : NULL;
  1031. }
  1032. }
  1033. /**
  1034. * Provide a separate Exception so it can be caught separately.
  1035. */
  1036. class EntityMetadataWrapperException extends Exception { }
  1037. /**
  1038. * Allows to easily iterate over existing child wrappers.
  1039. */
  1040. class EntityMetadataWrapperIterator implements RecursiveIterator {
  1041. protected $position = 0;
  1042. protected $wrapper, $keys;
  1043. public function __construct(EntityMetadataWrapper $wrapper, array $keys) {
  1044. $this->wrapper = $wrapper;
  1045. $this->keys = $keys;
  1046. }
  1047. function rewind() {
  1048. $this->position = 0;
  1049. }
  1050. function current() {
  1051. return $this->wrapper->get($this->keys[$this->position]);
  1052. }
  1053. function key() {
  1054. return $this->keys[$this->position];
  1055. }
  1056. function next() {
  1057. $this->position++;
  1058. }
  1059. function valid() {
  1060. return isset($this->keys[$this->position]);
  1061. }
  1062. public function hasChildren() {
  1063. return $this->current() instanceof IteratorAggregate;
  1064. }
  1065. public function getChildren() {
  1066. return $this->current()->getIterator();
  1067. }
  1068. }
  1069. /**
  1070. * An array object implementation keeping the reference on the given array so
  1071. * changes to the object are reflected in the passed array.
  1072. */
  1073. class EntityMetadataArrayObject implements ArrayAccess, Countable, IteratorAggregate {
  1074. protected $data;
  1075. public function __construct(&$array) {
  1076. $this->data =& $array;
  1077. }
  1078. public function &getArray() {
  1079. return $this->data;
  1080. }
  1081. /**
  1082. * Implements the ArrayAccess interface.
  1083. */
  1084. public function offsetGet($delta) {
  1085. return $this->data[$delta];
  1086. }
  1087. public function offsetExists($delta) {
  1088. return array_key_exists($delta, $this->data);
  1089. }
  1090. public function offsetSet($delta, $value) {
  1091. $this->data[$delta] = $value;
  1092. }
  1093. public function offsetUnset($delta) {
  1094. unset($this->data[$delta]);
  1095. }
  1096. public function count() {
  1097. return count($this->data);
  1098. }
  1099. public function getIterator() {
  1100. return new ArrayIterator($this->data);
  1101. }
  1102. }
Error | ELMSLN API

Error

×

Error message

  • Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/elmsln_community/api.elmsln.org/includes/common.inc:2791) in drupal_send_headers() (line 1499 of /var/www/html/elmsln_community/api.elmsln.org/includes/bootstrap.inc).
  • Error: Call to undefined function apc_delete() in DrupalAPCCache->clear() (line 289 of /var/www/html/elmsln_community/api.elmsln.org/sites/all/modules/apc/drupal_apc_cache.inc).
The website encountered an unexpected error. Please try again later.