DoubleQuoteWorkaround.php in Search API Solr 4.x
File
src/Plugin/search_api/processor/DoubleQuoteWorkaround.php
View source
<?php
namespace Drupal\search_api_solr\Plugin\search_api\processor;
use Drupal\Core\Form\FormStateInterface;
use Drupal\search_api\Plugin\search_api\data_type\value\TextValueInterface;
use Drupal\search_api\Processor\FieldsProcessorPluginBase;
use Drupal\search_api\Query\ResultSetInterface;
use Drupal\search_api_solr\SolrProcessorInterface;
class DoubleQuoteWorkaround extends FieldsProcessorPluginBase implements SolrProcessorInterface {
public function defaultConfiguration() {
$configuration = parent::defaultConfiguration();
$configuration += [
'replacement' => '|9999999998|',
];
return $configuration;
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$form['replacement'] = [
'#type' => 'textfield',
'#title' => $this
->t('Replacement'),
'#description' => $this
->t('The replacement for a double quote in the input string.'),
'#default_value' => $this->configuration['replacement'],
];
return $form;
}
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::validateConfigurationForm($form, $form_state);
$replacement = trim($form_state
->getValue('replacement'));
if (mb_strlen($replacement) < 3) {
$form_state
->setErrorByName('replacement', $this
->t('The replacement should at least consist of three cahracters.'));
}
}
protected function process(&$value) {
if (is_string($value)) {
$value = preg_replace('/"/u', $this->configuration['replacement'], $value);
}
}
public function postprocessSearchResults(ResultSetInterface $results) {
foreach ($results
->getResultItems() as $resultItem) {
foreach ($resultItem
->getFields(FALSE) as $field) {
$values = $field
->getValues();
foreach ($values as $key => $value) {
if (is_string($value)) {
$values[$key] = $this
->decodeStreamingExpressionValue($value);
}
elseif ($value instanceof TextValueInterface) {
$value
->setText($this
->decodeStreamingExpressionValue($value
->getText()));
}
}
$field
->setValues($values);
}
}
}
public function encodeStreamingExpressionValue(string $value) {
return preg_replace('/"/u', $this->configuration['replacement'], $value);
}
public function decodeStreamingExpressionValue(string $value) {
return preg_replace('/' . preg_quote($this->configuration['replacement'], '/') . '/u', '"', $value);
}
}