handler.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. <?php
  2. /**
  3. * @file
  4. * Contains base code for CER handlers, which are objects responsible for
  5. * creating, updating and deleting corresponding references between entities.
  6. */
  7. /**
  8. * Exception related to CER operations.
  9. */
  10. class CerException extends Exception {
  11. }
  12. interface CerHandlerInterface {
  13. /**
  14. * @constructor
  15. *
  16. * @param string $preset
  17. * The CER preset string, in the format:
  18. * entity_a*bundle_a*field_a*entity_b*bundle_b*field_b.
  19. *
  20. * @param $entity.
  21. * The local (home) entity to be wrapped by this instance.
  22. */
  23. public function __construct($preset, $entity);
  24. /**
  25. * Create reciprocal references on referenced entities after the
  26. * local entity has been created.
  27. */
  28. public function insert();
  29. /**
  30. * Delete reciprocal references on entities the local entity is no
  31. * longer referencing, and create new reciprocal references, after
  32. * the local entity has been updated.
  33. */
  34. public function update();
  35. /**
  36. * Delete all reciprocal references after the local entity is deleted.
  37. */
  38. public function delete();
  39. /**
  40. * Check if $entity is referenced by the local entity.
  41. *
  42. * @param object $entity
  43. * The remote entity.
  44. *
  45. * @return boolean
  46. */
  47. public function references($entity);
  48. /**
  49. * Check if the local entity is referenced by $entity.
  50. *
  51. * @param object $entity
  52. * The remote entiy.
  53. *
  54. * @return boolean
  55. */
  56. public function referencedBy($entity);
  57. /**
  58. * Check if the remote entity can reference the local entity, and vice-versa.
  59. *
  60. * @param object $entity
  61. * The remote entity.
  62. *
  63. * @return boolean
  64. */
  65. public function referenceable($entity);
  66. /**
  67. * Create a reference to the local entity on the remote entity, and vice-versa
  68. * if needed. Should throw CerException if the reference(s) can't be created
  69. * for any reason.
  70. *
  71. * @param object $entity
  72. */
  73. public function reference($entity);
  74. /**
  75. * Delete all references to the remote entity from the local entity,
  76. * and delete reciprocal references from the remote entity.
  77. *
  78. * @param object $entity.
  79. */
  80. public function dereference($entity);
  81. }
  82. /**
  83. * @class
  84. * Base class for CER handlers. All this does is parse the preset
  85. * and store instance info about the local and remote fields.
  86. */
  87. abstract class CerHandlerBase {
  88. /**
  89. * Local field instance definition.
  90. */
  91. protected $local;
  92. /**
  93. * Remote field instance definition.
  94. */
  95. protected $remote;
  96. public function __construct($preset) {
  97. $keys = explode('*', $preset);
  98. if (sizeof($keys) != 6) {
  99. throw new CerException(t('Invalid configuration: @preset', array('@preset' => $preset)));
  100. }
  101. $this->local = field_info_instance($keys[0], $keys[2], $keys[1]);
  102. if ($this->local) {
  103. $this->local['field'] = field_info_field($keys[2]);
  104. }
  105. else {
  106. throw new CerException(t('Local field instance does not exist.'));
  107. }
  108. $this->remote = field_info_instance($keys[3], $keys[5], $keys[4]);
  109. if ($this->remote) {
  110. $this->remote['field'] = field_info_field($keys[5]);
  111. }
  112. else {
  113. throw new CerException(t('Remote field instance does not exist.'));
  114. }
  115. }
  116. }
  117. /**
  118. * @class
  119. * Generic CER handler with rudimentary language handling.
  120. */
  121. class CerHandler extends CerHandlerBase implements CerHandlerInterface {
  122. /**
  123. * The local (home) entity.
  124. */
  125. protected $entity;
  126. /**
  127. * The local entity's ID.
  128. */
  129. protected $id;
  130. /**
  131. * Implements CerHandlerInterface::__construct().
  132. */
  133. public function __construct($preset, $entity) {
  134. parent::__construct($preset);
  135. // If $entity is of the wrong type, entity_extract_IDs()
  136. // will throw EntityMalformedException here.
  137. $extract_ids = entity_extract_IDs($this->local['entity_type'], $entity);
  138. $this->id = array_shift($extract_ids);
  139. $this->entity = $entity;
  140. }
  141. /**
  142. * Implements CerHandlerInterface::insert().
  143. */
  144. public function insert($ids = NULL) {
  145. if (empty($ids)) {
  146. $entities = $this->getReferencedEntities();
  147. }
  148. else {
  149. $entities = entity_load($this->remote['entity_type'], $ids);
  150. }
  151. foreach ($entities as $referenced_entity) {
  152. $this->reference($referenced_entity);
  153. _cer_update($this->remote['entity_type'], $referenced_entity);
  154. }
  155. }
  156. /**
  157. * Implements CerHandlerInterface::update().
  158. */
  159. public function update() {
  160. $original = isset($this->entity->original) ? $this->entity->original : $this->entity;
  161. $deleted = array_diff($this->getReferenceIDs($original, $this->local), $this->getLocalReferenceIDs());
  162. if ($deleted) {
  163. $entities = entity_load($this->remote['entity_type'], $deleted);
  164. foreach ($entities as $referenced_entity) {
  165. $this->dereference($referenced_entity);
  166. _cer_update($this->remote['entity_type'], $referenced_entity);
  167. }
  168. }
  169. $added = array_diff($this->getLocalReferenceIDs(), $this->getReferenceIDs($original, $this->local));
  170. if (!empty($added)) {
  171. $this->insert($added);
  172. }
  173. }
  174. /**
  175. * Implements CerHandlerInterface::delete().
  176. */
  177. public function delete() {
  178. foreach ($this->getReferencedEntities() as $referenced_entity) {
  179. $this->dereference($referenced_entity);
  180. _cer_update($this->remote['entity_type'], $referenced_entity);
  181. }
  182. }
  183. /**
  184. * Implements CerHandlerInterface::references().
  185. */
  186. public function references($entity) {
  187. return in_array($this->getRemoteEntityID($entity), $this->getLocalReferenceIDs());
  188. }
  189. /**
  190. * Implements CerHandlerInterface::referencedBy().
  191. */
  192. public function referencedBy($entity) {
  193. return in_array($this->id, $this->getRemoteReferenceIDs($entity));
  194. }
  195. /**
  196. * Implements CerHandlerInterface::referenceable().
  197. */
  198. public function referenceable($entity) {
  199. $id = $this->getRemoteEntityID($entity);
  200. $allowed = array(
  201. entityreference_get_selection_handler(
  202. $this->local['field'],
  203. $this->local,
  204. $this->local['entity_type'],
  205. $this->entity
  206. )
  207. ->validateReferencableEntities(array($id)),
  208. entityreference_get_selection_handler(
  209. $this->remote['field'],
  210. $this->remote,
  211. $this->remote['entity_type'],
  212. $entity
  213. )
  214. ->validateReferencableEntities(array($this->id)),
  215. );
  216. return in_array($id, $allowed[0]) && in_array($this->id, $allowed[1]);
  217. }
  218. /**
  219. * Implements CerHandlerInterface::reference().
  220. */
  221. public function reference($entity) {
  222. if ($this->referenceable($entity)) {
  223. try {
  224. $this->addReferenceTo($entity);
  225. }
  226. catch (CerException $e) {
  227. // Fail silently
  228. }
  229. try {
  230. $this->addReferenceFrom($entity);
  231. }
  232. catch (CerException $e) {
  233. // Fail silently
  234. }
  235. }
  236. else {
  237. $variables = array(
  238. '!local_field' => $this->local['field_name'],
  239. '!local_type' => $this->local['entity_type'],
  240. '!local_id' => $this->id,
  241. '!remote_field' => $this->remote['field_name'],
  242. '!remote_type' => $this->remote['entity_type'],
  243. '!remote_id' => $this->getRemoteEntityID($entity),
  244. );
  245. watchdog('cer', 'Failed to reference !remote_field on !remote_type !remote_id from !local_field on !local_type !local_id.', $variables, WATCHDOG_ERROR);
  246. }
  247. }
  248. /**
  249. * Implements CerHandlerInterface::dereference().
  250. */
  251. public function dereference($entity) {
  252. if ($this->references($entity)) {
  253. $id = $this->getRemoteEntityID($entity);
  254. foreach ($this->entity->{$this->local['field_name']} as $language => $references) {
  255. foreach ($references as $delta => $reference) {
  256. if ($reference['target_id'] == $id) {
  257. unset($this->entity->{$this->local['field_name']}[$language][$delta]);
  258. }
  259. }
  260. }
  261. }
  262. if ($this->referencedBy($entity)) {
  263. foreach ($entity->{$this->remote['field_name']} as $language => $references) {
  264. foreach ($references as $delta => $reference) {
  265. if ($reference['target_id'] == $this->id) {
  266. unset($entity->{$this->remote['field_name']}[$language][$delta]);
  267. }
  268. }
  269. }
  270. }
  271. }
  272. /**
  273. * Creates a reference to the local entity on the remote entity. Throws CerException
  274. * if the local entity is already referenced by the remote entity, or if the remote
  275. * field cannot hold any more values.
  276. *
  277. * @param object $entity
  278. * The remote entity.
  279. */
  280. protected function addReferenceFrom($entity) {
  281. if ($this->referencedBy($entity)) {
  282. throw new CerException(t('Cannot create duplicate reference from remote entity.'));
  283. }
  284. elseif ($this->filled($this->getRemoteReferenceIDs($entity), $this->remote['field'])) {
  285. throw new CerException(t('Remote field cannot support any more references.'));
  286. }
  287. else {
  288. $languages = field_available_languages($this->remote['entity_type'], $this->remote['field']);
  289. foreach ($languages as $language) {
  290. $entity->{$this->remote['field_name']}[$language][] = array('target_id' => $this->id);
  291. }
  292. }
  293. }
  294. /**
  295. * Creates a reference to the remote entity on the local entity. Throws CerException
  296. * if the local entity already references the remote entity, or if the field cannot
  297. * hold any more values.
  298. *
  299. * @param object $entity
  300. * The remote entity.
  301. */
  302. protected function addReferenceTo($entity) {
  303. $id = $this->getRemoteEntityID($entity);
  304. if ($this->references($entity)) {
  305. throw new CerException(t('Cannot create duplicate reference to remote entity.'));
  306. }
  307. elseif ($this->filled($this->getLocalReferenceIDs(), $this->local['field'])) {
  308. throw new CerException(t('Local field cannot support any more references.'));
  309. }
  310. else {
  311. $languages = field_available_languages($this->local['entity_type'], $this->local['field']);
  312. foreach ($languages as $language) {
  313. $this->entity->{$this->local['field_name']}[$language][] = array('target_id' => $id);
  314. }
  315. }
  316. }
  317. /**
  318. * Get the ID of the remote entity. If the entity is of the wrong type,
  319. * EntityMalformedException will be thrown.
  320. *
  321. * @param object $entity
  322. * The remote entity.
  323. *
  324. * @return mixed
  325. * The remote entity ID.
  326. */
  327. protected function getRemoteEntityID($entity) {
  328. $extract_ids = entity_extract_IDs($this->remote['entity_type'], $entity);
  329. return array_shift($extract_ids);
  330. }
  331. /**
  332. * Gets all the entities referenced by the local entity.
  333. *
  334. * @return array
  335. * Array of fully loaded referenced entities keyed by ID, or empty
  336. * array if nothing has been referenced.
  337. */
  338. protected function getReferencedEntities() {
  339. $IDs = $this->getLocalReferenceIDs();
  340. return $IDs ? entity_load($this->remote['entity_type'], $IDs) : array();
  341. }
  342. /**
  343. * Gets the IDs of the entities referenced by the local entity.
  344. *
  345. * @return array
  346. * Array of entity IDs, empty array if there are no references.
  347. */
  348. protected function getLocalReferenceIDs() {
  349. return $this->getReferenceIDs($this->entity, $this->local);
  350. }
  351. /**
  352. * Gets the IDs of the entities referenced by $entity.
  353. *
  354. * @param object $entity
  355. * The remote entity.
  356. *
  357. * @return array
  358. * Array of entity IDs, empty array if there are no references.
  359. */
  360. protected function getRemoteReferenceIDs($entity) {
  361. return $this->getReferenceIDs($entity, $this->remote);
  362. }
  363. /**
  364. * Check if a field can support any more values. Formerly known as
  365. * "reference overloading".
  366. *
  367. * @param array $references
  368. * The values in the field.
  369. *
  370. * @param $field
  371. * Field definition (i.e., from field_info_field).
  372. *
  373. * @return boolean
  374. */
  375. private function filled($references, $field) {
  376. return $field['cardinality'] != FIELD_CARDINALITY_UNLIMITED && sizeof($references) >= $field['cardinality'];
  377. }
  378. /**
  379. * Gets all the referenced entity IDs from a specific field on $entity.
  380. *
  381. * @param object $entity
  382. * The entity to scan for references.
  383. *
  384. * @param array $field
  385. * Field or instance definition.
  386. *
  387. * @return array
  388. * Array of unique IDs, empty if there are no references or the field
  389. * does not exist on $entity.
  390. */
  391. private function getReferenceIDs($entity, $field) {
  392. $IDs = array();
  393. if (isset($entity->{$field['field_name']})) {
  394. foreach ($entity->{$field['field_name']} as $references) {
  395. foreach ($references as $reference) {
  396. $IDs[] = $reference['target_id'];
  397. }
  398. }
  399. }
  400. return array_unique(array_filter($IDs));
  401. }
  402. }