entity.wrapper.inc 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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) === FALSE) {
  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. // If access is unknown, we return TRUE.
  478. return TRUE;
  479. }
  480. /**
  481. * Magic method: Can be used to check if a property is known.
  482. */
  483. public function __isset($name) {
  484. $this->spotInfo();
  485. return isset($this->propertyInfo['properties'][$name]);
  486. }
  487. public function getIterator() {
  488. $this->spotInfo();
  489. return new EntityMetadataWrapperIterator($this, array_keys($this->propertyInfo['properties']));
  490. }
  491. /**
  492. * Returns the identifier of the data structure. If there is none, NULL is
  493. * returned.
  494. */
  495. public function getIdentifier() {
  496. return isset($this->id) && $this->dataAvailable() ? $this->id->value() : NULL;
  497. }
  498. /**
  499. * Prepare for serializiation.
  500. */
  501. public function __sleep() {
  502. $vars = parent::__sleep();
  503. unset($vars['propertyInfoDefaults']);
  504. return $vars;
  505. }
  506. public function clear() {
  507. $this->propertyInfoAltered = FALSE;
  508. parent::clear();
  509. }
  510. }
  511. /**
  512. * Provides a wrapper for entities registrered in hook_entity_info().
  513. *
  514. * The wrapper eases applying getter and setter callbacks of entity properties
  515. * specified in hook_entity_property_info().
  516. */
  517. class EntityDrupalWrapper extends EntityStructureWrapper {
  518. /**
  519. * Contains the entity id.
  520. */
  521. protected $id = FALSE;
  522. protected $bundle;
  523. protected $entityInfo;
  524. /**
  525. * Construct a new EntityDrupalWrapper object.
  526. *
  527. * @param $type
  528. * The type of the passed data.
  529. * @param $data
  530. * Optional. The entity to wrap or its identifier.
  531. * @param $info
  532. * Optional. Used internally to pass info about properties down the tree.
  533. */
  534. public function __construct($type, $data = NULL, $info = array()) {
  535. parent::__construct($type, $data, $info);
  536. $this->setUp();
  537. }
  538. protected function setUp() {
  539. $this->propertyInfo = entity_get_property_info($this->type) + array('properties' => array());
  540. $info = $this->info + array('property info' => array(), 'bundle' => NULL);
  541. $this->propertyInfo['properties'] += $info['property info'];
  542. $this->bundle = $info['bundle'];
  543. $this->entityInfo = entity_get_info($this->type);
  544. if (isset($this->bundle)) {
  545. $this->spotBundleInfo(FALSE);
  546. }
  547. }
  548. /**
  549. * Sets the entity internally accepting both the entity id and object.
  550. */
  551. protected function setEntity($data) {
  552. // For entities we allow getter callbacks to return FALSE, which we
  553. // interpret like NULL values as unset properties.
  554. if (isset($data) && $data !== FALSE && !is_object($data)) {
  555. $this->id = $data;
  556. $this->data = FALSE;
  557. }
  558. elseif (is_object($data) && $data instanceof EntityDrupalWrapper) {
  559. // We got a wrapped entity passed, so take over its values.
  560. $this->id = $data->id;
  561. $this->data = $data->data;
  562. // For generic entity references, also update the entity type accordingly.
  563. if ($this->info['type'] == 'entity') {
  564. $this->type = $data->type;
  565. }
  566. }
  567. elseif (is_object($data)) {
  568. // We got the entity object passed.
  569. $this->data = $data;
  570. $id = entity_id($this->type, $data);
  571. $this->id = isset($id) ? $id : FALSE;
  572. }
  573. else {
  574. $this->id = FALSE;
  575. $this->data = NULL;
  576. }
  577. }
  578. /**
  579. * Used to lazy-load bundle info. So the wrapper can be loaded e.g. just
  580. * for setting without the data being loaded.
  581. */
  582. protected function spotInfo() {
  583. if (!$this->propertyInfoAltered) {
  584. if ($this->info['type'] == 'entity' && $this->dataAvailable() && $this->value()) {
  585. // Add in entity-type specific details.
  586. $this->setUp();
  587. }
  588. $this->spotBundleInfo(TRUE);
  589. parent::spotInfo();
  590. $this->propertyInfoAltered = TRUE;
  591. }
  592. }
  593. /**
  594. * Tries to determine the bundle and adds in the according property info.
  595. *
  596. * @param $load
  597. * Whether the entity should be loaded to spot the info if necessary.
  598. */
  599. protected function spotBundleInfo($load = TRUE) {
  600. // Like entity_extract_ids() assume the entity type if no key is given.
  601. if (empty($this->entityInfo['entity keys']['bundle']) && $this->type != 'entity') {
  602. $this->bundle = $this->type;
  603. }
  604. // Detect the bundle if not set yet and add in properties from the bundle.
  605. elseif (!$this->bundle && $load && $this->dataAvailable()) {
  606. try {
  607. if ($entity = $this->value()) {
  608. list($id, $vid, $bundle) = entity_extract_ids($this->type, $entity);
  609. $this->bundle = $bundle;
  610. }
  611. }
  612. catch (EntityMetadataWrapperException $e) {
  613. // Loading data failed, so we cannot derive the used bundle.
  614. }
  615. }
  616. if ($this->bundle && isset($this->propertyInfo['bundles'][$this->bundle])) {
  617. $bundle_info = (array) $this->propertyInfo['bundles'][$this->bundle] + array('properties' => array());
  618. // Allow bundles to re-define existing properties, such that the bundle
  619. // can add in more bundle-specific details like the bundle of a referenced
  620. // entity.
  621. $this->propertyInfo['properties'] = $bundle_info['properties'] + $this->propertyInfo['properties'];
  622. }
  623. }
  624. /**
  625. * Returns the identifier of the wrapped entity.
  626. *
  627. * @see entity_id()
  628. */
  629. public function getIdentifier() {
  630. return $this->dataAvailable() ? $this->value(array('identifier' => TRUE)) : NULL;
  631. }
  632. /**
  633. * Returns the bundle of an entity, or FALSE if it has no bundles.
  634. */
  635. public function getBundle() {
  636. if ($this->dataAvailable()) {
  637. $this->spotInfo();
  638. return $this->bundle;
  639. }
  640. }
  641. /**
  642. * Overridden.
  643. *
  644. * @param $options
  645. * An array of options. Known keys:
  646. * - identifier: If set to TRUE, the entity identifier is returned.
  647. */
  648. public function value(array $options = array()) {
  649. // Try loading the data via the getter callback if there is none yet.
  650. if (!isset($this->data)) {
  651. $this->setEntity(parent::value());
  652. }
  653. if (!empty($options['identifier'])) {
  654. return $this->id;
  655. }
  656. elseif (!$this->data && !empty($this->id)) {
  657. // Lazy load the entity if necessary.
  658. $return = entity_load($this->type, array($this->id));
  659. // In case the entity cannot be loaded, we return NULL just as for empty
  660. // properties.
  661. $this->data = $return ? reset($return) : NULL;
  662. }
  663. return $this->data;
  664. }
  665. /**
  666. * Returns the entity prepared for rendering.
  667. *
  668. * @see entity_view()
  669. */
  670. public function view($view_mode = 'full', $langcode = NULL, $page = NULL) {
  671. return entity_view($this->type(), array($this->value()), $view_mode, $langcode, $page);
  672. }
  673. /**
  674. * Overridden to support setting the entity by either the object or the id.
  675. */
  676. public function set($value) {
  677. if (!$this->validate($value)) {
  678. throw new EntityMetadataWrapperException('Invalid data value given. Be sure it matches the required data type and format.');
  679. }
  680. if ($this->info['type'] == 'entity' && $value === $this) {
  681. // Nothing to do.
  682. return $this;
  683. }
  684. $previous_id = $this->id;
  685. $previous_type = $this->type;
  686. // Set value, so we get the identifier and pass it to the normal setter.
  687. $this->clear();
  688. $this->setEntity($value);
  689. // Generally, we have to update the parent only if the entity reference
  690. // has changed. In case of a generic entity reference, we pass the entity
  691. // wrapped. Else we just pass the id of the entity to the setter callback.
  692. if ($this->info['type'] == 'entity' && ($previous_id != $this->id || $previous_type != $this->type)) {
  693. // We need to clone the wrapper we pass through as value, so it does not
  694. // get cleared when the current wrapper instance gets cleared.
  695. $this->updateParent(clone $this);
  696. }
  697. // In case the entity has been unset, we cannot properly detect changes as
  698. // the previous id defaults to FALSE for unloaded entities too. So in that
  699. // case we just always update the parent.
  700. elseif ($this->id === FALSE && !$this->data) {
  701. $this->updateParent(NULL);
  702. }
  703. elseif ($previous_id !== $this->id) {
  704. $this->updateParent($this->id);
  705. }
  706. return $this;
  707. }
  708. /**
  709. * Overridden.
  710. */
  711. public function clear() {
  712. $this->id = NULL;
  713. $this->bundle = isset($this->info['bundle']) ? $this->info['bundle'] : NULL;
  714. if ($this->type != $this->info['type']) {
  715. // Reset entity info / property info based upon the info provided during
  716. // the creation of the wrapper.
  717. $this->type = $this->info['type'];
  718. $this->setUp();
  719. }
  720. parent::clear();
  721. }
  722. /**
  723. * Overridden.
  724. */
  725. public function type() {
  726. // In case of a generic entity wrapper, load the data first to determine
  727. // the type of the concrete entity.
  728. if ($this->dataAvailable() && $this->info['type'] == 'entity') {
  729. try {
  730. $this->value(array('identifier' => TRUE));
  731. }
  732. catch (EntityMetadataWrapperException $e) {
  733. // If loading data fails, we cannot determine the concrete entity type.
  734. }
  735. }
  736. return $this->type;
  737. }
  738. /**
  739. * {@inheritdoc}
  740. *
  741. * Note that this method checks property access, but can be used for checking
  742. * entity access *only* if the wrapper is not a property (i.e. has no parent
  743. * wrapper).
  744. * To be safe, better use EntityDrupalWrapper::entityAccess() for checking
  745. * entity access.
  746. */
  747. public function access($op, $account = NULL) {
  748. if (!empty($this->info['parent'])) {
  749. // If this is a property, make sure the user is able to view the
  750. // currently referenced entity also.
  751. if ($this->entityAccess('view', $account) === FALSE) {
  752. return FALSE;
  753. }
  754. if (parent::access($op, $account) === FALSE) {
  755. return FALSE;
  756. }
  757. // If access is unknown, we return TRUE.
  758. return TRUE;
  759. }
  760. else {
  761. // This is not a property, so fallback on entity access.
  762. return $this->entityAccess($op == 'edit' ? 'update' : 'view', $account);
  763. }
  764. }
  765. /**
  766. * Checks whether the operation $op is allowed on the entity.
  767. *
  768. * @see entity_access()
  769. */
  770. public function entityAccess($op, $account = NULL) {
  771. $entity = $this->dataAvailable() ? $this->value() : NULL;
  772. // The value() method could return FALSE on entities such as user 0, so we
  773. // need to use NULL instead to conform to the expectations of
  774. // entity_access().
  775. if ($entity === FALSE) {
  776. $entity = NULL;
  777. }
  778. return entity_access($op, $this->type, $entity, $account);
  779. }
  780. /**
  781. * Permanently save the wrapped entity.
  782. *
  783. * @throws EntityMetadataWrapperException
  784. * If the entity type does not support saving.
  785. *
  786. * @return EntityDrupalWrapper
  787. */
  788. public function save() {
  789. if ($this->data) {
  790. if (!entity_type_supports($this->type, 'save')) {
  791. throw new EntityMetadataWrapperException("There is no information about how to save entities of type " . check_plain($this->type) . '.');
  792. }
  793. entity_save($this->type, $this->data);
  794. // On insert, update the identifier afterwards.
  795. if (!$this->id) {
  796. list($this->id, , ) = entity_extract_ids($this->type, $this->data);
  797. }
  798. }
  799. // If the entity hasn't been loaded yet, don't bother saving it.
  800. return $this;
  801. }
  802. /**
  803. * Permanently delete the wrapped entity.
  804. *
  805. * @return EntityDrupalWrapper
  806. */
  807. public function delete() {
  808. if ($this->dataAvailable() && $this->value()) {
  809. $return = entity_delete($this->type, $this->id);
  810. if ($return === FALSE) {
  811. throw new EntityMetadataWrapperException("There is no information about how to delete entities of type " . check_plain($this->type) . '.');
  812. }
  813. }
  814. return $this;
  815. }
  816. /**
  817. * Gets the info about the wrapped entity.
  818. */
  819. public function entityInfo() {
  820. return $this->entityInfo;
  821. }
  822. /**
  823. * Returns the name of the key used by the entity for given entity key.
  824. *
  825. * @param $name
  826. * One of 'id', 'name', 'bundle' or 'revision'.
  827. * @return
  828. * The name of the key used by the entity.
  829. */
  830. public function entityKey($name) {
  831. return isset($this->entityInfo['entity keys'][$name]) ? $this->entityInfo['entity keys'][$name] : FALSE;
  832. }
  833. /**
  834. * Returns the entity label.
  835. *
  836. * @see entity_label()
  837. */
  838. public function label() {
  839. if ($entity = $this->value()) {
  840. return entity_label($this->type, $entity);
  841. }
  842. }
  843. /**
  844. * Prepare for serializiation.
  845. */
  846. public function __sleep() {
  847. $vars = parent::__sleep();
  848. // Don't serialize the loaded entity and its property info.
  849. unset($vars['data'], $vars['propertyInfo'], $vars['propertyInfoAltered'], $vars['entityInfo']);
  850. // In case the entity is not saved yet, serialize the unsaved data.
  851. if ($this->dataAvailable() && $this->id === FALSE) {
  852. $vars['data'] = 'data';
  853. }
  854. return $vars;
  855. }
  856. public function __wakeup() {
  857. $this->setUp();
  858. if ($this->id !== FALSE) {
  859. // Make sure data is set, so the entity will be loaded when needed.
  860. $this->data = FALSE;
  861. }
  862. }
  863. }
  864. /**
  865. * Wraps a list of values.
  866. *
  867. * If the wrapped data is a list of data, its numerical indexes may be used to
  868. * retrieve wrappers for the list items. For that this wrapper implements
  869. * ArrayAccess so it may be used like a usual numerically indexed array.
  870. */
  871. class EntityListWrapper extends EntityMetadataWrapper implements IteratorAggregate, ArrayAccess, Countable {
  872. /**
  873. * The type of contained items.
  874. */
  875. protected $itemType;
  876. /**
  877. * Whether this is a list of entities with a known entity type, i.e. for
  878. * generic list of entities (list<entity>) this is FALSE.
  879. */
  880. protected $isEntityList;
  881. public function __construct($type, $data = NULL, $info = array()) {
  882. parent::__construct($type, NULL, $info);
  883. $this->itemType = entity_property_list_extract_type($this->type);
  884. if (!$this->itemType) {
  885. $this->itemType = 'unknown';
  886. }
  887. $this->isEntityList = (bool) entity_get_info($this->itemType);
  888. if (isset($data)) {
  889. $this->set($data);
  890. }
  891. }
  892. /**
  893. * Get the wrapper for a single item.
  894. *
  895. * @return
  896. * An instance of EntityMetadataWrapper.
  897. */
  898. public function get($delta) {
  899. // Look it up in the cache if possible.
  900. if (!array_key_exists($delta, $this->cache)) {
  901. if (!isset($delta)) {
  902. // The [] operator has been used so point at a new entry.
  903. $values = parent::value();
  904. $delta = $values ? max(array_keys($values)) + 1 : 0;
  905. }
  906. if (is_numeric($delta)) {
  907. $info = array('parent' => $this, 'name' => $delta) + $this->info;
  908. $this->cache[$delta] = entity_metadata_wrapper($this->itemType, NULL, $info);
  909. }
  910. else {
  911. throw new EntityMetadataWrapperException('There can be only numerical keyed items in a list.');
  912. }
  913. }
  914. return $this->cache[$delta];
  915. }
  916. protected function getPropertyValue($delta) {
  917. // Make use parent::value() to easily by-pass any entity-loading.
  918. $data = parent::value();
  919. if (isset($data[$delta])) {
  920. return $data[$delta];
  921. }
  922. }
  923. protected function getPropertyRaw($delta) {
  924. return $this->getPropertyValue($delta);
  925. }
  926. protected function setProperty($delta, $value) {
  927. $data = parent::value();
  928. if (is_numeric($delta)) {
  929. $data[$delta] = $value;
  930. $this->set($data);
  931. }
  932. }
  933. protected function propertyAccess($delta, $op, $account = NULL) {
  934. return $this->access($op, $account);
  935. }
  936. /**
  937. * Returns the list as numerically indexed array.
  938. *
  939. * Note that a list of entities might contain stale entity references. In
  940. * that case the wrapper and the identifier of a stale reference would be
  941. * still accessible, however the entity object value would be NULL. That way,
  942. * there may be NULL values in lists of entity objects due to stale entity
  943. * references.
  944. *
  945. * @param $options
  946. * An array of options. Known keys:
  947. * - identifier: If set to TRUE for a list of entities, it won't be returned
  948. * as list of fully loaded entity objects, but as a list of entity ids.
  949. * Note that this list may contain ids of stale entity references.
  950. */
  951. public function value(array $options = array()) {
  952. // For lists of entities fetch full entity objects before returning.
  953. // Generic entity-wrappers need to be handled separately though.
  954. if ($this->isEntityList && empty($options['identifier']) && $this->dataAvailable()) {
  955. $list = parent::value();
  956. $entities = $list ? entity_load($this->get(0)->type, $list) : array();
  957. // Make sure to keep the array keys as present in the list.
  958. foreach ($list as $key => $id) {
  959. // In case the entity cannot be loaded, we return NULL just as for empty
  960. // properties.
  961. $list[$key] = isset($entities[$id]) ? $entities[$id] : NULL;
  962. }
  963. return $list;
  964. }
  965. return parent::value();
  966. }
  967. public function set($values) {
  968. // Support setting lists of fully loaded entities.
  969. if ($this->isEntityList && $values && is_object(reset($values))) {
  970. foreach ($values as $key => $value) {
  971. // Ignore outdated NULL value references in lists of entities.
  972. if (isset($value)) {
  973. list($id, $vid, $bundle) = entity_extract_ids($this->itemType, $value);
  974. $values[$key] = $id;
  975. }
  976. }
  977. }
  978. return parent::set($values);
  979. }
  980. /**
  981. * If we wrap a list, we return an iterator over the data list.
  982. */
  983. public function getIterator() {
  984. // In case there is no data available, just iterate over the first item.
  985. return new EntityMetadataWrapperIterator($this, $this->dataAvailable() ? array_keys(parent::value()) : array(0));
  986. }
  987. /**
  988. * Implements the ArrayAccess interface.
  989. */
  990. public function offsetGet($delta) {
  991. return $this->get($delta);
  992. }
  993. public function offsetExists($delta) {
  994. return $this->dataAvailable() && ($data = $this->value()) && array_key_exists($delta, $data);
  995. }
  996. public function offsetSet($delta, $value) {
  997. $this->get($delta)->set($value);
  998. }
  999. public function offsetUnset($delta) {
  1000. if ($this->offsetExists($delta)) {
  1001. unset($this->data[$delta]);
  1002. $this->set($this->data);
  1003. }
  1004. }
  1005. public function count() {
  1006. return $this->dataAvailable() ? count($this->value()) : 0;
  1007. }
  1008. /**
  1009. * Overridden.
  1010. */
  1011. public function validate($value) {
  1012. // Required lists may not be empty or unset.
  1013. if (!empty($this->info['required']) && empty($value)) {
  1014. return FALSE;
  1015. }
  1016. return parent::validate($value);
  1017. }
  1018. /**
  1019. * Returns the label for the list of set values if available.
  1020. */
  1021. public function label() {
  1022. if ($options = $this->optionsList('view')) {
  1023. $options = entity_property_options_flatten($options);
  1024. $labels = array_intersect_key($options, array_flip((array) parent::value()));
  1025. }
  1026. else {
  1027. // Get each label on its own, e.g. to support getting labels of a list
  1028. // of entities.
  1029. $labels = array();
  1030. foreach ($this as $key => $property) {
  1031. $label = $property->label();
  1032. if (!$label) {
  1033. return NULL;
  1034. }
  1035. $labels[] = $label;
  1036. }
  1037. }
  1038. return isset($labels) ? implode(', ', $labels) : NULL;
  1039. }
  1040. }
  1041. /**
  1042. * Provide a separate Exception so it can be caught separately.
  1043. */
  1044. class EntityMetadataWrapperException extends Exception { }
  1045. /**
  1046. * Allows to easily iterate over existing child wrappers.
  1047. */
  1048. class EntityMetadataWrapperIterator implements RecursiveIterator {
  1049. protected $position = 0;
  1050. protected $wrapper, $keys;
  1051. public function __construct(EntityMetadataWrapper $wrapper, array $keys) {
  1052. $this->wrapper = $wrapper;
  1053. $this->keys = $keys;
  1054. }
  1055. function rewind() {
  1056. $this->position = 0;
  1057. }
  1058. function current() {
  1059. return $this->wrapper->get($this->keys[$this->position]);
  1060. }
  1061. function key() {
  1062. return $this->keys[$this->position];
  1063. }
  1064. function next() {
  1065. $this->position++;
  1066. }
  1067. function valid() {
  1068. return isset($this->keys[$this->position]);
  1069. }
  1070. public function hasChildren() {
  1071. return $this->current() instanceof IteratorAggregate;
  1072. }
  1073. public function getChildren() {
  1074. return $this->current()->getIterator();
  1075. }
  1076. }
  1077. /**
  1078. * An array object implementation keeping the reference on the given array so
  1079. * changes to the object are reflected in the passed array.
  1080. */
  1081. class EntityMetadataArrayObject implements ArrayAccess, Countable, IteratorAggregate {
  1082. protected $data;
  1083. public function __construct(&$array) {
  1084. $this->data =& $array;
  1085. }
  1086. public function &getArray() {
  1087. return $this->data;
  1088. }
  1089. /**
  1090. * Implements the ArrayAccess interface.
  1091. */
  1092. public function offsetGet($delta) {
  1093. return $this->data[$delta];
  1094. }
  1095. public function offsetExists($delta) {
  1096. return array_key_exists($delta, $this->data);
  1097. }
  1098. public function offsetSet($delta, $value) {
  1099. $this->data[$delta] = $value;
  1100. }
  1101. public function offsetUnset($delta) {
  1102. unset($this->data[$delta]);
  1103. }
  1104. public function count() {
  1105. return count($this->data);
  1106. }
  1107. public function getIterator() {
  1108. return new ArrayIterator($this->data);
  1109. }
  1110. }