Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
95.24% |
20 / 21 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
PropertyAttributeConverter | |
95.24% |
20 / 21 |
|
50.00% |
1 / 2 |
11 | |
0.00% |
0 / 1 |
applyToDomain | |
92.31% |
12 / 13 |
|
0.00% |
0 / 1 |
8.03 | |||
applyToStorage | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
3 |
1 | <?php |
2 | namespace Apie\StorageMetadata\PropertyConverters; |
3 | |
4 | use Apie\Core\Attributes\Optional; |
5 | use Apie\StorageMetadata\Attributes\GetMethodOrPropertyAttribute; |
6 | use Apie\StorageMetadata\Attributes\PropertyAttribute; |
7 | use Apie\StorageMetadata\Interfaces\PropertyConverterInterface; |
8 | use Apie\StorageMetadata\Mediators\DomainToStorageContext; |
9 | |
10 | class PropertyAttributeConverter implements PropertyConverterInterface |
11 | { |
12 | public function applyToDomain( |
13 | DomainToStorageContext $context |
14 | ): void { |
15 | $storageProperty = $context->storageProperty; |
16 | $propertyAttributes = [ |
17 | ...$storageProperty->getAttributes(PropertyAttribute::class), |
18 | ...$storageProperty->getAttributes(GetMethodOrPropertyAttribute::class), |
19 | ]; |
20 | foreach ($propertyAttributes as $propertyAttribute) { |
21 | $domainProperty = $propertyAttribute->newInstance()->getReflectionProperty($context->domainClass, $context->domainObject); |
22 | if ($domainProperty && (!$domainProperty->isInitialized($context->domainObject) || !$domainProperty->isReadOnly())) { |
23 | $domainPropertyType = $domainProperty->getType(); |
24 | $domainPropertyValue = $context->dynamicCast($context->getStoragePropertyValue(), $domainPropertyType); |
25 | if (!$domainPropertyType->allowsNull() && $domainPropertyValue === null && $domainProperty->getAttributes(Optional::class)) { |
26 | continue; |
27 | } |
28 | $domainProperty->setValue($context->domainObject, $domainPropertyValue); |
29 | } |
30 | } |
31 | } |
32 | |
33 | public function applyToStorage( |
34 | DomainToStorageContext $context |
35 | ): void { |
36 | $storageProperty = $context->storageProperty; |
37 | |
38 | foreach ($storageProperty->getAttributes(PropertyAttribute::class) as $propertyAttribute) { |
39 | $domainProperty = $propertyAttribute->newInstance()->getReflectionProperty($context->domainClass, $context->domainObject); |
40 | if ($domainProperty) { |
41 | $storagePropertyType = $storageProperty->getType(); |
42 | $domainPropertyValue = $domainProperty->getValue($context->domainObject); |
43 | $storagePropertyValue = $context->dynamicCast($domainPropertyValue, $storagePropertyType); |
44 | $context->setStoragePropertyValue($storagePropertyValue); |
45 | } |
46 | } |
47 | } |
48 | } |