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