Lines
100.00%
21 / 21
Functions and Methods
100.00%
2 / 2
Classes and Traits
100.00%
1 / 1
| Name | Lines | Functions and Methods | CRAP | Classes and Traits | ||||||
|---|---|---|---|---|---|---|---|---|---|---|
| DomainEntitiesEmitter | 100.00% | 21 / 21 | 100.00% | 2 / 2 | 2 | 100.00% | 1 / 1 | |||
| supportsDomain | 100.00% | 1 / 1 | 100.00% | 1 / 1 | 1 | |||||
| emitFile | 100.00% | 20 / 20 | 100.00% | 1 / 1 | 1 | |||||
| 1 | <?php | |
| 2 | ||
| 3 | declare(strict_types=1); | |
| 4 | ||
| 5 | namespace Stewart\Codegen\Emitter\Entity; | |
| 6 | ||
| 7 | use Stewart\Codegen\Emitter\DomainFileEmitter; | |
| 8 | use Stewart\Codegen\Emitter\EmitContext; | |
| 9 | use Stewart\Codegen\Model\DomainModel; | |
| 10 | use Stewart\Codegen\Output\GeneratedFile; | |
| 11 | use Stewart\Contracts\Entity\EntityId; | |
| 12 | use Stewart\Contracts\Exception\IdentifierException; | |
| 13 | use Stewart\Contracts\HaContext; | |
| 14 | ||
| 15 | final readonly class DomainEntitiesEmitter implements DomainFileEmitter | |
| 16 | { | |
| 17 | public function supportsDomain(DomainModel $domain): bool | |
| 18 | { | |
| 19 | return $domain->hasEntities(); | |
| 20 | } | |
| 21 | ||
| 22 | public function emitFile(DomainModel $domain, EmitContext $context): GeneratedFile | |
| 23 | { | |
| 24 | $namespace = $context->createNamespace(); | |
| 25 | $declared = $domain->getEntitiesClass(); | |
| 26 | $context->importClass($namespace, HaContext::class, $declared); | |
| 27 | $entityId = $context->importClass($namespace, EntityId::class, $declared); | |
| 28 | $identifierException = $context->importClass($namespace, IdentifierException::class, $declared); | |
| 29 | ||
| 30 | $class = $namespace->addClass($declared) | |
| 31 | ->setFinal() | |
| 32 | ->setReadOnly() | |
| 33 | ->addComment(\sprintf('The `%s` entities.', $domain->domain)); | |
| 34 | ||
| 35 | $class->addMethod('__construct') | |
| 36 | ->addPromotedParameter('ha') | |
| 37 | ->setType(HaContext::class) | |
| 38 | ->setPrivate(); | |
| 39 | ||
| 40 | $class->addMethod('getEntity') | |
| 41 | ->setReturnType($context->resolveClassName($domain->getHandleClass())) | |
| 42 | ->addComment('@throws ' . $identifierException) | |
| 43 | ->setBody(\sprintf('return new %s($this->ha, %s::fromStringOrId($id));', $domain->getHandleClass(), $entityId)) | |
| 44 | ->addParameter('id') | |
| 45 | ->setType('string|' . EntityId::class); | |
| 46 | ||
| 47 | return $context->printFile($namespace, $declared); | |
| 48 | } | |
| 49 | } |