Passed
Pull Request — master (#52)
by Daniel
06:20
created

UploadableAction   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 24
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 4
eloc 14
dl 0
loc 24
ccs 0
cts 13
cp 0
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 22 4
1
<?php
2
3
/*
4
 * This file is part of the Silverback API Component 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\ApiComponentBundle\Action\Uploadable;
15
16
use Silverback\ApiComponentBundle\Exception\InvalidArgumentException;
17
use Silverback\ApiComponentBundle\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 UploadableAction
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
        return $resource;
49
    }
50
}
51