handler.inc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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() {
  145. foreach ($this->getReferencedEntities() as $referenced_entity) {
  146. $this->reference($referenced_entity);
  147. _cer_update($this->remote['entity_type'], $referenced_entity);
  148. }
  149. }
  150. /**
  151. * Implements CerHandlerInterface::update().
  152. */
  153. public function update() {
  154. $original = isset($this->entity->original) ? $this->entity->original : $this->entity;
  155. $deleted = array_diff($this->getReferenceIDs($original, $this->local), $this->getLocalReferenceIDs());
  156. if ($deleted) {
  157. $entities = entity_load($this->remote['entity_type'], $deleted);
  158. foreach ($entities as $referenced_entity) {
  159. $this->dereference($referenced_entity);
  160. _cer_update($this->remote['entity_type'], $referenced_entity);
  161. }
  162. }
  163. $this->insert();
  164. }
  165. /**
  166. * Implements CerHandlerInterface::delete().
  167. */
  168. public function delete() {
  169. foreach ($this->getReferencedEntities() as $referenced_entity) {
  170. $this->dereference($referenced_entity);
  171. _cer_update($this->remote['entity_type'], $referenced_entity);
  172. }
  173. }
  174. /**
  175. * Implements CerHandlerInterface::references().
  176. */
  177. public function references($entity) {
  178. return in_array($this->getRemoteEntityID($entity), $this->getLocalReferenceIDs());
  179. }
  180. /**
  181. * Implements CerHandlerInterface::referencedBy().
  182. */
  183. public function referencedBy($entity) {
  184. return in_array($this->id, $this->getRemoteReferenceIDs($entity));
  185. }
  186. /**
  187. * Implements CerHandlerInterface::referenceable().
  188. */
  189. public function referenceable($entity) {
  190. $id = $this->getRemoteEntityID($entity);
  191. $allowed = array(
  192. entityreference_get_selection_handler(
  193. $this->local['field'],
  194. $this->local,
  195. $this->local['entity_type'],
  196. $this->entity
  197. )
  198. ->validateReferencableEntities(array($id)),
  199. entityreference_get_selection_handler(
  200. $this->remote['field'],
  201. $this->remote,
  202. $this->remote['entity_type'],
  203. $entity
  204. )
  205. ->validateReferencableEntities(array($this->id)),
  206. );
  207. return in_array($id, $allowed[0]) && in_array($this->id, $allowed[1]);
  208. }
  209. /**
  210. * Implements CerHandlerInterface::reference().
  211. */
  212. public function reference($entity) {
  213. if ($this->referenceable($entity)) {
  214. try {
  215. $this->addReferenceTo($entity);
  216. }
  217. catch (CerException $e) {
  218. // Fail silently
  219. }
  220. try {
  221. $this->addReferenceFrom($entity);
  222. }
  223. catch (CerException $e) {
  224. // Fail silently
  225. }
  226. }
  227. else {
  228. throw new CerException(t('Cannot create invalid reference to remote entity.'));
  229. }
  230. }
  231. /**
  232. * Implements CerHandlerInterface::dereference().
  233. */
  234. public function dereference($entity) {
  235. if ($this->references($entity)) {
  236. $id = $this->getRemoteEntityID($entity);
  237. foreach ($this->entity->{$this->local['field_name']} as $language => $references) {
  238. foreach ($references as $delta => $reference) {
  239. if ($reference['target_id'] == $id) {
  240. unset($this->entity->{$this->local['field_name']}[$language][$delta]);
  241. }
  242. }
  243. }
  244. }
  245. if ($this->referencedBy($entity)) {
  246. foreach ($entity->{$this->remote['field_name']} as $language => $references) {
  247. foreach ($references as $delta => $reference) {
  248. if ($reference['target_id'] == $this->id) {
  249. unset($entity->{$this->remote['field_name']}[$language][$delta]);
  250. }
  251. }
  252. }
  253. }
  254. }
  255. /**
  256. * Creates a reference to the local entity on the remote entity. Throws CerException
  257. * if the local entity is already referenced by the remote entity, or if the remote
  258. * field cannot hold any more values.
  259. *
  260. * @param object $entity
  261. * The remote entity.
  262. */
  263. protected function addReferenceFrom($entity) {
  264. if ($this->referencedBy($entity)) {
  265. throw new CerException(t('Cannot create duplicate reference from remote entity.'));
  266. }
  267. elseif ($this->filled($this->getRemoteReferenceIDs($entity), $this->remote['field'])) {
  268. throw new CerException(t('Remote field cannot support any more references.'));
  269. }
  270. else {
  271. $languages = field_available_languages($this->remote['entity_type'], $this->remote['field']);
  272. foreach ($languages as $language) {
  273. $entity->{$this->remote['field_name']}[$language][] = array('target_id' => $this->id);
  274. }
  275. }
  276. }
  277. /**
  278. * Creates a reference to the remote entity on the local entity. Throws CerException
  279. * if the local entity already references the remote entity, or if the field cannot
  280. * hold any more values.
  281. *
  282. * @param object $entity
  283. * The remote entity.
  284. */
  285. protected function addReferenceTo($entity) {
  286. $id = $this->getRemoteEntityID($entity);
  287. if ($this->references($entity)) {
  288. throw new CerException(t('Cannot create duplicate reference to remote entity.'));
  289. }
  290. elseif ($this->filled($this->getLocalReferenceIDs(), $this->local['field'])) {
  291. throw new CerException(t('Local field cannot support any more references.'));
  292. }
  293. else {
  294. $languages = field_available_languages($this->local['entity_type'], $this->local['field']);
  295. foreach ($languages as $language) {
  296. $this->entity->{$this->local['field_name']}[$language][] = array('target_id' => $id);
  297. }
  298. }
  299. }
  300. /**
  301. * Get the ID of the remote entity. If the entity is of the wrong type,
  302. * EntityMalformedException will be thrown.
  303. *
  304. * @param object $entity
  305. * The remote entity.
  306. *
  307. * @return mixed
  308. * The remote entity ID.
  309. */
  310. protected function getRemoteEntityID($entity) {
  311. $extract_ids = entity_extract_IDs($this->remote['entity_type'], $entity);
  312. return array_shift($extract_ids);
  313. }
  314. /**
  315. * Gets all the entities referenced by the local entity.
  316. *
  317. * @return array
  318. * Array of fully loaded referenced entities keyed by ID, or empty
  319. * array if nothing has been referenced.
  320. */
  321. protected function getReferencedEntities() {
  322. $IDs = $this->getLocalReferenceIDs();
  323. return $IDs ? entity_load($this->remote['entity_type'], $IDs) : array();
  324. }
  325. /**
  326. * Gets the IDs of the entities referenced by the local entity.
  327. *
  328. * @return array
  329. * Array of entity IDs, empty array if there are no references.
  330. */
  331. protected function getLocalReferenceIDs() {
  332. return $this->getReferenceIDs($this->entity, $this->local);
  333. }
  334. /**
  335. * Gets the IDs of the entities referenced by $entity.
  336. *
  337. * @param object $entity
  338. * The remote entity.
  339. *
  340. * @return array
  341. * Array of entity IDs, empty array if there are no references.
  342. */
  343. protected function getRemoteReferenceIDs($entity) {
  344. return $this->getReferenceIDs($entity, $this->remote);
  345. }
  346. /**
  347. * Check if a field can support any more values. Formerly known as
  348. * "reference overloading".
  349. *
  350. * @param array $references
  351. * The values in the field.
  352. *
  353. * @param $field
  354. * Field definition (i.e., from field_info_field).
  355. *
  356. * @return boolean
  357. */
  358. private function filled($references, $field) {
  359. return $field['cardinality'] != FIELD_CARDINALITY_UNLIMITED && sizeof($references) >= $field['cardinality'];
  360. }
  361. /**
  362. * Gets all the referenced entity IDs from a specific field on $entity.
  363. *
  364. * @param object $entity
  365. * The entity to scan for references.
  366. *
  367. * @param array $field
  368. * Field or instance definition.
  369. *
  370. * @return array
  371. * Array of unique IDs, empty if there are no references or the field
  372. * does not exist on $entity.
  373. */
  374. private function getReferenceIDs($entity, $field) {
  375. $IDs = array();
  376. if (isset($entity->{$field['field_name']})) {
  377. foreach ($entity->{$field['field_name']} as $references) {
  378. foreach ($references as $reference) {
  379. $IDs[] = $reference['target_id'];
  380. }
  381. }
  382. }
  383. return array_unique(array_filter($IDs));
  384. }
  385. }