porterstemmer.module in Porter-Stemmer 8
File
porterstemmer.module
View source
<?php
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\porterstemmer\Porter2;
define('PORTERSTEMMER_BOUNDARY', "[^a-zA-Z']+");
function porterstemmer_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.porterstemmer':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Improves American English language searching by simplifying related words to their root (conjugations, plurals, ...).') . '</p>';
return $output;
default:
}
}
function porterstemmer_search_preprocess($text, $langcode = NULL) {
if (!isset($langcode)) {
$langcode = \Drupal::languageManager()
->getCurrentLanguage()
->getId();
}
if ($langcode == 'en') {
$text = strtolower(str_replace('’', "'", $text));
$words = preg_split('/(' . PORTERSTEMMER_BOUNDARY . '+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
if (!count($words)) {
return $text;
}
$has_pecl_stem = _porterstemmer_pecl_loaded();
$isword = !preg_match('/' . PORTERSTEMMER_BOUNDARY . '/', $words[0]);
foreach ($words as $k => $word) {
if ($isword) {
if ($has_pecl_stem) {
$words[$k] = stem_english($word);
}
else {
$words[$k] = Porter2::stem($word);
}
}
$isword = !$isword;
}
return implode('', $words);
}
return $text;
}
function _porterstemmer_pecl_loaded() {
static $has_pecl_stem = FALSE;
static $already_checked = FALSE;
if ($already_checked) {
return $has_pecl_stem;
}
$has_pecl_stem = extension_loaded('stem') && function_exists('stem_english');
$already_checked = TRUE;
return $has_pecl_stem;
}