SnowballStemmer.php in Snowball Stemmer 2.x
File
src/Plugin/search_api/processor/SnowballStemmer.php
View source
<?php
namespace Drupal\snowball_stemmer\Plugin\search_api\processor;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\search_api\Query\QueryInterface;
use Drupal\search_api\Plugin\search_api\processor\Stemmer as StemmerProcessor;
use Drupal\snowball_stemmer\Stemmer;
class SnowballStemmer extends StemmerProcessor {
protected $stemmer;
protected $languageManager;
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
$processor = parent::create($container, $configuration, $plugin_id, $plugin_definition);
$processor
->setStemmer($container
->get('snowball_stemmer.stemmer'));
$processor
->setLanguageManager($container
->get('language_manager'));
return $processor;
}
public function getStemmer() {
$stemmer = $this->stemmer ?: \Drupal::service('snowball_stemmer.stemmer');
$stemmer
->setOverrides($this->configuration['exceptions']);
return $stemmer;
}
public function setStemmer(Stemmer $stemmer) {
$this->stemmer = $stemmer;
return $this;
}
public function getLanguageManager() {
return $this->languageManager ?: \Drupal::service('language_manager');
}
public function setLanguageManager(LanguageManagerInterface $language_manager) {
$this->languageManager = $language_manager;
return $this;
}
public function preprocessIndexItems(array $items) {
foreach ($items as $item) {
if ($this
->getStemmer()
->setLanguage($item
->getLanguage())) {
foreach ($item
->getFields() as $name => $field) {
if ($this
->testField($name, $field)) {
$this
->processField($field);
}
}
}
}
}
public function preprocessSearchQuery(QueryInterface $query) {
if ($languages = $query
->getLanguages()) {
$language = reset($languages);
}
else {
$language = $this
->getLanguageManager()
->getCurrentLanguage()
->getId();
}
$keys =& $query
->getKeys();
if (isset($keys) && $this
->getStemmer()
->setLanguage($language)) {
$this
->processKeys($keys);
}
$conditions = $query
->getConditionGroup();
$this
->processConditions($conditions
->getConditions());
}
protected function process(&$value) {
$words = preg_split('/[^\\p{L}\\p{N}]+/u', strip_tags($value), -1, PREG_SPLIT_NO_EMPTY);
$stemmed = [];
foreach ($words as $word) {
$stemmed[] = $this
->stem($word);
}
$value = implode(' ', $stemmed);
}
protected function stem($word) {
if (strlen($word)) {
$word = $this
->getStemmer()
->stem($word);
}
return $word;
}
}