-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathEDTFYear.php
260 lines (243 loc) · 9.85 KB
/
EDTFYear.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
<?php
namespace Drupal\controlled_access_terms\Plugin\search_api\processor;
use Drupal\controlled_access_terms\EDTFUtils;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\search_api\Datasource\DatasourceInterface;
use Drupal\search_api\Item\ItemInterface;
use Drupal\search_api\Plugin\PluginFormTrait;
use Drupal\search_api\Processor\ProcessorPluginBase;
use Drupal\search_api\Processor\ProcessorProperty;
use EDTF\EdtfFactory;
/**
* Adds the item's creation year to the indexed data.
*
* @SearchApiProcessor(
* id = "edtf_year_only",
* label = @Translation("EDTF Year"),
* description = @Translation("Adds the item's EDTF date as a year."),
* stages = {
* "add_properties" = 0,
* },
* )
*/
class EDTFYear extends ProcessorPluginBase implements PluginFormInterface {
use PluginFormTrait;
/**
* {@inheritdoc}
*/
public function getPropertyDefinitions(DatasourceInterface $datasource = NULL) {
$properties = [];
if (!$datasource) {
$definition = [
'label' => $this->t('EDTF Creation Date Year'),
'description' => $this->t('The year the item was created'),
'type' => 'integer',
'is_list' => TRUE,
'processor_id' => $this->getPluginId(),
];
$properties['edtf_year'] = new ProcessorProperty($definition);
}
return $properties;
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'fields' => [],
'ignore_undated' => TRUE,
'ignore_open_start' => FALSE,
'ignore_open_end' => FALSE,
'open_start_year' => 0,
'open_end_year' => '',
];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $formState) {
$form['#description'] = $this->t('Select the fields containing EDTF strings to extract year values for.');
$fields = \Drupal::entityTypeManager()
->getStorage('field_config')
->loadByProperties(['field_type' => 'edtf']);
$fields_options = [];
foreach ($fields as $field) {
$fields_options[$field->getTargetEntityTypeId() . '|' . $field->getTargetBundle() . '|' . $field->get('field_name')] = $this->t("%label (%type:%bundle)", [
'%type' => $field->getTargetEntityTypeId(),
'%label' => $field->label(),
'%bundle' => $field->getTargetBundle(),
]);
}
$form['fields'] = [
'#type' => 'select',
'#multiple' => TRUE,
'#title' => $this->t('Fields'),
'#description' => $this->t('Select the fields with EDTF values to use.'),
'#options' => $fields_options,
'#default_value' => $this->configuration['fields'],
];
$form['ignore_undated'] = [
'#type' => 'checkbox',
'#title' => $this->t('Ignore Undated'),
'#description' => $this->t('Ignore undated values (i.e. "XXXX").'),
'#default_value' => $this->configuration['ignore_undated'],
];
$form['ignore_open_start'] = [
'#type' => 'checkbox',
'#title' => $this->t('Ignore Open Dates'),
'#description' => $this->t('Ignores the open start dates. E.g. "../2021" would be indexed as "2021" instead of every year from 0 (or the configured open start year).'),
'#default_value' => $this->configuration['ignore_open_start'],
];
$form['open_start_year'] = [
'#type' => 'number',
'#title' => $this->t('Open Interval Begin Year'),
'#description' => $this->t('Sets the beginning year to be used when processing an date interval. For example, by default, "../%year" would become every year from 0 until %year', ['%year' => date("Y")]),
'#default_value' => $this->configuration['open_start_year'],
];
$form['ignore_open_end'] = [
'#type' => 'checkbox',
'#title' => $this->t('Ignore Open Ended Dates'),
'#description' => $this->t('Ignores the open ended dates. E.g. "2020/.." would be indexed as "2020" instead of every year from 2020 until %year.', ['%year' => date("Y")]),
'#default_value' => $this->configuration['ignore_open_end'],
];
$form['open_end_year'] = [
'#type' => 'number',
'#title' => $this->t('Open Interval End Year'),
'#description' => $this->t('Sets the last year to be used when processing an date interval. Leave blank to use the current year when indexed. For example, by default, "2020/.." would become every year from 2020 until this year (%year).', ['%year' => date("Y")]),
'#default_value' => $this->configuration['open_end_year'],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $formState) {
if (!is_numeric($formState->getValue('open_start_year'))) {
$formState->setError($form['open_start_year'], $this->t('Please provide an integer year value.'));
}
if (!empty($formState->getValue('open_end_year')) && !is_numeric($formState->getValue('open_end_year'))) {
$formState->setError($form['open_end_year'], $this->t('Please leave the field blank or provide an integer year value.'));
}
}
/**
* {@inheritdoc}
*/
public function addFieldValues(ItemInterface $item) {
$entity = $item->getOriginalObject()->getValue();
foreach ($this->configuration['fields'] as $field) {
[$entityType, $bundle, $field_name] = explode('|', $field, 3);
if ($entityType === 'paragraph') {
$edtf = $this->getDateFromParagraphField($entity, $bundle, $field_name);
}
elseif ($entity->getEntityTypeId() == $entityType
&& $entity->bundle() == $bundle
&& $entity->hasField($field_name)
&& !$entity->get($field_name)->isEmpty()) {
$edtf = trim($entity->get($field_name)->value);
}
if ($edtf) {
if ($edtf != "nan" && empty(EDTFUtils::validate($edtf))) {
if ($this->configuration['ignore_undated'] && $edtf == "XXXX") {
continue;
}
try {
$parser = EdtfFactory::newParser();
$years = [];
// Sets.
if (strpos($edtf, '[') !== FALSE || strpos($edtf, '{') !== FALSE) {
$dates = $parser->parse($edtf)->getEdtfValue();
$years = array_map(function ($date) {
return $date->getYear();
}, $dates->getDates());
}
else {
// Open start dates with `../`.
if (substr($edtf, 0, 3) === '../') {
if ($this->configuration['ignore_open_start']) {
$edtf = substr($edtf, 3);
}
else {
$edtf = str_replace('../', $this->configuration['open_start_year'] . '/', $edtf);
}
}
// Open start dates with `/`.
if (substr($edtf, 0, 1) === '/') {
if ($this->configuration['ignore_open_start']) {
$edtf = substr($edtf, 1);
}
else {
$edtf = str_replace('/', $this->configuration['open_start_year'] . '/', $edtf);
}
}
// Open end dates with `/..`.
if (substr($edtf, -3) === '/..') {
if ($this->configuration['ignore_open_end']) {
$edtf = substr($edtf, 0, -3);
}
else {
$end_year = (empty($this->configuration['open_end_year'])) ? date('Y') : $this->configuration['open_end_year'];
$edtf = str_replace('/..', '/' . $end_year, $edtf);
}
}
// Open end dates with `/`.
if (substr($edtf, -1) === '/') {
if ($this->configuration['ignore_open_end']) {
$edtf = substr($edtf, 0, -1);
}
else {
$end_year = (empty($this->configuration['open_end_year'])) ? date('Y') : $this->configuration['open_end_year'];
$edtf = str_replace('/', '/' . $end_year, $edtf);
}
}
$parsed = $parser->parse($edtf)->getEdtfValue();
$years = range(intval(date('Y', $parsed->getMin())), intval(date('Y', $parsed->getMax())));
}
foreach ($years as $year) {
if (is_numeric($year)) {
$fields = $item->getFields(FALSE);
$fields = $this->getFieldsHelper()
->filterForPropertyPath($fields, NULL, 'edtf_year');
foreach ($fields as $field) {
$field->addValue($year);
}
}
}
}
catch (\Throwable $e) {
\Drupal::logger('controlled_access_terms')
->warning(t("Could not parse EDTF value '@edtf' for indexing @type/@id",
[
'@edtf' => $edtf,
'@type' => $entity->getEntityTypeId(),
'@id' => $entity->id(),
]));
}
}
}
}
}
/**
* Gets edtf date value from a referenced paragraph.
*/
private function getDateFromParagraphField(EntityInterface $entity, string $bundle, string $field_name) {
$query = \Drupal::entityTypeManager()
->getStorage('field_config')
->getQuery();
$query->condition('bundle', $entity->bundle());
$query->condition("settings.handler_settings.target_bundles.{$bundle}", $bundle);
$paragraph_ids = $query->execute();
if (!empty($paragraph_ids)) {
$paragraph_field_config = reset($paragraph_ids);
$paragraph_field_config_array = explode('.', $paragraph_field_config);
$paragraph_field_name = end($paragraph_field_config_array);
$paragraph_entity = $entity->get($paragraph_field_name)
->referencedEntities()[0] ?? NULL;
if ($paragraph_entity->hasField($field_name)
&& !$paragraph_entity->get($field_name)->isEmpty()) {
return trim($paragraph_entity->get($field_name)->value);
}
}
}
}