Completed
Pull Request — master (#105)
by Kristof
10:56 queued 03:32
created

ImageUploaderService::getUploadDirectory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 4
rs 10
c 1
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace CultuurNet\UDB3\Media;
4
5
use Broadway\CommandHandling\CommandBusInterface;
6
use Broadway\UuidGenerator\UuidGeneratorInterface;
7
use CultuurNet\UDB3\Media\Commands\UploadImage;
8
use CultuurNet\UDB3\Media\Properties\MIMEType;
9
use League\Flysystem\FilesystemInterface;
10
use Symfony\Component\HttpFoundation\File\UploadedFile;
11
use ValueObjects\Identity\UUID;
12
use ValueObjects\String\String;
13
14
class ImageUploaderService implements ImageUploaderInterface
15
{
16
    /**
17
     * @var UuidGeneratorInterface
18
     */
19
    protected $uuidGenerator;
20
21
    /**
22
     * @var CommandBusInterface
23
     */
24
    protected $commandBus;
25
26
    /**
27
     * @var string
28
     */
29
    protected $uploadDirectory;
30
31
    /**
32
     * @var FilesystemInterface
33
     */
34
    protected $filesystem;
35
36
    public function __construct(
37
        UuidGeneratorInterface $uuidGenerator,
38
        CommandBusInterface $commandBus,
39
        FilesystemInterface $filesystem,
40
        $uploadDirectory
41
    ) {
42
        $this->uuidGenerator = $uuidGenerator;
43
        $this->commandBus = $commandBus;
44
        $this->filesystem = $filesystem;
45
        $this->uploadDirectory = $uploadDirectory;
46
    }
47
48
    /**
49
     * @inheritdoc
50
     */
51
    public function upload(UploadedFile $file, String $description, String $copyrightHolder)
52
    {
53
        if (!$file->isValid()) {
54
            throw new \InvalidArgumentException('The file did not upload correctly.');
55
        }
56
57
        $fileType = $file->getMimeType();
58
59
        if (!$fileType) {
60
            throw new \InvalidArgumentException('The type of the uploaded file can not be guessed.');
61
        } else {
62
            $mimeType = MIMEType::fromNative($fileType);
63
        }
64
65
        $fileId = new UUID($this->uuidGenerator->generate());
66
        $fileName = $fileId.'.'.$file->guessExtension();
67
        $destination = $this->getUploadDirectory().'/'.$fileName;
68
        $stream = fopen($file->getRealPath(), 'r+');
69
        $this->filesystem->writeStream($destination, $stream);
70
        fclose($stream);
71
72
        return $this->commandBus->dispatch(
73
            new UploadImage($fileId, $mimeType, $description, $copyrightHolder)
74
        );
75
    }
76
77
    /**
78
     * @inheritdoc
79
     */
80
    public function getUploadDirectory()
81
    {
82
        return $this->uploadDirectory;
83
    }
84
}
85