|
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\Factory; |
|
15
|
|
|
|
|
16
|
|
|
use ApiPlatform\Core\Api\IriConverterInterface; |
|
17
|
|
|
use Silverback\ApiComponentBundle\Dto\File\FileData; |
|
18
|
|
|
use Silverback\ApiComponentBundle\Dto\File\ImageMetadata; |
|
19
|
|
|
use Silverback\ApiComponentBundle\Entity\Utility\FileInterface; |
|
20
|
|
|
use Symfony\Component\Routing\RouterInterface; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @author Daniel West <[email protected]> |
|
24
|
|
|
*/ |
|
25
|
|
|
class FileDataFactory |
|
26
|
|
|
{ |
|
27
|
|
|
private IriConverterInterface $iriConverter; |
|
28
|
|
|
private RouterInterface $router; |
|
29
|
|
|
private ImagineMetadataFactory $imagineMetadataFactory; |
|
30
|
|
|
|
|
31
|
|
|
public function __construct(IriConverterInterface $iriConverter, RouterInterface $router, ImagineMetadataFactory $imagineMetadataFactory) |
|
32
|
|
|
{ |
|
33
|
|
|
$this->iriConverter = $iriConverter; |
|
34
|
|
|
$this->router = $router; |
|
35
|
|
|
$this->imagineMetadataFactory = $imagineMetadataFactory; |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
public function create(FileInterface $resource): ?FileData |
|
39
|
|
|
{ |
|
40
|
|
|
if (!($filePath = $resource->getFilePath()) || !file_exists($filePath)) { |
|
41
|
|
|
return null; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if ($fileData = $resource->getFileData()) { |
|
45
|
|
|
return $fileData; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
$publicPath = $this->getPublicPath($resource); |
|
49
|
|
|
|
|
50
|
|
|
$imageData = self::isImage($filePath) ? new ImageMetadata($filePath, $publicPath) : null; |
|
51
|
|
|
|
|
52
|
|
|
return new FileData( |
|
53
|
|
|
$publicPath, |
|
54
|
|
|
pathinfo($filePath, PATHINFO_EXTENSION), |
|
55
|
|
|
filesize($filePath) ?: null, |
|
56
|
|
|
$imageData, |
|
57
|
|
|
$this->imagineMetadataFactory->create($resource) |
|
58
|
|
|
); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
private static function isImage($filePath): bool |
|
62
|
|
|
{ |
|
63
|
|
|
return exif_imagetype($filePath) || 'image/svg+xml' === mime_content_type($filePath); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
private function getPublicPath(FileInterface $resource): string |
|
67
|
|
|
{ |
|
68
|
|
|
$objectId = $this->iriConverter->getIriFromItem($resource); |
|
69
|
|
|
|
|
70
|
|
|
return $this->router->generate( |
|
71
|
|
|
'api_component_file_upload', |
|
72
|
|
|
['field' => 'filePath', 'id' => $objectId] |
|
73
|
|
|
); |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|