1 | <?php |
||
16 | class ImageUploaderService implements ImageUploaderInterface |
||
17 | { |
||
18 | /** |
||
19 | * @var UuidGeneratorInterface |
||
20 | */ |
||
21 | protected $uuidGenerator; |
||
22 | |||
23 | /** |
||
24 | * @var CommandBusInterface |
||
25 | */ |
||
26 | protected $commandBus; |
||
27 | |||
28 | /** |
||
29 | * @var string |
||
30 | */ |
||
31 | protected $uploadDirectory; |
||
32 | |||
33 | /** |
||
34 | * @var FilesystemInterface |
||
35 | */ |
||
36 | protected $filesystem; |
||
37 | |||
38 | /** |
||
39 | * @var Natural|null |
||
40 | * The maximum file size in bytes. |
||
41 | * There is no limit when the file size if null. |
||
42 | */ |
||
43 | protected $maxFileSize; |
||
44 | |||
45 | /** |
||
46 | * @param UuidGeneratorInterface $uuidGenerator |
||
47 | * @param CommandBusInterface $commandBus |
||
48 | * @param FilesystemInterface $filesystem |
||
49 | * @param $uploadDirectory |
||
50 | * |
||
51 | * @param Natural|null $maxFileSize |
||
52 | * The maximum file size in bytes. |
||
53 | */ |
||
54 | public function __construct( |
||
67 | |||
68 | /** |
||
69 | * @inheritdoc |
||
70 | */ |
||
71 | public function upload(UploadedFile $file, String $description, String $copyrightHolder) |
||
72 | { |
||
73 | if (!$file->isValid()) { |
||
74 | throw new \InvalidArgumentException('The file did not upload correctly.'); |
||
75 | } |
||
76 | |||
77 | $mimeTypeString = $file->getMimeType(); |
||
78 | |||
79 | if (!$mimeTypeString) { |
||
80 | throw new \InvalidArgumentException('The type of the uploaded file can not be guessed.'); |
||
81 | } |
||
82 | |||
83 | $this->guardFileSizeLimit($file); |
||
84 | |||
85 | $fileTypeParts = explode('/', $mimeTypeString); |
||
86 | $fileType = array_shift($fileTypeParts); |
||
87 | if ($fileType !== 'image') { |
||
88 | throw new \InvalidArgumentException('The uploaded file is not an image.'); |
||
89 | } |
||
90 | |||
91 | $mimeType = MIMEType::fromNative($mimeTypeString); |
||
92 | |||
93 | $fileId = new UUID($this->uuidGenerator->generate()); |
||
94 | $fileName = $fileId . '.' . $file->guessExtension(); |
||
95 | $destination = $this->getUploadDirectory() . '/' . $fileName; |
||
96 | $stream = fopen($file->getRealPath(), 'r+'); |
||
97 | $this->filesystem->writeStream($destination, $stream); |
||
98 | fclose($stream); |
||
99 | |||
100 | return $this->commandBus->dispatch( |
||
101 | new UploadImage( |
||
102 | $fileId, |
||
103 | $mimeType, |
||
104 | $description, |
||
105 | $copyrightHolder, |
||
106 | new String($destination) |
||
107 | ) |
||
108 | ); |
||
109 | } |
||
110 | |||
111 | private function guardFileSizeLimit(UploadedFile $file) |
||
126 | |||
127 | /** |
||
128 | * @inheritdoc |
||
129 | */ |
||
130 | public function getUploadDirectory() |
||
134 | } |
||
135 |