callback_bundle_filter.inc 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. /**
  3. * Search API data alteration callback that filters out items based on their
  4. * bundle.
  5. */
  6. class SearchApiAlterBundleFilter extends SearchApiAbstractAlterCallback {
  7. public function supportsIndex(SearchApiIndex $index) {
  8. return ($info = entity_get_info($index->item_type)) && self::hasBundles($info);
  9. }
  10. public function alterItems(array &$items) {
  11. $info = entity_get_info($this->index->item_type);
  12. if (self::hasBundles($info) && isset($this->options['bundles'])) {
  13. $bundles = array_flip($this->options['bundles']);
  14. $default = (bool) $this->options['default'];
  15. $bundle_prop = $info['entity keys']['bundle'];
  16. foreach ($items as $id => $item) {
  17. if (isset($bundles[$item->$bundle_prop]) == $default) {
  18. unset($items[$id]);
  19. }
  20. }
  21. }
  22. }
  23. public function configurationForm() {
  24. $info = entity_get_info($this->index->item_type);
  25. if (self::hasBundles($info)) {
  26. $options = array();
  27. foreach ($info['bundles'] as $bundle => $bundle_info) {
  28. $options[$bundle] = isset($bundle_info['label']) ? $bundle_info['label'] : $bundle;
  29. }
  30. $form = array(
  31. 'default' => array(
  32. '#type' => 'radios',
  33. '#title' => t('Which items should be indexed?'),
  34. '#default_value' => isset($this->options['default']) ? $this->options['default'] : 1,
  35. '#options' => array(
  36. 1 => t('All but those from one of the selected bundles'),
  37. 0 => t('Only those from the selected bundles'),
  38. ),
  39. ),
  40. 'bundles' => array(
  41. '#type' => 'select',
  42. '#title' => t('Bundles'),
  43. '#default_value' => isset($this->options['bundles']) ? $this->options['bundles'] : array(),
  44. '#options' => $options,
  45. '#size' => min(4, count($options)),
  46. '#multiple' => TRUE,
  47. ),
  48. );
  49. }
  50. else {
  51. $form = array(
  52. 'forbidden' => array(
  53. '#markup' => '<p>' . t("Items indexed by this index don't have bundles and therefore cannot be filtered here.") . '</p>',
  54. ),
  55. );
  56. }
  57. return $form;
  58. }
  59. /**
  60. * Helper method for figuring out if the entities with the given entity info
  61. * can be filtered by bundle.
  62. */
  63. protected static function hasBundles(array $entity_info) {
  64. return !empty($entity_info['entity keys']['bundle']) && !empty($entity_info['bundles']);
  65. }
  66. }