Passed
Push — master ( be1bc4...bcc02c )
by Daniel
06:06
created

UploadableFileManager   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 165
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 88
dl 0
loc 165
ccs 0
cts 92
cp 0
rs 10
c 1
b 0
f 1
wmc 26

8 Methods

Rating   Name   Duplication   Size   Complexity  
A addDeletedField() 0 3 1
A deleteFiles() 0 9 3
A __construct() 0 10 1
A removeFilepath() 0 12 3
A setUploadedFilesFromFileBag() 0 11 3
A getFileResponse() 0 33 4
A storeFilesMetadata() 0 16 6
A persistFiles() 0 37 5
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\Helper\Uploadable;
15
16
use Doctrine\Common\Collections\ArrayCollection;
17
use Doctrine\Persistence\ManagerRegistry;
18
use Liip\ImagineBundle\Service\FilterService;
19
use Silverback\ApiComponentsBundle\Annotation\UploadableField;
20
use Silverback\ApiComponentsBundle\AnnotationReader\UploadableAnnotationReader;
21
use Silverback\ApiComponentsBundle\Entity\Utility\ImagineFiltersInterface;
22
use Silverback\ApiComponentsBundle\Flysystem\FilesystemProvider;
23
use Silverback\ApiComponentsBundle\Imagine\CacheManager;
24
use Silverback\ApiComponentsBundle\Imagine\FlysystemDataLoader;
25
use Silverback\ApiComponentsBundle\Model\Uploadable\UploadedDataUriFile;
26
use Silverback\ApiComponentsBundle\Utility\ClassMetadataTrait;
27
use Symfony\Component\HttpFoundation\File\File;
28
use Symfony\Component\HttpFoundation\FileBag;
29
use Symfony\Component\HttpFoundation\HeaderUtils;
30
use Symfony\Component\HttpFoundation\Response;
31
use Symfony\Component\HttpFoundation\StreamedResponse;
32
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
33
use Symfony\Component\PropertyAccess\PropertyAccess;
34
35
/**
36
 * @author Daniel West <[email protected]>
37
 */
38
class UploadableFileManager
39
{
40
    use ClassMetadataTrait;
41
42
    private UploadableAnnotationReader $annotationReader;
43
    private FilesystemProvider $filesystemProvider;
44
    private FlysystemDataLoader $flysystemDataLoader;
45
    private FileInfoCacheManager $fileInfoCacheManager;
46
    private ?CacheManager $imagineCacheManager;
47
    private ?FilterService $filterService;
48
    private ArrayCollection $deletedFields;
49
50
    public function __construct(ManagerRegistry $registry, UploadableAnnotationReader $annotationReader, FilesystemProvider $filesystemProvider, FlysystemDataLoader $flysystemDataLoader, FileInfoCacheManager $fileInfoCacheManager, ?CacheManager $imagineCacheManager, ?FilterService $filterService = null)
51
    {
52
        $this->initRegistry($registry);
53
        $this->annotationReader = $annotationReader;
54
        $this->filesystemProvider = $filesystemProvider;
55
        $this->flysystemDataLoader = $flysystemDataLoader;
56
        $this->fileInfoCacheManager = $fileInfoCacheManager;
57
        $this->imagineCacheManager = $imagineCacheManager;
58
        $this->filterService = $filterService;
59
        $this->deletedFields = new ArrayCollection();
60
    }
61
62
    public function addDeletedField($field)
63
    {
64
        $this->deletedFields->add($field);
65
    }
66
67
    public function setUploadedFilesFromFileBag(object $object, FileBag $fileBag): void
68
    {
69
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
70
        $configuredProperties = $this->annotationReader->getConfiguredProperties($object, false);
71
72
        /**
73
         * @var UploadableField[] $configuredProperties
74
         */
75
        foreach ($configuredProperties as $fileProperty => $fieldConfiguration) {
76
            if ($file = $fileBag->get($fileProperty)) {
77
                $propertyAccessor->setValue($object, $fileProperty, $file);
78
            }
79
        }
80
    }
81
82
    public function storeFilesMetadata(object $object): void
83
    {
84
        $configuredProperties = $this->annotationReader->getConfiguredProperties($object, true);
85
        $classMetadata = $this->getClassMetadata($object);
86
87
        foreach ($configuredProperties as $fileProperty => $fieldConfiguration) {
88
            // Let the data loader which should be configured for imagine to know which adapter to use
89
            $this->flysystemDataLoader->setAdapter($fieldConfiguration->adapter);
90
91
            $filename = $classMetadata->getFieldValue($object, $fieldConfiguration->property);
92
            if ($filename && $object instanceof ImagineFiltersInterface && $this->filterService) {
93
                $filters = $object->getImagineFilters($fileProperty, null);
94
                foreach ($filters as $filter) {
95
                    // This will trigger the cached file to be store
96
                    // When cached files are store we save the file info
97
                    $this->filterService->getUrlOfFilteredImage($filename, $filter);
98
                }
99
            }
100
        }
101
    }
102
103
    public function persistFiles(object $object): void
104
    {
105
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
106
        $classMetadata = $this->getClassMetadata($object);
107
108
        $configuredProperties = $this->annotationReader->getConfiguredProperties($object, true);
109
        foreach ($configuredProperties as $fileProperty => $fieldConfiguration) {
110
            // this is null if null is submitted as the value and null if not submitted
111
            /** @var File|UploadedDataUriFile|null $file */
112
            $file = $propertyAccessor->getValue($object, $fileProperty);
113
            if (!$file) {
114
                if ($this->deletedFields->contains($fieldConfiguration->property)) {
115
                    // this will not have been updated yet, original database value - string file path
116
                    $currentFilepath = $classMetadata->getFieldValue($object, $fieldConfiguration->property);
117
                    if ($currentFilepath) {
118
                        $this->removeFilepath($object, $fieldConfiguration);
119
                        // file path set to null
120
                        $classMetadata->setFieldValue($object, $fieldConfiguration->property, null);
121
                    }
122
                }
123
                continue;
124
            }
125
126
            $filesystem = $this->filesystemProvider->getFilesystem($fieldConfiguration->adapter);
0 ignored issues
show
Bug introduced by
It seems like $fieldConfiguration->adapter can also be of type null; however, parameter $name of Silverback\ApiComponents...ovider::getFilesystem() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

126
            $filesystem = $this->filesystemProvider->getFilesystem(/** @scrutinizer ignore-type */ $fieldConfiguration->adapter);
Loading history...
127
128
            $path = $fieldConfiguration->prefix ?? '';
129
            $path .= $file->getFilename();
130
            $stream = fopen($file->getRealPath(), 'r');
131
            $filesystem->writeStream(
132
                $path,
133
                $stream,
134
                [
135
                    'mimetype' => $file->getMimeType(),
136
                ]
137
            );
138
            $classMetadata->setFieldValue($object, $fieldConfiguration->property, $path);
139
            $propertyAccessor->setValue($object, $fileProperty, null);
140
        }
141
    }
142
143
    public function deleteFiles(object $object): void
144
    {
145
        $classMetadata = $this->getClassMetadata($object);
146
147
        $configuredProperties = $this->annotationReader->getConfiguredProperties($object, true);
148
        foreach ($configuredProperties as $fileProperty => $fieldConfiguration) {
149
            $currentFilepath = $classMetadata->getFieldValue($object, $fieldConfiguration->property);
150
            if ($currentFilepath) {
151
                $this->removeFilepath($object, $fieldConfiguration);
152
            }
153
        }
154
    }
155
156
    public function getFileResponse(object $object, string $property, bool $forceDownload = false): Response
157
    {
158
        try {
159
            $reflectionProperty = new \ReflectionProperty($object, $property);
160
        } catch (\ReflectionException $exception) {
161
            throw new NotFoundHttpException($exception->getMessage());
162
        }
163
        if (!$this->annotationReader->isFieldConfigured($reflectionProperty)) {
164
            throw new NotFoundHttpException(sprintf('field configuration not found for %s', $property));
165
        }
166
167
        $propertyConfiguration = $this->annotationReader->getPropertyConfiguration($reflectionProperty);
168
169
        $filesystem = $this->filesystemProvider->getFilesystem($propertyConfiguration->adapter);
0 ignored issues
show
Bug introduced by
It seems like $propertyConfiguration->adapter can also be of type null; however, parameter $name of Silverback\ApiComponents...ovider::getFilesystem() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

169
        $filesystem = $this->filesystemProvider->getFilesystem(/** @scrutinizer ignore-type */ $propertyConfiguration->adapter);
Loading history...
170
171
        $classMetadata = $this->getClassMetadata($object);
172
173
        $filePath = $classMetadata->getFieldValue($object, $propertyConfiguration->property);
174
175
        $response = new StreamedResponse();
176
        $response->setCallback(
177
            static function () use ($filesystem, $filePath) {
178
                $outputStream = fopen('php://output', 'w');
179
                $fileStream = $filesystem->readStream($filePath);
180
                stream_copy_to_stream($fileStream, $outputStream);
181
            }
182
        );
183
        $response->headers->set('Content-Type', $filesystem->mimeType($filePath));
184
185
        $disposition = HeaderUtils::makeDisposition($forceDownload ? HeaderUtils::DISPOSITION_ATTACHMENT : HeaderUtils::DISPOSITION_INLINE, $filePath);
186
        $response->headers->set('Content-Disposition', $disposition);
187
188
        return $response;
189
    }
190
191
    private function removeFilepath(object $object, UploadableField $fieldConfiguration): void
192
    {
193
        $classMetadata = $this->getClassMetadata($object);
194
195
        $filesystem = $this->filesystemProvider->getFilesystem($fieldConfiguration->adapter);
0 ignored issues
show
Bug introduced by
It seems like $fieldConfiguration->adapter can also be of type null; however, parameter $name of Silverback\ApiComponents...ovider::getFilesystem() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

195
        $filesystem = $this->filesystemProvider->getFilesystem(/** @scrutinizer ignore-type */ $fieldConfiguration->adapter);
Loading history...
196
        $currentFilepath = $classMetadata->getFieldValue($object, $fieldConfiguration->property);
197
        $this->fileInfoCacheManager->deleteCaches([$currentFilepath], [null]);
198
        if ($this->imagineCacheManager) {
199
            $this->imagineCacheManager->remove([$currentFilepath], null);
200
        }
201
        if ($filesystem->fileExists($currentFilepath)) {
202
            $filesystem->delete($currentFilepath);
203
        }
204
    }
205
}
206