IngredientUnitFuzzymatch.php in Recipe 8.2
File
modules/ingredient/src/Utility/IngredientUnitFuzzymatch.php
View source
<?php
namespace Drupal\ingredient\Utility;
use Drupal\Core\Config\ConfigFactory;
class IngredientUnitFuzzymatch {
protected $ingredientUnitConfig;
public function __construct(ConfigFactory $config_factory) {
$this->ingredientUnitConfig = $config_factory
->get('ingredient.units');
}
public function getUnitFuzzymatch($subject) {
$unit_sets = $this->ingredientUnitConfig
->get('unit_sets');
$units = [];
foreach ($unit_sets as $set) {
$units = array_merge($units, $set['units']);
}
if (empty($subject)) {
$subject = 'unit';
}
foreach ($units as $unit_key => $unit) {
$patterns = [];
$patterns[] = '^' . $unit['name'] . 's{0,1}$';
if (isset($unit['plural'])) {
$patterns[] = '^' . $unit['plural'] . 's{0,1}$';
}
if (isset($unit['abbreviation'])) {
$patterns[] = '^' . $unit['abbreviation'] . 's{0,1}\\.{0,1}$';
}
if (isset($unit['aliases'])) {
foreach ($unit['aliases'] as $alias) {
$patterns[] = '^' . trim($alias) . 's{0,1}\\.{0,1}$';
}
}
if (preg_match("/" . implode('|', $patterns) . "/", $subject)) {
return $unit_key;
}
}
foreach ($units as $unit_key => $unit) {
$patterns = [];
$patterns[] = '^' . $unit['name'] . 's{0,1}$';
if (isset($unit['plural'])) {
$patterns[] = '^' . $unit['plural'] . 's{0,1}$';
}
if (isset($unit['abbreviation'])) {
$patterns[] = '^' . $unit['abbreviation'] . 's{0,1}\\.{0,1}$';
}
if (isset($unit['aliases'])) {
foreach ($unit['aliases'] as $alias) {
$patterns[] = '^' . trim($alias) . 's{0,1}\\.{0,1}$';
}
}
if (preg_match("/" . implode('|', $patterns) . "/i", $subject)) {
return $unit_key;
}
}
return FALSE;
}
}