|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Patchlevel\Hydrator; |
| 6 | + |
| 7 | +use Patchlevel\Hydrator\Guesser\ChainGuesser; |
| 8 | +use Patchlevel\Hydrator\Guesser\Guesser; |
| 9 | +use Patchlevel\Hydrator\Metadata\AttributeMetadataFactory; |
| 10 | +use Patchlevel\Hydrator\Metadata\MetadataEnricher; |
| 11 | +use Patchlevel\Hydrator\Middleware\Middleware; |
| 12 | + |
| 13 | +use function array_merge; |
| 14 | +use function krsort; |
| 15 | + |
| 16 | +final class HydratorBuilder |
| 17 | +{ |
| 18 | + private bool $defaultLazy = false; |
| 19 | + |
| 20 | + /** @var array<int, list<Middleware>> */ |
| 21 | + private array $middlewares = []; |
| 22 | + |
| 23 | + /** @var array<int, list<MetadataEnricher>> */ |
| 24 | + private array $metadataEnrichers = []; |
| 25 | + |
| 26 | + /** @var array<int, list<Guesser>> */ |
| 27 | + private array $guessers = []; |
| 28 | + |
| 29 | + /** @return $this */ |
| 30 | + public function addMiddleware(Middleware $middleware, int $priority = 0): static |
| 31 | + { |
| 32 | + $this->middlewares[$priority][] = $middleware; |
| 33 | + |
| 34 | + return $this; |
| 35 | + } |
| 36 | + |
| 37 | + /** @return $this */ |
| 38 | + public function addMetadataEnricher(MetadataEnricher $enricher, int $priority = 0): static |
| 39 | + { |
| 40 | + $this->metadataEnrichers[$priority][] = $enricher; |
| 41 | + |
| 42 | + return $this; |
| 43 | + } |
| 44 | + |
| 45 | + /** @return $this */ |
| 46 | + public function addGuesser(Guesser $guesser, int $priority = 0): static |
| 47 | + { |
| 48 | + $this->guessers[$priority][] = $guesser; |
| 49 | + |
| 50 | + return $this; |
| 51 | + } |
| 52 | + |
| 53 | + public function enableDefaultLazy(bool $lazy = true): static |
| 54 | + { |
| 55 | + $this->defaultLazy = $lazy; |
| 56 | + |
| 57 | + return $this; |
| 58 | + } |
| 59 | + |
| 60 | + public function useExtension(Extension $extension): static |
| 61 | + { |
| 62 | + $extension->configure($this); |
| 63 | + |
| 64 | + return $this; |
| 65 | + } |
| 66 | + |
| 67 | + public function build(): Hydrator |
| 68 | + { |
| 69 | + krsort($this->middlewares); |
| 70 | + krsort($this->metadataEnrichers); |
| 71 | + krsort($this->guessers); |
| 72 | + |
| 73 | + return new MetadataHydrator( |
| 74 | + new AttributeMetadataFactory( |
| 75 | + guesser: new ChainGuesser([...array_merge(...$this->guessers)]), |
| 76 | + ), |
| 77 | + [...array_merge(...$this->middlewares)], |
| 78 | + [...array_merge(...$this->metadataEnrichers)], |
| 79 | + $this->defaultLazy, |
| 80 | + ); |
| 81 | + } |
| 82 | +} |
0 commit comments