|
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; |
|
|
|
|
|
|
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
|
|
|
|