entity.wrapper.inc 40 KB

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