|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace TypeLang\Mapper\Mapping\Reader\ReflectionReader; |
| 6 | + |
| 7 | +use TypeLang\Mapper\Mapping\Metadata\ClassMetadata\PropertyInfo; |
| 8 | +use TypeLang\Mapper\Mapping\Metadata\ClassMetadata\PropertyMetadata\DefaultValueInfo; |
| 9 | + |
| 10 | +final class DefaultValuePropertyReflectionLoader extends PropertyReflectionLoader |
| 11 | +{ |
| 12 | + public function load(PropertyInfo $info, \ReflectionProperty $property): void |
| 13 | + { |
| 14 | + $this->loadPropertyDefaultValue($info, $property); |
| 15 | + $this->loadPromotedPropertyDefaultValue($info, $property); |
| 16 | + } |
| 17 | + |
| 18 | + private function loadPromotedPropertyDefaultValue(PropertyInfo $info, \ReflectionProperty $property): void |
| 19 | + { |
| 20 | + if (!$property->isPromoted()) { |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + $parameter = $this->findParameterByProperty($property); |
| 25 | + |
| 26 | + if ($parameter === null) { |
| 27 | + return; |
| 28 | + } |
| 29 | + |
| 30 | + if (!$parameter->isDefaultValueAvailable()) { |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + $info->default = new DefaultValueInfo( |
| 35 | + value: $parameter->getDefaultValue(), |
| 36 | + ); |
| 37 | + } |
| 38 | + |
| 39 | + private function findParameterByProperty(\ReflectionProperty $property): ?\ReflectionParameter |
| 40 | + { |
| 41 | + $class = $property->getDeclaringClass(); |
| 42 | + $constructor = $class->getConstructor(); |
| 43 | + |
| 44 | + if ($constructor === null) { |
| 45 | + return null; |
| 46 | + } |
| 47 | + |
| 48 | + foreach ($constructor->getParameters() as $parameter) { |
| 49 | + // Skip non-promoted properties |
| 50 | + if (!$parameter->isPromoted()) { |
| 51 | + continue; |
| 52 | + } |
| 53 | + |
| 54 | + if ($parameter->name === $property->name) { |
| 55 | + return $parameter; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return null; |
| 60 | + } |
| 61 | + |
| 62 | + private function loadPropertyDefaultValue(PropertyInfo $info, \ReflectionProperty $property): void |
| 63 | + { |
| 64 | + if (!$property->hasDefaultValue()) { |
| 65 | + $this->loadPromotedPropertyDefaultValue($info, $property); |
| 66 | + |
| 67 | + return; |
| 68 | + } |
| 69 | + |
| 70 | + $info->default = new DefaultValueInfo( |
| 71 | + value: $property->getDefaultValue(), |
| 72 | + ); |
| 73 | + } |
| 74 | +} |
0 commit comments