Last active
October 21, 2023 09:53
-
-
Save joecorall/fa914809af3304cdd98194d929d1bad9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Drupal\oaks_fields\Plugin\search_api\processor; | |
use Drupal\search_api\Datasource\DatasourceInterface; | |
use Drupal\search_api\Item\ItemInterface; | |
use Drupal\search_api\Processor\ProcessorPluginBase; | |
use Drupal\search_api\Processor\ProcessorProperty; | |
use Drupal\node\Entity\Node; | |
use Drupal\controlled_access_terms\EDTFUtils; | |
/** | |
* Extract the year from an EDTF date | |
* | |
* @SearchApiProcessor( | |
* id = "oaks_fields_issue_year", | |
* label = @Translation("Issue Year"), | |
* description = @Translation("Gets the year from the EDTF date."), | |
* stages = { | |
* "add_properties" = 0, | |
* }, | |
* locked = true, | |
* hidden = true, | |
* ) | |
*/ | |
class IssueYear extends ProcessorPluginBase { | |
/** | |
* {@inheritdoc} | |
*/ | |
public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) { | |
$properties = []; | |
if (!$datasource) { | |
$definition = [ | |
'label' => $this->t('OAKS Issue Year'), | |
'description' => $this->t('The year the item was published'), | |
'type' => 'integer', | |
'processor_id' => $this->getPluginId(), | |
]; | |
$properties['oaks_issue_year'] = new ProcessorProperty($definition); | |
} | |
return $properties; | |
} | |
/** | |
* {@inheritdoc} | |
*/ | |
public function addFieldValues(ItemInterface $item) { | |
// find the URI of the entity being added to the search API | |
// via the search API's item ID (e.g. entity:node/1:en) | |
$components = explode(':', $item->getId()); | |
array_shift($components); | |
$uri = array_shift($components); | |
$components = explode('/', $uri); | |
// if this is a node, load it | |
if (count($components) == 2 && $components[0] === 'node') { | |
// @todo is there a better way to get the node entity than loading it again? | |
$node = Node::load($components[1]); | |
// if we the node, and it has an issued date, add it to the index | |
if ($node | |
&& $node->hasField('field_edtf_date_issued') | |
&& !$node->field_edtf_date_issued->isEmpty()) { | |
$date = $node->field_edtf_date_issued->value; | |
$iso = EDTFUtils::iso8601Value($date); | |
$components = explode('-', $iso); | |
$year = array_shift($components); | |
if (is_numeric($year)) { | |
$fields = $item->getFields(FALSE); | |
$fields = $this->getFieldsHelper() | |
->filterForPropertyPath($fields, NULL, 'oaks_issue_year'); | |
foreach ($fields as $field) { | |
$field->addValue($year); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment