|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of the Silverback API Components Bundle Project |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Daniel West <[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 Silverback\ApiComponentsBundle\Action\Uploadable; |
|
15
|
|
|
|
|
16
|
|
|
use Silverback\ApiComponentsBundle\Exception\InvalidArgumentException; |
|
17
|
|
|
use Silverback\ApiComponentsBundle\Uploadable\UploadableHelper; |
|
18
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
19
|
|
|
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; |
|
20
|
|
|
use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @author Daniel West <[email protected]> |
|
24
|
|
|
*/ |
|
25
|
|
|
class UploadAction |
|
26
|
|
|
{ |
|
27
|
|
|
public function __invoke(?object $data, Request $request, UploadableHelper $uploadableHelper) |
|
28
|
|
|
{ |
|
29
|
|
|
$contentType = $request->headers->get('CONTENT_TYPE'); |
|
30
|
|
|
if (null === $contentType) { |
|
|
|
|
|
|
31
|
|
|
throw new UnsupportedMediaTypeHttpException('The "Content-Type" header must exist.'); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
$formats = ['multipart/form-data']; |
|
35
|
|
|
if (!\in_array(strtolower($contentType), $formats, true)) { |
|
36
|
|
|
throw new UnsupportedMediaTypeHttpException(sprintf('The content-type "%s" is not supported. Supported MIME type is "%s".', $contentType, implode('", "', $formats))); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
$resourceClass = $request->attributes->get('_api_resource_class'); |
|
40
|
|
|
$resource = $data ?? new $resourceClass(); |
|
41
|
|
|
|
|
42
|
|
|
try { |
|
43
|
|
|
$uploadableHelper->setUploadedFilesFromFileBag($resource, $request->files); |
|
44
|
|
|
} catch (InvalidArgumentException $exception) { |
|
45
|
|
|
throw new BadRequestHttpException($exception->getMessage()); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
$request->attributes->set('data', $resource); |
|
49
|
|
|
|
|
50
|
|
|
return $resource; |
|
51
|
|
|
} |
|
52
|
|
|
} |
|
53
|
|
|
|