Untitled
unknown
plain_text
a year ago
2.1 kB
7
Indexable
custom_search_filter.info.yml
name: 'Custom Search Filter'
type: module
description: 'A custom module to filter out media entities not referenced by any content.'
core_version_requirement: ^10
package: Custom
dependencies:
- search_api:search_api
- entity_usage:entity_usage
version: '1.0.0'
custom_search_filter.module
<?php
/**
* @file
* Custom module to add a processor for filtering referenced media entities.
*/
/**
* Implements hook_help().
*/
function custom_search_filter_help($route_name, \Drupal\Core\Routing\RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.custom_search_filter':
return '<p>' . t('Custom module to index only referenced media entities in Solr.') . '</p>';
}
}
src/Plugin/search_api/processor/MediaReferenceProcessor.php
<?php
namespace Drupal\custom_search_filter\Plugin\search_api\processor;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Item\ItemInterface;
use Drupal\media\Entity\Media;
/**
* Filters out media entities not referenced by content.
*
* @SearchApiProcessor(
* id = "media_reference_processor",
* label = @Translation("Media Reference Processor"),
* description = @Translation("Only index media entities that are referenced by other content."),
* stages = {
* "alter_items" = 0
* }
* )
*/
class MediaReferenceProcessor extends ProcessorPluginBase {
/**
* {@inheritdoc}
*/
public function alterIndexedItems(array &$items) {
// Loop through all items in the index.
foreach ($items as $id => $item) {
// Get the entity from the indexed item.
$entity = $item->getOriginalObject()->getValue();
// Check if the entity is a Media entity.
if ($entity instanceof Media) {
// Use entity_usage service to check if the media is referenced.
$usage = \Drupal::service('entity_usage.usage')->getUsage($entity);
// If the media is not referenced, remove it from indexing.
if (empty($usage)) {
unset($items[$id]);
}
}
}
}
}
Editor is loading...
Leave a Comment