TermUsed.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace Drupal\materio_sapi\Plugin\search_api\processor;
  3. use Drupal\Core\Entity\EntityPublishedInterface;
  4. use Drupal\search_api\IndexInterface;
  5. use Drupal\search_api\Processor\ProcessorPluginBase;
  6. use Drupal\user\UserInterface;
  7. /**
  8. * Excludes unused terms from indexes.
  9. *
  10. * @SearchApiProcessor(
  11. * id = "term_used",
  12. * label = @Translation("Term used"),
  13. * description = @Translation("Exclude unused taxonomy terms from being indexed."),
  14. * stages = {
  15. * "alter_items" = 0,
  16. * },
  17. * )
  18. */
  19. class TermUsed extends ProcessorPluginBase {
  20. /**
  21. * {@inheritdoc}
  22. */
  23. public static function supportsIndex(IndexInterface $index) {
  24. $interface = EntityPublishedInterface::class;
  25. foreach ($index->getDatasources() as $datasource) {
  26. $entity_type_id = $datasource->getEntityTypeId();
  27. if (!$entity_type_id) {
  28. continue;
  29. }
  30. // We support users and any entities that implement
  31. // \Drupal\Core\Entity\EntityPublishedInterface.
  32. if ($entity_type_id === 'taxonomy_term') {
  33. return TRUE;
  34. }
  35. // $entity_type = \Drupal::entityTypeManager()
  36. // ->getDefinition($entity_type_id);
  37. // if ($entity_type && $entity_type->entityClassImplements($interface)) {
  38. // return TRUE;
  39. // }
  40. }
  41. return FALSE;
  42. }
  43. /**
  44. * {@inheritdoc}
  45. */
  46. public function alterIndexedItems(array &$items) {
  47. // Annoyingly, this doc comment is needed for PHPStorm. See
  48. // http://youtrack.jetbrains.com/issue/WI-23586
  49. /** @var \Drupal\search_api\Item\ItemInterface $item */
  50. foreach ($items as $item_id => $item) {
  51. $term = $item->getOriginalObject()->getValue();
  52. $enabled = TRUE;
  53. // $entity_storage = \Drupal::entityTypeManager()->getStorage('node');
  54. // $count_query = $entity_storage->getQuery()
  55. // ->condition('type', 'materiau')
  56. // ->accessCheck(TRUE)
  57. // ->condition('status', '1')
  58. // ->count();
  59. //
  60. // $this->count = $this->count_query->execute();
  61. $query = \Drupal::database()->select('taxonomy_index', 'ti');
  62. $query->fields('ti', array('nid'));
  63. $query->condition('ti.tid', $term->id());
  64. $query->distinct(TRUE);
  65. $result = $query->execute();
  66. $nodeIds = $result->fetchCol();
  67. if (!$nodeIds) {
  68. unset($items[$item_id]);
  69. }
  70. }
  71. }
  72. }