DataTransformer   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
eloc 26
c 1
b 0
f 0
dl 0
loc 55
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A transformArray() 0 11 3
A transform() 0 20 6
A applyTransformations() 0 12 2
1
<?php
2
3
/**
4
 * @author     Oleh Boiko <[email protected]>
5
 *
6
 * @site       https://mackrais.com
7
 *
8
 * @copyright  2014-2025 MackRais
9
 *
10
 * @date: 15.03.25
11
 */
12
13
declare(strict_types=1);
14
15
namespace MackRais\PropertyTransform;
16
17
class DataTransformer
18
{
19
    public function __construct(private readonly TransformerFactory $transformerFactory)
20
    {
21
    }
22
23
    public function transform(object $object): void
24
    {
25
        $reflectionClass = new \ReflectionClass($object);
26
27
        foreach ($reflectionClass->getProperties() as $property) {
28
            $attributes = $property->getAttributes(Transform::class);
29
30
            if (\count($attributes) > 0) {
31
                $value = $property->getValue($object);
32
33
                if (\is_array($value)) {
34
                    $value = $this->applyTransformations($value, $attributes);
35
                    $value = $this->transformArray(\is_array($value) ? $value : [], $attributes);
36
                } elseif (\is_object($value)) {
37
                    $this->transform($value);
38
                } else {
39
                    $value = $this->applyTransformations($value, $attributes);
40
                }
41
42
                $property->setValue($object, $value);
43
            }
44
        }
45
    }
46
47
    private function transformArray(array $array, array $attributes): array
48
    {
49
        foreach ($array as &$item) {
50
            if (\is_object($item)) {
51
                $this->transform($item);
52
            } else {
53
                $item = $this->applyTransformations($item, $attributes);
54
            }
55
        }
56
57
        return $array;
58
    }
59
60
    private function applyTransformations(mixed $value, array $attributes): mixed
61
    {
62
        foreach ($attributes as $attribute) {
63
            /** @var Transform $transformInstance */
64
            $transformInstance = $attribute->newInstance();
65
            $transformer = $this->transformerFactory->create($transformInstance->getTransformer());
66
            $params = $transformInstance->getParams();
67
68
            $value = $transformer($value, ...$params);
69
        }
70
71
        return $value;
72
    }
73
}
74