Completed
Push — master ( 286024...f3e7b4 )
by Luc
13s
created

ImageController::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 3
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
namespace VSV\GVQ_API\Image\Controllers;
4
5
use League\Flysystem\Filesystem;
6
use Ramsey\Uuid\Uuid;
7
use Ramsey\Uuid\UuidFactoryInterface;
8
use Symfony\Component\HttpFoundation\File\UploadedFile;
9
use Symfony\Component\HttpFoundation\FileBag;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use VSV\GVQ_API\Image\Validation\UploadFileValidator;
13
14
class ImageController
15
{
16
    /**
17
     * @var Filesystem
18
     */
19
    private $fileSystem;
20
21
    /**
22
     * @var UploadFileValidator
23
     */
24
    private $imageValidator;
25
26
    /**
27
     * @var UuidFactoryInterface
28
     */
29
    private $uuidFactory;
30
31
    /**
32
     * @param Filesystem $fileSystem
33
     * @param UploadFileValidator $imageValidator
34
     * @param UuidFactoryInterface $uuidFactory
35
     */
36
    public function __construct(
37
        Filesystem $fileSystem,
38
        UploadFileValidator $imageValidator,
39
        UuidFactoryInterface $uuidFactory
40
    ) {
41
        $this->fileSystem = $fileSystem;
42
        $this->imageValidator = $imageValidator;
43
        $this->uuidFactory = $uuidFactory;
44
    }
45
46
    /**
47
     * @param Request $request
48
     * @return Response
49
     * @throws \League\Flysystem\FileExistsException
50
     */
51
    public function upload(Request $request): Response
52
    {
53
        $uploadFile = $this->guardFiles($request->files);
54
55
        $uuid = $this->uuidFactory->uuid4();
56
        $filename = $uuid->toString().'.'. $uploadFile->getClientOriginalExtension();
57
58
        $stream = fopen($uploadFile->getRealPath(), 'r+');
59
        $this->fileSystem->writeStream($filename, $stream);
60
        fclose($stream);
61
62
        $response = new Response('{"filename":"'.$filename.'"}');
63
        $response->headers->set('Content-Type', 'application/json');
64
65
        return $response;
66
    }
67
68
    /**
69
     * @param FileBag $files
70
     * @return UploadedFile
71
     */
72
    private function guardFiles(FileBag $files): UploadedFile
73
    {
74
        if (count($files) !== 1) {
75
            throw new \InvalidArgumentException('Exactly one image is required.');
76
        }
77
78
        if (empty($files->get('image'))) {
79
            throw new \InvalidArgumentException('Key image is required inside form-data.');
80
        }
81
82
        /** @var UploadedFile $uploadFile */
83
        $uploadFile = $files->get('image');
84
85
        $this->imageValidator->validate($uploadFile);
86
87
        return $uploadFile;
88
    }
89
}
90