<?php
class Kategorie
{
const Mathematik = "mathematik";
const Wissenschaft = "wissenschaft";
const Mechanik = "mechanik";
const Roman = "roman";
}
class Produkt
{
public $name;
public $kategorie;
/**
* Produkt constructor.
* @param string $name
* @param string[] $kategorien
*/
public function __construct($name, ...$kategorien)
{
$this->name = $name ?? "";
$this->kategorie = $kategorien ?? [];
}
}
function findAll(array $items, array $predicates)
{
$retVal = $items;
foreach ($predicates as $match) {
$temp = [];
foreach ($retVal as $value) {
if ($match($value)) {
$temp[] = $value;
}
}
$retVal = $temp;
}
return $retVal;
}
$k_filter = function (string $kategorie): Closure {
return function (Produkt $p) use ($kategorie): bool {
foreach ($p->kategorie as $k) {
if ($k === $kategorie) {
return true;
}
}
return false;
};
};
$produkte = [
new Produkt("Eine kurze Geschichte der Zeit", Kategorie::Wissenschaft, Kategorie::Mathematik),
new Produkt("Tropic of calculess", Kategorie::Mathematik),
new Produkt("Über die Himmelmechanik", Kategorie::Mechanik),
new Produkt("Momo", Kategorie::Roman)
];
$filters = [
$k_filter(Kategorie::Mathematik),
$k_filter(Kategorie::Wissenschaft)
];
print_r(findAll($produkte, $filters));
$l_filter = function (int $length): Closure {
return function (Produkt $p) use ($length): bool {
return strlen($p->name) < $length;
};
};
$filters = [
$k_filter(Kategorie::Mathematik),
$l_filter(20)
];
print_r(findAll($produkte, $filters));
$filters = [
(function (): Closure {
return function (Produkt $p): bool {
return
strlen($p->name) < 20;
};
})()
];
print_r(findAll($produkte, $filters));
Comments