|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +/** |
| 4 | + * HydratorsContainer.php |
| 5 | + * |
| 6 | + * @license More in LICENSE.md |
| 7 | + * @copyright https://www.fastybird.com |
| 8 | + * @author Adam Kadlec <[email protected]> |
| 9 | + * @package FastyBird:JsonApi! |
| 10 | + * @subpackage Hydrators |
| 11 | + * @since 0.7.0 |
| 12 | + * |
| 13 | + * @date 11.01.22 |
| 14 | + */ |
| 15 | + |
| 16 | +namespace FastyBird\JsonApi\Hydrators; |
| 17 | + |
| 18 | +use FastyBird\JsonApi\JsonApi; |
| 19 | +use IPub\JsonAPIDocument; |
| 20 | +use SplObjectStorage; |
| 21 | + |
| 22 | +/** |
| 23 | + * API hydrators container |
| 24 | + * |
| 25 | + * @package FastyBird:JsonApi! |
| 26 | + * @subpackage Hydrators |
| 27 | + */ |
| 28 | +class HydratorsContainer |
| 29 | +{ |
| 30 | + |
| 31 | + /** @var SplObjectStorage<Hydrator, null> */ |
| 32 | + private SplObjectStorage $hydrators; |
| 33 | + |
| 34 | + /** @var JsonApi\JsonApiSchemaContainer */ |
| 35 | + private JsonApi\JsonApiSchemaContainer $jsonApiSchemaContainer; |
| 36 | + |
| 37 | + public function __construct( |
| 38 | + JsonApi\JsonApiSchemaContainer $jsonApiSchemaContainer |
| 39 | + ) { |
| 40 | + $this->jsonApiSchemaContainer = $jsonApiSchemaContainer; |
| 41 | + |
| 42 | + $this->hydrators = new SplObjectStorage(); |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * @param JsonAPIDocument\IDocument $document |
| 47 | + * |
| 48 | + * @return Hydrator|null |
| 49 | + * |
| 50 | + * @phpstan-return Hydrator|null |
| 51 | + */ |
| 52 | + public function findHydrator(JsonAPIDocument\IDocument $document): ?Hydrator |
| 53 | + { |
| 54 | + $this->hydrators->rewind(); |
| 55 | + |
| 56 | + foreach ($this->hydrators as $hydrator) { |
| 57 | + $schema = $this->jsonApiSchemaContainer->getSchemaByClassName($hydrator->getEntityName()); |
| 58 | + |
| 59 | + if ($schema->getType() === $document->getResource()->getType()) { |
| 60 | + return $hydrator; |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return null; |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * @param Hydrator $hydrator |
| 69 | + * |
| 70 | + * @return void |
| 71 | + * |
| 72 | + * @phpstan-param Hydrator $hydrator |
| 73 | + */ |
| 74 | + public function add(Hydrator $hydrator): void |
| 75 | + { |
| 76 | + if (!$this->hydrators->contains($hydrator)) { |
| 77 | + $this->hydrators->attach($hydrator); |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | +} |
0 commit comments