Advertisement
MBrendecke

LambdaFilter2

May 25th, 2020
943
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.00 KB | None | 0 0
  1. <?php
  2.  
  3. class Kategorie
  4. {
  5.     const Mathematik = "mathematik";
  6.     const Wissenschaft = "wissenschaft";
  7.     const Mechanik = "mechanik";
  8.     const Roman = "roman";
  9. }
  10.  
  11. class Produkt
  12. {
  13.     public $name;
  14.     public $kategorie;
  15.  
  16.     /**
  17.      * Produkt constructor.
  18.      * @param string $name
  19.      * @param string[] $kategorien
  20.      */
  21.     public function __construct($name, ...$kategorien)
  22.     {
  23.         $this->name = $name ?? "";
  24.         $this->kategorie = $kategorien ?? [];
  25.     }
  26. }
  27.  
  28. function findAll(array $items, array $predicates)
  29. {
  30.     $retVal = $items;
  31.     foreach ($predicates as $match) {
  32.         $temp = [];
  33.         foreach ($retVal as $value) {
  34.             if ($match($value)) {
  35.                 $temp[] = $value;
  36.             }
  37.         }
  38.         $retVal = $temp;
  39.     }
  40.     return $retVal;
  41. }
  42.  
  43. $k_filter = function (string $kategorie): Closure {
  44.     return function (Produkt $p) use ($kategorie): bool {
  45.         foreach ($p->kategorie as $k) {
  46.             if ($k === $kategorie) {
  47.                 return true;
  48.             }
  49.         }
  50.         return false;
  51.     };
  52. };
  53.  
  54. $produkte = [
  55.     new Produkt("Eine kurze Geschichte der Zeit", Kategorie::Wissenschaft, Kategorie::Mathematik),
  56.     new Produkt("Tropic of calculess", Kategorie::Mathematik),
  57.     new Produkt("Über die Himmelmechanik", Kategorie::Mechanik),
  58.     new Produkt("Momo", Kategorie::Roman)
  59. ];
  60.  
  61. $filters = [
  62.     $k_filter(Kategorie::Mathematik),
  63.     $k_filter(Kategorie::Wissenschaft)
  64. ];
  65. print_r(findAll($produkte, $filters));
  66.  
  67. $l_filter = function (int $length): Closure {
  68.   return function (Produkt $p) use ($length): bool {
  69.       return strlen($p->name) < $length;
  70.   };
  71. };
  72.  
  73. $filters = [
  74.     $k_filter(Kategorie::Mathematik),
  75.     $l_filter(20)
  76. ];
  77. print_r(findAll($produkte, $filters));
  78.  
  79. $filters = [
  80.     (function (): Closure {
  81.         return function (Produkt $p): bool {
  82.             return
  83.                 strlen($p->name) < 20;
  84.         };
  85.     })()
  86. ];
  87. print_r(findAll($produkte, $filters));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement