Passed
Push — feature/uploadable ( 7c6d25...a7ed20 )
by Daniel
11:07
created

UploadableAction   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 15
dl 0
loc 26
ccs 0
cts 14
cp 0
rs 10
c 1
b 0
f 0
wmc 4

1 Method

Rating   Name   Duplication   Size   Complexity  
A __invoke() 0 24 4
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 UploadableAction
26
{
27
    public function __invoke(?object $data, Request $request, UploadableHelper $uploadableHelper)
28
    {
29
        $contentType = $request->headers->get('CONTENT_TYPE');
30
        if (null === $contentType) {
1 ignored issue
show
introduced by
The condition null === $contentType is always false.
Loading history...
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