|
| 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 | + protected function mappingUploadFiles(array $operations, array $map, array $files) |
| 18 | + { |
| 19 | + $accessor = PropertyAccess::createPropertyAccessorBuilder() |
| 20 | + ->enableExceptionOnInvalidIndex() |
| 21 | + ->getPropertyAccessor(); |
| 22 | + |
| 23 | + foreach ($map as $fileName => $locations) { |
| 24 | + foreach ($locations as $location) { |
| 25 | + $fileKey = sprintf('[%s]', $fileName); |
| 26 | + if (!$accessor->isReadable($files, $fileKey)) { |
| 27 | + throw new BadRequestHttpException(sprintf('File %s is missing in the request.', json_encode($fileName))); |
| 28 | + } |
| 29 | + $file = $accessor->getValue($files, $fileKey); |
| 30 | + $locationKey = $this->locationToPropertyAccessPath($location); |
| 31 | + if (!$accessor->isReadable($operations, $locationKey)) { |
| 32 | + throw new BadRequestHttpException(sprintf('Map entry %s could not be localized in operations.', json_encode($location))); |
| 33 | + } |
| 34 | + $accessor->setValue($operations, $locationKey, $file); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + return $operations; |
| 39 | + } |
| 40 | + |
| 41 | + protected function locationToPropertyAccessPath($location) |
| 42 | + { |
| 43 | + return array_reduce( |
| 44 | + explode('.', $location), |
| 45 | + function ($carry, $item) { |
| 46 | + return sprintf('%s[%s]', $carry, $item); |
| 47 | + } |
| 48 | + ); |
| 49 | + } |
| 50 | + |
| 51 | + protected function isUploadPayload(array $payload) |
| 52 | + { |
| 53 | + return isset($payload['operations']) && isset($payload['map']) && is_array($payload['operations']) && is_array($payload['map']); |
| 54 | + } |
| 55 | + |
| 56 | + protected function treatUploadFiles(array $parsedBody, array $files) |
| 57 | + { |
| 58 | + if ($this->isUploadPayload($parsedBody)) { |
| 59 | + return $this->mappingUploadFiles($parsedBody['operations'], $parsedBody['map'], $files); |
| 60 | + } else { |
| 61 | + return $parsedBody; |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments