ResponseTransform   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
dl 0
loc 56
ccs 15
cts 15
cp 1
rs 10
c 1
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A applyResponseTransformer() 0 12 4
A __construct() 0 3 1
A transform() 0 8 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace CCT\Component\Rest\Http\Transform;
6
7
use CCT\Component\Rest\Http\ResponseInterface;
8
use CCT\Component\Rest\Serializer\ContextInterface;
9
use CCT\Component\Rest\Transformer\Response\ResponseTransformerInterface;
10
11
class ResponseTransform implements ResponseTransformInterface
12
{
13
    /**
14
     * @var array
15
     */
16
    protected $transformers;
17
18
    /**
19
     * ResponseTransformer constructor.
20
     *
21
     * @param array $transformers
22
     */
23 7
    public function __construct(array $transformers = [])
24
    {
25 7
        $this->transformers = $transformers;
26 7
    }
27
28
    /**
29
     * It is possible to handle the Response data defining the Config key response_transformers
30
     * with an instance of Closure or an instance of TransformerInterface.
31
     *
32
     * @param ResponseInterface $response
33
     * @param ContextInterface|null $context
34
     *
35
     * @return void
36
     */
37 6
    public function transform(ResponseInterface $response, ContextInterface $context = null): void
38
    {
39 6
        if (null === $response->getData()) {
40 1
            return;
41
        }
42
43 5
        foreach ($this->transformers as $transformer) {
44 5
            $this->applyResponseTransformer($transformer, $response, $context);
45
        }
46 5
    }
47
48
    /**
49
     * Applied single response transformer
50
     *
51
     * @param ResponseTransformerInterface|\Closure $transformer
52
     * @param ResponseInterface $response
53
     * @param ContextInterface|null $context
54
     */
55 5
    protected function applyResponseTransformer(
56
        $transformer,
57
        ResponseInterface $response,
58
        ContextInterface $context = null
59
    ): void {
60 5
        if ($transformer instanceof ResponseTransformerInterface && $transformer->supports($response)) {
61 3
            $transformer->transform($response, $context);
62 3
            return;
63
        }
64
65 4
        if ($transformer instanceof \Closure) {
66 1
            $transformer($response);
67
        }
68 4
    }
69
}
70