|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Symfony package. |
| 5 | + * |
| 6 | + * (c) Fabien Potencier <[email protected]> |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + */ |
| 11 | + |
| 12 | +namespace App\Service; |
| 13 | + |
| 14 | +use App\Enum\AnimalzType; |
| 15 | +use App\Model\Animalz; |
| 16 | + |
| 17 | +class AnimalzRepository |
| 18 | +{ |
| 19 | + private const string DATA_FILE = __DIR__.'/data/animalz-properties.json'; |
| 20 | + |
| 21 | + /** @var list<Animalz>|null */ |
| 22 | + private ?array $zanimalz = null; |
| 23 | + |
| 24 | + /** |
| 25 | + * @return list<Animalz> |
| 26 | + */ |
| 27 | + public function findAll(): array |
| 28 | + { |
| 29 | + return $this->zanimalz ??= $this->loadZanimalz(); |
| 30 | + } |
| 31 | + |
| 32 | + /** |
| 33 | + * @return list<Animalz> |
| 34 | + */ |
| 35 | + public function findByNameAndTypeAndLegs(?string $name, ?AnimalzType $type, ?int $maxLegs): array |
| 36 | + { |
| 37 | + $zanimalz = $this->findAll(); |
| 38 | + |
| 39 | + if (null !== $name && '' !== $name) { |
| 40 | + $zanimalz = array_filter( |
| 41 | + $zanimalz, |
| 42 | + fn (Animalz $animalz): bool => str_contains( |
| 43 | + strtolower($animalz->getName()), |
| 44 | + strtolower($name), |
| 45 | + ), |
| 46 | + ); |
| 47 | + } |
| 48 | + |
| 49 | + if (null !== $type) { |
| 50 | + $zanimalz = array_filter( |
| 51 | + $zanimalz, |
| 52 | + fn (Animalz $animalz): bool => $animalz->hasType($type->value), |
| 53 | + ); |
| 54 | + } |
| 55 | + |
| 56 | + if (null !== $maxLegs) { |
| 57 | + $zanimalz = array_filter( |
| 58 | + $zanimalz, |
| 59 | + fn (Animalz $animalz): bool => $animalz->getLegs() <= $maxLegs, |
| 60 | + ); |
| 61 | + } |
| 62 | + |
| 63 | + $zanimalz = array_values($zanimalz); |
| 64 | + usort($zanimalz, fn (Animalz $a, Animalz $b): int => $a->getName() <=> $b->getName()); |
| 65 | + |
| 66 | + return $zanimalz; |
| 67 | + } |
| 68 | + |
| 69 | + public function getMaxLegs(): int |
| 70 | + { |
| 71 | + $zanimalz = $this->findAll(); |
| 72 | + |
| 73 | + return max(array_map(fn (Animalz $a): int => $a->getLegs(), $zanimalz)); |
| 74 | + } |
| 75 | + |
| 76 | + /** |
| 77 | + * @return list<Animalz> |
| 78 | + */ |
| 79 | + private function loadZanimalz(): array |
| 80 | + { |
| 81 | + $content = file_get_contents(self::DATA_FILE); |
| 82 | + |
| 83 | + if (false === $content) { |
| 84 | + return []; |
| 85 | + } |
| 86 | + |
| 87 | + $data = json_decode($content, true, 512, \JSON_THROW_ON_ERROR); |
| 88 | + |
| 89 | + return array_map( |
| 90 | + fn (array $item): Animalz => new Animalz($item['name'], $item['type'], $item['legs'], $item['description']), |
| 91 | + $data, |
| 92 | + ); |
| 93 | + } |
| 94 | +} |
0 commit comments