entity.wrapper.inc 37 KB

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