rules.state.inc 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804
  1. <?php
  2. /**
  3. * @file
  4. * Contains the state and data related stuff.
  5. */
  6. /**
  7. * The rules evaluation state.
  8. *
  9. * A rule element may clone the state, so any added variables are only visible
  10. * for elements in the current PHP-variable-scope.
  11. */
  12. class RulesState {
  13. /**
  14. * Globally keeps the ids of rules blocked due to recursion prevention.
  15. *
  16. * @var array
  17. */
  18. static protected $blocked = array();
  19. /**
  20. * The known variables.
  21. *
  22. * @var array
  23. */
  24. public $variables = array();
  25. /**
  26. * Holds info about the variables.
  27. *
  28. * @var array
  29. */
  30. protected $info = array();
  31. /**
  32. * Keeps wrappers to be saved later on.
  33. */
  34. protected $save;
  35. /**
  36. * Holds the arguments while an element is executed.
  37. *
  38. * May be used by the element to easily access the wrapped arguments.
  39. */
  40. public $currentArguments;
  41. /**
  42. * Variable for saving currently blocked configs for serialization.
  43. */
  44. protected $currentlyBlocked;
  45. /**
  46. * Constructs a RulesState object.
  47. */
  48. public function __construct() {
  49. // Use an object in order to ensure any cloned states reference the same
  50. // save information.
  51. $this->save = new ArrayObject();
  52. $this->addVariable('site', FALSE, self::defaultVariables('site'));
  53. }
  54. /**
  55. * Adds the given variable to the given execution state.
  56. */
  57. public function addVariable($name, $data, $info) {
  58. $this->info[$name] = $info + array(
  59. 'skip save' => FALSE,
  60. 'type' => 'unknown',
  61. 'handler' => FALSE,
  62. );
  63. if (empty($this->info[$name]['handler'])) {
  64. $this->variables[$name] = rules_wrap_data($data, $this->info[$name]);
  65. }
  66. }
  67. /**
  68. * Runs post-evaluation tasks, such as saving variables.
  69. */
  70. public function cleanUp() {
  71. // Make changes permanent.
  72. foreach ($this->save->getArrayCopy() as $selector => $wrapper) {
  73. $this->saveNow($selector);
  74. }
  75. unset($this->currentArguments);
  76. }
  77. /**
  78. * Block a rules configuration from execution.
  79. */
  80. public function block($rules_config) {
  81. if (empty($rules_config->recursion) && $rules_config->id) {
  82. self::$blocked[$rules_config->id] = TRUE;
  83. }
  84. }
  85. /**
  86. * Unblock a rules configuration from execution.
  87. */
  88. public function unblock($rules_config) {
  89. if (empty($rules_config->recursion) && $rules_config->id) {
  90. unset(self::$blocked[$rules_config->id]);
  91. }
  92. }
  93. /**
  94. * Returns whether a rules configuration should be blocked from execution.
  95. */
  96. public function isBlocked($rule_config) {
  97. return !empty($rule_config->id) && isset(self::$blocked[$rule_config->id]);
  98. }
  99. /**
  100. * Get the info about the state variables or a single variable.
  101. */
  102. public function varInfo($name = NULL) {
  103. if (isset($name)) {
  104. return isset($this->info[$name]) ? $this->info[$name] : FALSE;
  105. }
  106. return $this->info;
  107. }
  108. /**
  109. * Returns whether the given wrapper is savable.
  110. */
  111. public function isSavable($wrapper) {
  112. return ($wrapper instanceof EntityDrupalWrapper && entity_type_supports($wrapper->type(), 'save')) || $wrapper instanceof RulesDataWrapperSavableInterface;
  113. }
  114. /**
  115. * Returns whether the variable with the given name is an entity.
  116. */
  117. public function isEntity($name) {
  118. $entity_info = entity_get_info();
  119. return isset($this->info[$name]['type']) && isset($entity_info[$this->info[$name]['type']]);
  120. }
  121. /**
  122. * Gets a variable.
  123. *
  124. * If necessary, the specified handler is invoked to fetch the variable.
  125. *
  126. * @param string $name
  127. * The name of the variable to return.
  128. *
  129. * @return
  130. * The variable or a EntityMetadataWrapper containing the variable.
  131. *
  132. * @throws RulesEvaluationException
  133. * Throws a RulesEvaluationException in case we have info about the
  134. * requested variable, but it is not defined.
  135. */
  136. public function &get($name) {
  137. if (!array_key_exists($name, $this->variables)) {
  138. // If there is handler to load the variable, do it now.
  139. if (!empty($this->info[$name]['handler'])) {
  140. $data = call_user_func($this->info[$name]['handler'], rules_unwrap_data($this->variables), $name, $this->info[$name]);
  141. $this->variables[$name] = rules_wrap_data($data, $this->info[$name]);
  142. $this->info[$name]['handler'] = FALSE;
  143. if (!isset($data)) {
  144. throw new RulesEvaluationException('Unable to load variable %name, aborting.', array('%name' => $name), NULL, RulesLog::INFO);
  145. }
  146. }
  147. else {
  148. throw new RulesEvaluationException('Unable to get variable %name, it is not defined.', array('%name' => $name), NULL, RulesLog::ERROR);
  149. }
  150. }
  151. return $this->variables[$name];
  152. }
  153. /**
  154. * Apply permanent changes provided the wrapper's data type is savable.
  155. *
  156. * @param $selector
  157. * The data selector of the wrapper to save or just a variable name.
  158. * @param $wrapper
  159. * @param bool $immediate
  160. * Pass FALSE to postpone saving to later on. Else it's immediately saved.
  161. */
  162. public function saveChanges($selector, $wrapper, $immediate = FALSE) {
  163. $info = $wrapper->info();
  164. if (empty($info['skip save']) && $this->isSavable($wrapper)) {
  165. $this->save($selector, $wrapper, $immediate);
  166. }
  167. // No entity, so try saving the parent.
  168. elseif (empty($info['skip save']) && isset($info['parent']) && !($wrapper instanceof EntityDrupalWrapper)) {
  169. // Cut of the last part of the selector.
  170. $selector = implode(':', explode(':', $selector, -1));
  171. $this->saveChanges($selector, $info['parent'], $immediate);
  172. }
  173. return $this;
  174. }
  175. /**
  176. * Remembers to save the wrapper on cleanup or does it now.
  177. */
  178. protected function save($selector, EntityMetadataWrapper $wrapper, $immediate) {
  179. // Convert variable names and selectors to both use underscores.
  180. $selector = strtr($selector, '-', '_');
  181. if (isset($this->save[$selector])) {
  182. if ($this->save[$selector][0]->getIdentifier() == $wrapper->getIdentifier()) {
  183. // The entity is already remembered. So do a combined save.
  184. $this->save[$selector][1] += self::$blocked;
  185. }
  186. else {
  187. // The wrapper is already in there, but wraps another entity. So first
  188. // save the old one, then care about the new one.
  189. $this->saveNow($selector);
  190. }
  191. }
  192. if (!isset($this->save[$selector])) {
  193. // In case of immediate saving don't clone the wrapper, so saving a new
  194. // entity immediately makes the identifier available afterwards.
  195. $this->save[$selector] = array($immediate ? $wrapper : clone $wrapper, self::$blocked);
  196. }
  197. if ($immediate) {
  198. $this->saveNow($selector);
  199. }
  200. }
  201. /**
  202. * Saves the wrapper for the given selector.
  203. */
  204. protected function saveNow($selector) {
  205. // Add the set of blocked elements for the recursion prevention.
  206. $previously_blocked = self::$blocked;
  207. self::$blocked += $this->save[$selector][1];
  208. // Actually save!
  209. $wrapper = $this->save[$selector][0];
  210. $entity = $wrapper->value();
  211. // When operating in hook_entity_insert() $entity->is_new might be still
  212. // set. In that case remove the flag to avoid causing another insert instead
  213. // of an update.
  214. if (!empty($entity->is_new) && $wrapper->getIdentifier()) {
  215. $entity->is_new = FALSE;
  216. }
  217. rules_log('Saved %selector of type %type.', array('%selector' => $selector, '%type' => $wrapper->type()));
  218. $wrapper->save();
  219. // Restore the state's set of blocked elements.
  220. self::$blocked = $previously_blocked;
  221. unset($this->save[$selector]);
  222. }
  223. /**
  224. * Merges info from the given state into the existing state.
  225. *
  226. * Merges the info about to-be-saved variables from the given state into the
  227. * existing state. Therefore we can aggregate saves from invoked components.
  228. * Merged-in saves are removed from the given state, but not-mergeable saves
  229. * remain there.
  230. *
  231. * @param $state
  232. * The state for which to merge the to be saved variables in.
  233. * @param $component
  234. * The component which has been invoked, thus needs to be blocked for the
  235. * merged in saves.
  236. * @param $settings
  237. * The settings of the element that invoked the component. Contains
  238. * information about variable/selector mappings between the states.
  239. */
  240. public function mergeSaveVariables(RulesState $state, RulesPlugin $component, $settings) {
  241. // For any saves that we take over, also block the component.
  242. $this->block($component);
  243. foreach ($state->save->getArrayCopy() as $selector => $data) {
  244. $parts = explode(':', $selector, 2);
  245. // Adapt the selector to fit for the parent state and move the wrapper.
  246. if (isset($settings[$parts[0] . ':select'])) {
  247. $parts[0] = $settings[$parts[0] . ':select'];
  248. $this->save(implode(':', $parts), $data[0], FALSE);
  249. unset($state->save[$selector]);
  250. }
  251. }
  252. $this->unblock($component);
  253. }
  254. /**
  255. * Returns an entity metadata wrapper as specified in the selector.
  256. *
  257. * @param string $selector
  258. * The selector string, e.g. "node:author:mail".
  259. * @param string $langcode
  260. * (optional) The language code used to get the argument value if the
  261. * argument value should be translated. Defaults to LANGUAGE_NONE.
  262. *
  263. * @return EntityMetadataWrapper
  264. * The wrapper for the given selector.
  265. *
  266. * @throws RulesEvaluationException
  267. * Throws a RulesEvaluationException in case the selector cannot be applied.
  268. */
  269. public function applyDataSelector($selector, $langcode = LANGUAGE_NONE) {
  270. $parts = explode(':', str_replace('-', '_', $selector), 2);
  271. $wrapper = $this->get($parts[0]);
  272. if (count($parts) == 1) {
  273. return $wrapper;
  274. }
  275. elseif (!$wrapper instanceof EntityMetadataWrapper) {
  276. throw new RulesEvaluationException('Unable to apply data selector %selector. The specified variable is not wrapped correctly.', array('%selector' => $selector));
  277. }
  278. try {
  279. foreach (explode(':', $parts[1]) as $name) {
  280. if ($wrapper instanceof EntityListWrapper || $wrapper instanceof EntityStructureWrapper) {
  281. // Make sure we are using the right language. Wrappers might be cached
  282. // and have previous langcodes set, so always set the right language.
  283. if ($wrapper instanceof EntityStructureWrapper) {
  284. $wrapper->language($langcode);
  285. }
  286. $wrapper = $wrapper->get($name);
  287. }
  288. else {
  289. throw new RulesEvaluationException('Unable to apply data selector %selector. The specified variable is not a list or a structure: %wrapper.', array('%selector' => $selector, '%wrapper' => $wrapper));
  290. }
  291. }
  292. }
  293. catch (EntityMetadataWrapperException $e) {
  294. // In case of an exception, re-throw it.
  295. throw new RulesEvaluationException('Unable to apply data selector %selector: %error', array('%selector' => $selector, '%error' => $e->getMessage()));
  296. }
  297. return $wrapper;
  298. }
  299. /**
  300. * Magic method. Only serialize variables and their info.
  301. *
  302. * Additionally we remember currently blocked configs, so we can restore them
  303. * upon deserialization using restoreBlocks().
  304. */
  305. public function __sleep() {
  306. $this->currentlyBlocked = self::$blocked;
  307. return array('info', 'variables', 'currentlyBlocked');
  308. }
  309. /**
  310. * Magic method. Unserialize variables and their info.
  311. */
  312. public function __wakeup() {
  313. $this->save = new ArrayObject();
  314. }
  315. /**
  316. * Restores the before-serialization blocked configurations.
  317. *
  318. * Warning: This overwrites any possible currently blocked configs. Thus
  319. * do not invoke this method if there might be evaluations active.
  320. */
  321. public function restoreBlocks() {
  322. self::$blocked = $this->currentlyBlocked;
  323. }
  324. /**
  325. * Defines always-available variables.
  326. *
  327. * @param $key
  328. * (optional)
  329. */
  330. public static function defaultVariables($key = NULL) {
  331. // Add a variable for accessing site-wide data properties.
  332. $vars['site'] = array(
  333. 'type' => 'site',
  334. 'label' => t('Site information'),
  335. 'description' => t("Site-wide settings and other global information."),
  336. // Add the property info via a callback making use of the cached info.
  337. 'property info alter' => array('RulesData', 'addSiteMetadata'),
  338. 'property info' => array(),
  339. 'optional' => TRUE,
  340. );
  341. return isset($key) ? $vars[$key] : $vars;
  342. }
  343. }
  344. /**
  345. * A class holding static methods related to data.
  346. */
  347. class RulesData {
  348. /**
  349. * Returns whether the type match. They match if type1 is compatible to type2.
  350. *
  351. * @param $var_info
  352. * The name of the type to check for whether it is compatible to type2.
  353. * @param $param_info
  354. * The type expression to check for.
  355. * @param bool $ancestors
  356. * (optional) Whether sub-type relationships for checking type compatibility
  357. * should be taken into account. Defaults to TRUE.
  358. *
  359. * @return bool
  360. * Whether the types match.
  361. */
  362. public static function typesMatch($var_info, $param_info, $ancestors = TRUE) {
  363. $var_type = $var_info['type'];
  364. $param_type = $param_info['type'];
  365. if ($param_type == '*' || $param_type == 'unknown') {
  366. return TRUE;
  367. }
  368. if ($var_type == $param_type) {
  369. // Make sure the bundle matches, if specified by the parameter.
  370. return !isset($param_info['bundles']) || isset($var_info['bundle']) && in_array($var_info['bundle'], $param_info['bundles']);
  371. }
  372. // Parameters may specify multiple types using an array.
  373. $valid_types = is_array($param_type) ? $param_type : array($param_type);
  374. if (in_array($var_type, $valid_types)) {
  375. return TRUE;
  376. }
  377. // Check for sub-type relationships.
  378. if ($ancestors && !isset($param_info['bundles'])) {
  379. $cache = &rules_get_cache();
  380. self::typeCalcAncestors($cache, $var_type);
  381. // If one of the types is an ancestor return TRUE.
  382. return (bool) array_intersect_key($cache['data_info'][$var_type]['ancestors'], array_flip($valid_types));
  383. }
  384. return FALSE;
  385. }
  386. protected static function typeCalcAncestors(&$cache, $type) {
  387. if (!isset($cache['data_info'][$type]['ancestors'])) {
  388. $cache['data_info'][$type]['ancestors'] = array();
  389. if (isset($cache['data_info'][$type]['parent']) && $parent = $cache['data_info'][$type]['parent']) {
  390. $cache['data_info'][$type]['ancestors'][$parent] = TRUE;
  391. self::typeCalcAncestors($cache, $parent);
  392. // Add all parent ancestors to our own ancestors.
  393. $cache['data_info'][$type]['ancestors'] += $cache['data_info'][$parent]['ancestors'];
  394. }
  395. // For special lists like list<node> add in "list" as valid parent.
  396. if (entity_property_list_extract_type($type)) {
  397. $cache['data_info'][$type]['ancestors']['list'] = TRUE;
  398. }
  399. }
  400. }
  401. /**
  402. * Returns data for the given info and the to-be-configured parameter.
  403. *
  404. * Returns matching data variables or properties for the given info and the
  405. * to-be-configured parameter.
  406. *
  407. * @param $source
  408. * Either an array of info about available variables or a entity metadata
  409. * wrapper.
  410. * @param $param_info
  411. * The information array about the to be configured parameter.
  412. * @param string $prefix
  413. * An optional prefix for the data selectors.
  414. * @param int $recursions
  415. * The number of recursions used to go down the tree. Defaults to 2.
  416. * @param bool $suggestions
  417. * Whether possibilities to recurse are suggested as soon as the deepest
  418. * level of recursions is reached. Defaults to TRUE.
  419. *
  420. * @return array
  421. * An array of info about matching variables or properties that match, keyed
  422. * with the data selector.
  423. */
  424. public static function matchingDataSelector($source, $param_info, $prefix = '', $recursions = 2, $suggestions = TRUE) {
  425. // If an array of info is given, get entity metadata wrappers first.
  426. $data = NULL;
  427. if (is_array($source)) {
  428. foreach ($source as $name => $info) {
  429. $source[$name] = rules_wrap_data($data, $info, TRUE);
  430. }
  431. }
  432. $matches = array();
  433. foreach ($source as $name => $wrapper) {
  434. $info = $wrapper->info();
  435. $name = str_replace('_', '-', $name);
  436. if (self::typesMatch($info, $param_info)) {
  437. $matches[$prefix . $name] = $info;
  438. if (!is_array($source) && $source instanceof EntityListWrapper) {
  439. // Add some more possible list items.
  440. for ($i = 1; $i < 4; $i++) {
  441. $matches[$prefix . $i] = $info;
  442. }
  443. }
  444. }
  445. // Recurse later on to get an improved ordering of the results.
  446. if ($wrapper instanceof EntityStructureWrapper || $wrapper instanceof EntityListWrapper) {
  447. $recurse[$prefix . $name] = $wrapper;
  448. if ($recursions > 0) {
  449. $matches += self::matchingDataSelector($wrapper, $param_info, $prefix . $name . ':', $recursions - 1, $suggestions);
  450. }
  451. elseif ($suggestions) {
  452. // We may not recurse any more,
  453. // but indicate the possibility to recurse.
  454. $matches[$prefix . $name . ':'] = $wrapper->info();
  455. if (!is_array($source) && $source instanceof EntityListWrapper) {
  456. // Add some more possible list items.
  457. for ($i = 1; $i < 4; $i++) {
  458. $matches[$prefix . $i . ':'] = $wrapper->info();
  459. }
  460. }
  461. }
  462. }
  463. }
  464. return $matches;
  465. }
  466. /**
  467. * Adds asserted metadata to the variable info.
  468. *
  469. * In case there are already assertions for a variable, the assertions are
  470. * merged such that both apply.
  471. *
  472. * @see RulesData::applyMetadataAssertions()
  473. */
  474. public static function addMetadataAssertions($var_info, $assertions) {
  475. foreach ($assertions as $selector => $assertion) {
  476. // Convert the selector back to underscores, such it matches the varname.
  477. $selector = str_replace('-', '_', $selector);
  478. $parts = explode(':', $selector);
  479. if (isset($var_info[$parts[0]])) {
  480. // Apply the selector to determine the right target array. We build an
  481. // array like
  482. // $var_info['rules assertion']['property1']['property2']['#info'] = ..
  483. $target = &$var_info[$parts[0]]['rules assertion'];
  484. foreach (array_slice($parts, 1) as $part) {
  485. $target = &$target[$part];
  486. }
  487. // In case the assertion is directly for a variable, we have to modify
  488. // the variable info directly. In case the asserted property is nested
  489. // the info-has to be altered by RulesData::applyMetadataAssertions()
  490. // before the child-wrapper is created.
  491. if (count($parts) == 1) {
  492. // Support asserting a type in case of generic entity references only.
  493. $var_type = &$var_info[$parts[0]]['type'];
  494. if (isset($assertion['type']) && ($var_type == 'entity' || $var_type == 'list<entity>')) {
  495. $var_type = $assertion['type'];
  496. unset($assertion['type']);
  497. }
  498. // Add any single bundle directly to the variable info, so the
  499. // variable fits as argument for parameters requiring the bundle.
  500. if (isset($assertion['bundle']) && count($bundles = (array) $assertion['bundle']) == 1) {
  501. $var_info[$parts[0]]['bundle'] = reset($bundles);
  502. }
  503. }
  504. // Add the assertions, but merge them with any previously added
  505. // assertions if necessary.
  506. $target['#info'] = isset($target['#info']) ? rules_update_array($target['#info'], $assertion) : $assertion;
  507. // Add in a callback that the entity metadata wrapper pick up for
  508. // altering the property info, such that we can add in the assertions.
  509. $var_info[$parts[0]] += array('property info alter' => array('RulesData', 'applyMetadataAssertions'));
  510. // In case there is a VARNAME_unchanged variable as it is used in update
  511. // hooks, assume the assertions are valid for the unchanged variable
  512. // too.
  513. if (isset($var_info[$parts[0] . '_unchanged'])) {
  514. $name = $parts[0] . '_unchanged';
  515. $var_info[$name]['rules assertion'] = $var_info[$parts[0]]['rules assertion'];
  516. $var_info[$name]['property info alter'] = array('RulesData', 'applyMetadataAssertions');
  517. if (isset($var_info[$parts[0]]['bundle']) && !isset($var_info[$name]['bundle'])) {
  518. $var_info[$name]['bundle'] = $var_info[$parts[0]]['bundle'];
  519. }
  520. }
  521. }
  522. }
  523. return $var_info;
  524. }
  525. /**
  526. * Property info alter callback for the entity metadata wrapper.
  527. *
  528. * Used for applying the rules metadata assertions.
  529. *
  530. * @see RulesData::addMetadataAssertions()
  531. */
  532. public static function applyMetadataAssertions(EntityMetadataWrapper $wrapper, $property_info) {
  533. $info = $wrapper->info();
  534. if (!empty($info['rules assertion'])) {
  535. $assertion = $info['rules assertion'];
  536. // In case there are list-wrappers pass through the assertions of the item
  537. // but make sure we only apply the assertions for the list items for
  538. // which the conditions are executed.
  539. if (isset($info['parent']) && $info['parent'] instanceof EntityListWrapper) {
  540. $assertion = isset($assertion[$info['name']]) ? $assertion[$info['name']] : array();
  541. }
  542. // Support specifying multiple bundles, whereas the added properties are
  543. // the intersection of the bundle properties.
  544. if (isset($assertion['#info']['bundle'])) {
  545. $bundles = (array) $assertion['#info']['bundle'];
  546. foreach ($bundles as $bundle) {
  547. $properties[] = isset($property_info['bundles'][$bundle]['properties']) ? $property_info['bundles'][$bundle]['properties'] : array();
  548. }
  549. // Add the intersection.
  550. $property_info['properties'] += count($properties) > 1 ? call_user_func_array('array_intersect_key', $properties) : reset($properties);
  551. }
  552. // Support adding directly asserted property info.
  553. if (isset($assertion['#info']['property info'])) {
  554. $property_info['properties'] += $assertion['#info']['property info'];
  555. }
  556. // Pass through any rules assertion of properties to their info, so any
  557. // derived wrappers apply it.
  558. foreach (element_children($assertion) as $key) {
  559. $property_info['properties'][$key]['rules assertion'] = $assertion[$key];
  560. $property_info['properties'][$key]['property info alter'] = array('RulesData', 'applyMetadataAssertions');
  561. // Apply any 'type' and 'bundle' assertion directly to the property
  562. // info.
  563. if (isset($assertion[$key]['#info']['type'])) {
  564. $type = $assertion[$key]['#info']['type'];
  565. // Support asserting a type in case of generic entity references only.
  566. if ($property_info['properties'][$key]['type'] == 'entity' && entity_get_info($type)) {
  567. $property_info['properties'][$key]['type'] = $type;
  568. }
  569. }
  570. if (isset($assertion[$key]['#info']['bundle'])) {
  571. $bundle = (array) $assertion[$key]['#info']['bundle'];
  572. // Add any single bundle directly to the variable info, so the
  573. // property fits as argument for parameters requiring the bundle.
  574. if (count($bundle) == 1) {
  575. $property_info['properties'][$key]['bundle'] = reset($bundle);
  576. }
  577. }
  578. }
  579. }
  580. return $property_info;
  581. }
  582. /**
  583. * Property info alter callback for the entity metadata wrapper.
  584. *
  585. * Used to inject metadata for the 'site' variable. In contrast to doing this
  586. * via hook_rules_data_info() this callback makes use of the already existing
  587. * property info cache for site information of entity metadata.
  588. *
  589. * @see RulesPlugin::availableVariables()
  590. */
  591. public static function addSiteMetadata(EntityMetadataWrapper $wrapper, $property_info) {
  592. $site_info = entity_get_property_info('site');
  593. $property_info['properties'] += $site_info['properties'];
  594. // Also invoke the usual callback for altering metadata, in case actions
  595. // have specified further metadata.
  596. return RulesData::applyMetadataAssertions($wrapper, $property_info);
  597. }
  598. }
  599. /**
  600. * A wrapper class similar to the EntityDrupalWrapper, but for non-entities.
  601. *
  602. * This class is intended to serve as base for a custom wrapper classes of
  603. * identifiable data types, which are non-entities. By extending this class only
  604. * the extractIdentifier() and load() methods have to be defined.
  605. * In order to make the data type savable implement the
  606. * RulesDataWrapperSavableInterface.
  607. *
  608. * That way it is possible for non-entity data types to be work with Rules, i.e.
  609. * one can implement a 'ui class' with a direct input form returning the
  610. * identifier of the data. However, instead of that it is suggested to implement
  611. * an entity type, such that the same is achieved via general API functions like
  612. * entity_load().
  613. */
  614. abstract class RulesIdentifiableDataWrapper extends EntityStructureWrapper {
  615. /**
  616. * Contains the id.
  617. */
  618. protected $id = FALSE;
  619. /**
  620. * Construct a new wrapper object.
  621. *
  622. * @param $type
  623. * The type of the passed data.
  624. * @param $data
  625. * Optional. The data to wrap or its identifier.
  626. * @param array $info
  627. * Optional. Used internally to pass info about properties down the tree.
  628. */
  629. public function __construct($type, $data = NULL, $info = array()) {
  630. parent::__construct($type, $data, $info);
  631. $this->setData($data);
  632. }
  633. /**
  634. * Sets the data internally accepting both the data id and object.
  635. */
  636. protected function setData($data) {
  637. if (isset($data) && $data !== FALSE && !is_object($data)) {
  638. $this->id = $data;
  639. $this->data = FALSE;
  640. }
  641. elseif (is_object($data)) {
  642. // We got the data object passed.
  643. $this->data = $data;
  644. $id = $this->extractIdentifier($data);
  645. $this->id = isset($id) ? $id : FALSE;
  646. }
  647. }
  648. /**
  649. * Returns the identifier of the wrapped data.
  650. */
  651. public function getIdentifier() {
  652. return $this->dataAvailable() && $this->value() ? $this->id : NULL;
  653. }
  654. /**
  655. * Overridden.
  656. */
  657. public function value(array $options = array()) {
  658. $this->setData(parent::value());
  659. if (!$this->data && !empty($this->id)) {
  660. // Lazy load the data if necessary.
  661. $this->data = $this->load($this->id);
  662. if (!$this->data) {
  663. throw new EntityMetadataWrapperException('Unable to load the ' . check_plain($this->type) . ' with the id ' . check_plain($this->id) . '.');
  664. }
  665. }
  666. return $this->data;
  667. }
  668. /**
  669. * Overridden to support setting the data by either the object or the id.
  670. */
  671. public function set($value) {
  672. if (!$this->validate($value)) {
  673. throw new EntityMetadataWrapperException('Invalid data value given. Be sure it matches the required data type and format.');
  674. }
  675. // As custom wrapper classes can only appear for Rules variables, but not
  676. // as properties we don't have to care about updating the parent.
  677. $this->clear();
  678. $this->setData($value);
  679. return $this;
  680. }
  681. /**
  682. * Overridden.
  683. */
  684. public function clear() {
  685. $this->id = NULL;
  686. parent::clear();
  687. }
  688. /**
  689. * Prepare for serialization.
  690. */
  691. public function __sleep() {
  692. $vars = parent::__sleep();
  693. // Don't serialize the loaded data, except for the case the data is not
  694. // saved yet.
  695. if (!empty($this->id)) {
  696. unset($vars['data']);
  697. }
  698. return $vars;
  699. }
  700. /**
  701. * Prepare for unserialization.
  702. */
  703. public function __wakeup() {
  704. if ($this->id !== FALSE) {
  705. // Make sure data is set, so the data will be loaded when needed.
  706. $this->data = FALSE;
  707. }
  708. }
  709. /**
  710. * Extract the identifier of the given data object.
  711. *
  712. * @return
  713. * The extracted identifier.
  714. */
  715. abstract protected function extractIdentifier($data);
  716. /**
  717. * Load a data object given an identifier.
  718. *
  719. * @return
  720. * The loaded data object, or FALSE if loading failed.
  721. */
  722. abstract protected function load($id);
  723. }
  724. /**
  725. * Used to declare custom wrapper classes as savable.
  726. */
  727. interface RulesDataWrapperSavableInterface {
  728. /**
  729. * Save the currently wrapped data.
  730. */
  731. public function save();
  732. }