callback_bundle_filter.inc 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * @file
  4. * Contains SearchApiAlterBundleFilter.
  5. */
  6. /**
  7. * Represents a data alteration that restricts entity indexes to some bundles.
  8. */
  9. class SearchApiAlterBundleFilter extends SearchApiAbstractAlterCallback {
  10. /**
  11. * {@inheritdoc}
  12. */
  13. public function supportsIndex(SearchApiIndex $index) {
  14. return $index->getEntityType() && ($info = entity_get_info($index->getEntityType())) && self::hasBundles($info);
  15. }
  16. /**
  17. * {@inheritdoc}
  18. */
  19. public function alterItems(array &$items) {
  20. $info = entity_get_info($this->index->getEntityType());
  21. if (self::hasBundles($info) && isset($this->options['bundles'])) {
  22. $bundles = array_flip($this->options['bundles']);
  23. $default = (bool) $this->options['default'];
  24. $bundle_prop = $info['entity keys']['bundle'];
  25. foreach ($items as $id => $item) {
  26. if (isset($bundles[$item->$bundle_prop]) == $default) {
  27. unset($items[$id]);
  28. }
  29. }
  30. }
  31. }
  32. /**
  33. * {@inheritdoc}
  34. */
  35. public function configurationForm() {
  36. $info = entity_get_info($this->index->getEntityType());
  37. if (self::hasBundles($info)) {
  38. $options = array();
  39. foreach ($info['bundles'] as $bundle => $bundle_info) {
  40. $options[$bundle] = isset($bundle_info['label']) ? $bundle_info['label'] : $bundle;
  41. }
  42. $form = array(
  43. 'default' => array(
  44. '#type' => 'radios',
  45. '#title' => t('Which items should be indexed?'),
  46. '#default_value' => isset($this->options['default']) ? $this->options['default'] : 1,
  47. '#options' => array(
  48. 1 => t('All but those from one of the selected bundles'),
  49. 0 => t('Only those from the selected bundles'),
  50. ),
  51. ),
  52. 'bundles' => array(
  53. '#type' => 'select',
  54. '#title' => t('Bundles'),
  55. '#default_value' => isset($this->options['bundles']) ? $this->options['bundles'] : array(),
  56. '#options' => $options,
  57. '#size' => min(4, count($options)),
  58. '#multiple' => TRUE,
  59. ),
  60. );
  61. }
  62. else {
  63. $form = array(
  64. 'forbidden' => array(
  65. '#markup' => '<p>' . t("Items indexed by this index don't have bundles and therefore cannot be filtered here.") . '</p>',
  66. ),
  67. );
  68. }
  69. return $form;
  70. }
  71. /**
  72. * Determines whether a certain entity type has any bundles.
  73. *
  74. * @param array $entity_info
  75. * The entity type's entity_get_info() array.
  76. *
  77. * @return bool
  78. * TRUE if the entity type has bundles, FASLE otherwise.
  79. */
  80. protected static function hasBundles(array $entity_info) {
  81. return !empty($entity_info['entity keys']['bundle']) && !empty($entity_info['bundles']);
  82. }
  83. }