public function IngredientUnitFuzzymatch::getUnitFuzzymatch in Recipe 8.2
Returns a best-guess matched unit key for a unit of measure.
Parameters
string $subject: The unit of measure for which the function will search.
Return value
string|false The unit's key from configuration or FALSE if there was no match.
File
- modules/
ingredient/ src/ Utility/ IngredientUnitFuzzymatch.php, line 38
Class
- IngredientUnitFuzzymatch
- Provides the ingredient.fuzzymatch service.
Namespace
Drupal\ingredient\UtilityCode
public function getUnitFuzzymatch($subject) {
$unit_sets = $this->ingredientUnitConfig
->get('unit_sets');
// Merge the unit sets into a single array for simplicity.
$units = [];
foreach ($unit_sets as $set) {
$units = array_merge($units, $set['units']);
}
// Empty strings should use the default non-printing 'unit'.
if (empty($subject)) {
$subject = 'unit';
}
// First pass unit case must match exactly( T=Tbsp, t=tsp ).
foreach ($units as $unit_key => $unit) {
$patterns = [];
// Add name pattern.
$patterns[] = '^' . $unit['name'] . 's{0,1}$';
if (isset($unit['plural'])) {
// Add plural name pattern.
$patterns[] = '^' . $unit['plural'] . 's{0,1}$';
}
if (isset($unit['abbreviation'])) {
// Add abbreviation pattern.
$patterns[] = '^' . $unit['abbreviation'] . 's{0,1}\\.{0,1}$';
}
if (isset($unit['aliases'])) {
// Add alias patterns.
foreach ($unit['aliases'] as $alias) {
$patterns[] = '^' . trim($alias) . 's{0,1}\\.{0,1}$';
}
}
if (preg_match("/" . implode('|', $patterns) . "/", $subject)) {
return $unit_key;
}
}
// Second pass unit case doesn't matter.
foreach ($units as $unit_key => $unit) {
$patterns = [];
// Add name pattern.
$patterns[] = '^' . $unit['name'] . 's{0,1}$';
if (isset($unit['plural'])) {
// Add plural name pattern.
$patterns[] = '^' . $unit['plural'] . 's{0,1}$';
}
if (isset($unit['abbreviation'])) {
// Add abbreviation pattern.
$patterns[] = '^' . $unit['abbreviation'] . 's{0,1}\\.{0,1}$';
}
if (isset($unit['aliases'])) {
// Add alias patterns.
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;
}