CerPresetFinder.inc 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * This class is a unified way for CER to find the presets that apply to a given
  4. * entity. The result set is segmented into two parts: presets where the entity
  5. * is on the left side, and bidirectional presets with the entity on the right
  6. * side (i.e., the ones which need to be inverted before use). The execute()
  7. * method will return a merged and sorted array of presets, but the segmented
  8. * result set is exposed to the world as well for other uses (i.e., CER Entity
  9. * Settings' selection handler).
  10. */
  11. class CerPresetFinder extends EntityFieldQuery {
  12. public $result = array();
  13. protected $entity;
  14. public function __construct(EntityDrupalWrapper $entity) {
  15. $this->entity = $entity;
  16. $this
  17. ->entityCondition('entity_type', 'cer')
  18. ->addTag('cer_presets')
  19. ->addMetaData('entity', $entity);
  20. }
  21. public function execute() {
  22. $lineage = $this->entity->cer->lineage->value();
  23. $this->result['cer'] = $this
  24. ->fieldCondition('cer_enabled', 'value', TRUE)
  25. ->fieldCondition('cer_left', 'path', $lineage, 'STARTS_WITH')
  26. ->_load(parent::execute());
  27. $this->fieldConditions = array();
  28. $this->result['cer__invert'] = $this
  29. ->fieldCondition('cer_enabled', 'value', TRUE)
  30. ->fieldCondition('cer_bidirectional', 'value', TRUE)
  31. ->fieldCondition('cer_right', 'path', $lineage, 'STARTS_WITH')
  32. ->_load(parent::execute());
  33. $result = $this->result['cer'];
  34. foreach ($this->result['cer__invert'] as $preset) {
  35. $result[] = $preset->invert();
  36. }
  37. usort($result, array($this, '_sort'));
  38. return $result;
  39. }
  40. private function _load(array $result) {
  41. return isset($result['cer']) ? entity_load('cer', array_keys($result['cer'])) : array();
  42. }
  43. private function _sort(CerPreset $a, CerPreset $b) {
  44. $a_weight = $a->wrapper->cer_weight->value();
  45. $b_weight = $b->wrapper->cer_weight->value();
  46. if ($a_weight > $b_weight) {
  47. return 1;
  48. }
  49. elseif ($b_weight > $a_weight) {
  50. return -1;
  51. }
  52. else {
  53. return 0;
  54. }
  55. }
  56. }