1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Overblog\GraphQLBundle\Request; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; |
6
|
|
|
use Symfony\Component\PropertyAccess\PropertyAccess; |
7
|
|
|
|
8
|
|
|
trait UploadParserTrait |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @param array $operations |
12
|
|
|
* @param array $map |
13
|
|
|
* @param array $files |
14
|
|
|
* |
15
|
|
|
* @return array |
16
|
|
|
*/ |
17
|
10 |
|
protected function mappingUploadFiles(array $operations, array $map, array $files) |
18
|
|
|
{ |
19
|
10 |
|
$accessor = PropertyAccess::createPropertyAccessorBuilder() |
20
|
10 |
|
->enableExceptionOnInvalidIndex() |
21
|
10 |
|
->getPropertyAccessor(); |
22
|
|
|
|
23
|
10 |
|
foreach ($map as $fileName => $locations) { |
24
|
10 |
|
foreach ($locations as $location) { |
25
|
10 |
|
$fileKey = sprintf('[%s]', $fileName); |
26
|
10 |
|
if (!$accessor->isReadable($files, $fileKey)) { |
27
|
1 |
|
throw new BadRequestHttpException(sprintf('File %s is missing in the request.', json_encode($fileName))); |
28
|
|
|
} |
29
|
9 |
|
$file = $accessor->getValue($files, $fileKey); |
30
|
9 |
|
$locationKey = $this->locationToPropertyAccessPath($location); |
31
|
9 |
|
if (!$accessor->isReadable($operations, $locationKey)) { |
32
|
1 |
|
throw new BadRequestHttpException(sprintf('Map entry %s could not be localized in operations.', json_encode($location))); |
33
|
|
|
} |
34
|
8 |
|
$accessor->setValue($operations, $locationKey, $file); |
35
|
|
|
} |
36
|
|
|
} |
37
|
|
|
|
38
|
8 |
|
return $operations; |
39
|
|
|
} |
40
|
|
|
|
41
|
15 |
|
protected function locationToPropertyAccessPath($location) |
42
|
|
|
{ |
43
|
15 |
|
return array_reduce( |
44
|
15 |
|
explode('.', $location), |
45
|
15 |
|
function ($carry, $item) { |
46
|
15 |
|
return sprintf('%s[%s]', $carry, $item); |
47
|
15 |
|
} |
48
|
|
|
); |
49
|
|
|
} |
50
|
|
|
|
51
|
8 |
|
protected function isUploadPayload(array $payload) |
52
|
|
|
{ |
53
|
8 |
|
return isset($payload['operations']) && isset($payload['map']) && is_array($payload['operations']) && is_array($payload['map']); |
54
|
|
|
} |
55
|
|
|
|
56
|
7 |
|
protected function treatUploadFiles(array $parsedBody, array $files) |
57
|
|
|
{ |
58
|
7 |
|
if ($this->isUploadPayload($parsedBody)) { |
59
|
5 |
|
return $this->mappingUploadFiles($parsedBody['operations'], $parsedBody['map'], $files); |
60
|
|
|
} else { |
61
|
2 |
|
return $parsedBody; |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|