|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace TypeLang\Mapper\Mapping\Introspection; |
| 6 | + |
| 7 | +use TypeLang\Mapper\Mapping\Metadata\ClassMetadata; |
| 8 | +use TypeLang\Mapper\Mapping\Metadata\PropertyMetadata; |
| 9 | +use TypeLang\Mapper\Runtime\Context; |
| 10 | +use TypeLang\Parser\Node\Stmt\NamedTypeNode; |
| 11 | +use TypeLang\Parser\Node\Stmt\Shape\FieldNode; |
| 12 | +use TypeLang\Parser\Node\Stmt\Shape\FieldsListNode; |
| 13 | +use TypeLang\Parser\Node\Stmt\Shape\NamedFieldNode; |
| 14 | +use TypeLang\Parser\Node\Stmt\TypeStatement; |
| 15 | + |
| 16 | +final class ClassIntrospection implements IntrospectionInterface |
| 17 | +{ |
| 18 | + public function __construct( |
| 19 | + /** |
| 20 | + * @var ClassMetadata<object> |
| 21 | + */ |
| 22 | + private readonly ClassMetadata $metadata, |
| 23 | + ) {} |
| 24 | + |
| 25 | + public function getTypeStatement(Context $context): TypeStatement |
| 26 | + { |
| 27 | + if (!$context->isDetailedTypes()) { |
| 28 | + return new NamedTypeNode($this->metadata->getName()); |
| 29 | + } |
| 30 | + |
| 31 | + $fields = []; |
| 32 | + |
| 33 | + foreach ($this->metadata->getProperties() as $property) { |
| 34 | + $fields[] = $this->getFieldNode($property, $context); |
| 35 | + } |
| 36 | + |
| 37 | + if ($fields === []) { |
| 38 | + return new NamedTypeNode($this->metadata->getName()); |
| 39 | + } |
| 40 | + |
| 41 | + return new NamedTypeNode($this->metadata->getName(), fields: new FieldsListNode($fields)); |
| 42 | + } |
| 43 | + |
| 44 | + private function getFieldNode(PropertyMetadata $metadata, Context $context): FieldNode |
| 45 | + { |
| 46 | + $name = $metadata->getName(); |
| 47 | + |
| 48 | + if ($context->isDenormalization()) { |
| 49 | + $name = $metadata->getExportName(); |
| 50 | + } |
| 51 | + |
| 52 | + return new NamedFieldNode( |
| 53 | + key: $name, |
| 54 | + of: $metadata->getTypeStatement($context), |
| 55 | + optional: $metadata->hasDefaultValue(), |
| 56 | + ); |
| 57 | + } |
| 58 | +} |
0 commit comments