Completed
Pull Request — master (#1645)
by Yanick
32:16
created

BatchEndpointAction   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 125
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 6

Importance

Changes 0
Metric Value
wmc 12
lcom 2
cbo 6
dl 0
loc 125
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B __invoke() 0 30 4
A convertResponse() 0 8 1
A validateBatchData() 0 14 4
A executeSubRequest() 0 11 2
1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Action;
15
use Symfony\Component\HttpFoundation\Request;
16
use Symfony\Component\HttpFoundation\Response;
17
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
18
use Symfony\Component\HttpKernel\HttpKernelInterface;
19
20
/**
21
 * Provides an endpoint for batch processing by splitting up
22
 *
23
 * @author Yanick Witschi <[email protected]>
24
 */
25
class BatchEndpointAction
26
{
27
    /**
28
     * @var HttpKernelInterface
29
     */
30
    private $kernel;
31
32
    /**
33
     * @var array
34
     */
35
    private $validKeys = [
36
        'path',
37
        'method',
38
        'headers',
39
        'body',
40
    ];
41
42
    /**
43
     * @param HttpKernelInterface $kernel
44
     */
45
    public function __construct(HttpKernelInterface $kernel)
46
    {
47
        $this->kernel = $kernel;
48
    }
49
50
    /**
51
     * Execute multiple subrequests from batch request.
52
     *
53
     * @param Request $request
54
     * @param array   $data
55
     *
56
     * @return array
57
     */
58
    public function __invoke(Request $request, array $data = null): array
59
    {
60
        if (!$this->validateBatchData((array) $data)) {
61
            throw new BadRequestHttpException('Batch request data not accepted.');
62
        }
63
64
        $result = [];
65
66
        foreach ($data as $k => $item) {
0 ignored issues
show
Bug introduced by
The expression $data of type null|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
67
68
            // Copy current headers if no specific provided for simplicity
69
            // otherwise one would have to provide Content-Type with every
70
            // single entry.
71
            if (!isset($item['headers'])) {
72
                $item['headers'] = $request->headers->all();
73
            }
74
75
            $result[] = $this->convertResponse(
76
                $this->executeSubRequest(
77
                    $k,
78
                    $item['path'],
79
                    $item['method'],
80
                    $item['headers'],
81
                    $item['body']
82
                )
83
            );
84
        }
85
86
        return $result;
87
    }
88
89
    /**
90
     * Converts a response into an array.
91
     *
92
     * @param Response $response
93
     *
94
     * @return array
95
     */
96
    private function convertResponse(Response $response): array
97
    {
98
        return [
99
            'status' => $response->getStatusCode(),
100
            'body' => $response->getContent(),
101
            'headers' => $response->headers->all(),
102
        ];
103
    }
104
105
    /**
106
     * Validates that the keys are all correctly present.
107
     *
108
     * @param array $data
109
     *
110
     * @return bool
111
     */
112
    private function validateBatchData(array $data)
113
    {
114
        if (0 === count($data)) {
115
            return false;
116
        }
117
118
        foreach ($data as $item) {
119
            if (0 !== count(array_diff(array_keys($item), $this->validKeys))) {
120
                return false;
121
            }
122
        }
123
124
        return true;
125
    }
126
127
    /**
128
     * Executes a subrequest.
129
     *
130
     * @param int    $index
131
     * @param string $path
132
     * @param string $method
133
     * @param array  $headers
134
     * @param string $body
135
     *
136
     * @return Response
137
     */
138
    private function executeSubRequest(int $index, string $path, string $method, array $headers, string $body): Response
139
    {
140
        $subRequest = Request::create($path, $method, [], [], [], [], $body);
141
        $subRequest->headers->replace($headers);
142
143
        try {
144
            return $this->kernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
145
        } catch (\Exception $e) {
146
            return Response::create(sprintf('Batch element #%d failed, check the log files.', $index), 400);
147
        }
148
    }
149
}
150