RequestTransform::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace CCT\Component\Rest\Http\Transform;
6
7
use CCT\Component\Rest\Serializer\ContextInterface;
8
use CCT\Component\Rest\Transformer\Request\RequestTransformerInterface;
9
10
class RequestTransform implements RequestTransformInterface
11
{
12
    /**
13
     * @var RequestTransformerInterface[]|\Closure[]
14
     */
15
    protected $transformers;
16
17
    /**
18
     * RequestTransform constructor.
19
     *
20
     * @param array $transformers
21
     */
22 7
    public function __construct(array $transformers = [])
23
    {
24 7
        $this->transformers = $transformers;
25 7
    }
26
27
    /**
28
     * Tries to identify the data object sent, and convert them
29
     * into an array properly handled
30
     *
31
     * @param array|object $formData
32
     * @param ContextInterface|null $context
33
     *
34
     * @return array|object
35
     */
36 6
    public function transform($formData = [], ContextInterface $context = null): array
37
    {
38 6
        if (empty($formData)) {
39 3
            return $formData;
40
        }
41
42 3
        foreach ($this->transformers as $transformer) {
43 3
            $formData = $this->applyRequestTransformers($transformer, $formData, $context);
44
        }
45
46 3
        return $formData;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $formData could return the type object which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
47
    }
48
49
    /**
50
     * Applied single request transformer
51
     *
52
     * @param RequestTransformerInterface|\Closure $transformer
53
     * @param array|object $formData
54
     * @param ContextInterface|null $context
55
     *
56
     * @return array|mixed
57
     */
58 3
    protected function applyRequestTransformers($transformer, $formData, ContextInterface $context = null)
59
    {
60 3
        if ($transformer instanceof RequestTransformerInterface && $transformer->supports($formData)) {
61 1
            return $transformer->transform($formData, $context);
62
        }
63
64 2
        if ($transformer instanceof \Closure) {
65 1
            return $transformer($formData);
66
        }
67
68 1
        return $formData;
69
    }
70
}
71