cookidoo-shopping-advanced/src/Rules/Simplify.php

57 lines
1.8 KiB
PHP

<?php
namespace CookidooShoppingAdvanced\Rules;
use CookidooShoppingAdvanced\Models\ShoppingList;
use CookidooShoppingAdvanced\Normalizer;
class Simplify extends AbstractRule {
private const SIMPLIFICATION_OMISSION = [ // obey the replacement order
'frisch gemahlen' => '',
'gemahlen' => '',
'selbst gemacht' => '',
'konserviert' => '',
'vegan' => '',
'mittelscharf' => '',
];
private const SIMPLIFICATION_MAPPING = [ // obey the replacement order
'Cayenne-Pfeffer' => 'Pfeffer',
'Paprikaschote' => 'Paprika',
'Schalotte' => 'Zwiebel',
'Erdäpfel' => 'Kartoffel',
'Paprikapulver' => 'Paprika',
'Essiggurkerl' => 'Essiggurken',
];
// Words the stemming algorithm cannot reduce
private const SIMPLIFICATION_STEMMS = [ // obey the replacement order
'Zwiebeln' => 'Zwiebel',
'Kartoffeln' => 'Kartoffel',
];
public function filter(ShoppingList &$shoppingList): void {
foreach($shoppingList as $key => $ingredient) {
$cleanName = $ingredient->getCleanName();
$search = $replace = [];
$mappings = array_merge(
self::SIMPLIFICATION_OMISSION,
self::SIMPLIFICATION_MAPPING,
self::SIMPLIFICATION_STEMMS
);
foreach($mappings as $simplify => $with) {
$simplify = Normalizer::normalize($simplify);
if (strpos($cleanName, $simplify) !== false) {
$search[] = $simplify;
$replace[] = Normalizer::normalize($with);
}
}
if (!empty($search)) {
$ingredient->setCleanName(trim(str_replace($search, $replace, $cleanName)));
$shoppingList[$key] = $ingredient;
}
}
}
}