Passed
Pull Request — master (#58)
by Daniel
06:14
created

UploadableHelper::getMediaObjects()   B

Complexity

Conditions 7
Paths 14

Size

Total Lines 31
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
eloc 18
nc 14
nop 1
dl 0
loc 31
ccs 0
cts 18
cp 0
crap 56
rs 8.8333
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A UploadableHelper::removeFilepath() 0 12 3
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\Uploadable;
15
16
use _HumbugBox3ad74b9da04b\Nette\InvalidArgumentException;
0 ignored issues
show
Bug introduced by
The type _HumbugBox3ad74b9da04b\N...nvalidArgumentException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
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\FileBag;
28
use Symfony\Component\PropertyAccess\PropertyAccess;
29
30
/**
31
 * @author Daniel West <[email protected]>
32
 */
33
class UploadableHelper
34
{
35
    use ClassMetadataTrait;
36
37
    private UploadableAnnotationReader $annotationReader;
38
    private FilesystemProvider $filesystemProvider;
39
    private FlysystemDataLoader $flysystemDataLoader;
40
    private FileInfoCacheHelper $fileInfoCacheHelper;
41
    private ?CacheManager $imagineCacheManager;
42
    private ?FilterService $filterService;
43
44
    public function __construct(
45
        ManagerRegistry $registry,
46
        UploadableAnnotationReader $annotationReader,
47
        FilesystemProvider $filesystemProvider,
48
        FlysystemDataLoader $flysystemDataLoader,
49
        FileInfoCacheHelper $fileInfoCacheHelper,
50
        ?CacheManager $imagineCacheManager,
51
        ?FilterService $filterService = null
52
    ) {
53
        $this->initRegistry($registry);
54
        $this->annotationReader = $annotationReader;
55
        $this->filesystemProvider = $filesystemProvider;
56
        $this->flysystemDataLoader = $flysystemDataLoader;
57
        $this->fileInfoCacheHelper = $fileInfoCacheHelper;
58
        $this->imagineCacheManager = $imagineCacheManager;
59
        $this->filterService = $filterService;
60
    }
61
62
    public function setUploadedFilesFromFileBag(object $object, FileBag $fileBag): void
63
    {
64
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
65
        $configuredProperties = $this->annotationReader->getConfiguredProperties($object, false);
66
67
        /**
68
         * @var UploadableField[] $configuredProperties
69
         */
70
        foreach ($configuredProperties as $fileProperty => $fieldConfiguration) {
71
            if ($file = $fileBag->get($fileProperty, null)) {
72
                $propertyAccessor->setValue($object, $fileProperty, $file);
73
            }
74
        }
75
    }
76
77
    public function storeFilesMetadata(object $object): void
78
    {
79
        $configuredProperties = $this->annotationReader->getConfiguredProperties($object, true);
80
        $classMetadata = $this->getClassMetadata($object);
81
82
        foreach ($configuredProperties as $fileProperty => $fieldConfiguration) {
83
            // Let the data loader which should be configured for imagine to know which adapter to use
84
            $this->flysystemDataLoader->setAdapter($fieldConfiguration->adapter);
85
86
            $filename = $classMetadata->getFieldValue($object, $fieldConfiguration->property);
87
88
            if ($object instanceof ImagineFiltersInterface && $this->filterService) {
89
                $filters = $object->getImagineFilters($fileProperty, null);
90
                foreach ($filters as $filter) {
91
                    // This will trigger the cached file to be store
92
                    // When cached files are store we save the file info
93
                    $this->filterService->getUrlOfFilteredImage($filename, $filter);
94
                }
95
            }
96
        }
97
    }
98
99
    public function persistFiles(object $object): void
100
    {
101
        $propertyAccessor = PropertyAccess::createPropertyAccessor();
102
        $classMetadata = $this->getClassMetadata($object);
103
104
        $configuredProperties = $this->annotationReader->getConfiguredProperties($object, true);
105
        /**
106
         * @var UploadableField[] $configuredProperties
107
         */
108
        foreach ($configuredProperties as $fileProperty => $fieldConfiguration) {
109
            $currentFilepath = $classMetadata->getFieldValue($object, $fieldConfiguration->property);
110
            if ($currentFilepath) {
111
                $this->removeFilepath($object, $fieldConfiguration);
112
            }
113
            /** @var UploadedDataUriFile|null $file */
114
            $file = $propertyAccessor->getValue($object, $fileProperty);
115
            if (!$file) {
116
                $classMetadata->setFieldValue($object, $fieldConfiguration->property, null);
117
                continue;
118
            }
119
120
            $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

120
            $filesystem = $this->filesystemProvider->getFilesystem(/** @scrutinizer ignore-type */ $fieldConfiguration->adapter);
Loading history...
121
122
            $path = $fieldConfiguration->prefix ?? '';
123
            $path .= $file->getFilename();
124
            $stream = fopen($file->getRealPath(), 'r');
125
            $filesystem->writeStream($path, $stream, [
126
                'mimetype' => $file->getMimeType(),
127
            ]);
128
            $classMetadata->setFieldValue($object, $fieldConfiguration->property, $path);
129
            $propertyAccessor->setValue($object, $fileProperty, null);
130
        }
131
    }
132
133
    public function deleteFiles(object $object): void
134
    {
135
        $classMetadata = $this->getClassMetadata($object);
136
137
        $configuredProperties = $this->annotationReader->getConfiguredProperties($object, true);
138
        foreach ($configuredProperties as $fileProperty => $fieldConfiguration) {
139
            $currentFilepath = $classMetadata->getFieldValue($object, $fieldConfiguration->property);
140
            if ($currentFilepath) {
141
                $this->removeFilepath($object, $fieldConfiguration);
142
            }
143
        }
144
    }
145
146
    public function getFile(object $object, string $property)
147
    {
148
        $reflectionProperty = new \ReflectionProperty($object, $property);
149
        if (!$this->annotationReader->isFieldConfigured($reflectionProperty)) {
150
            throw new InvalidArgumentException(sprintf('field configuration not found for %s', $property));
151
        }
152
153
        $propertyConfiguration = $this->annotationReader->getPropertyConfiguration($reflectionProperty);
154
155
        $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

155
        $filesystem = $this->filesystemProvider->getFilesystem(/** @scrutinizer ignore-type */ $propertyConfiguration->adapter);
Loading history...
156
157
        $classMetadata = $this->getClassMetadata($object);
158
159
        return $filesystem->readStream($classMetadata->getFieldValue($object, $propertyConfiguration->property));
160
    }
161
162
    private function removeFilepath(object $object, UploadableField $fieldConfiguration): void
163
    {
164
        $classMetadata = $this->getClassMetadata($object);
165
166
        $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

166
        $filesystem = $this->filesystemProvider->getFilesystem(/** @scrutinizer ignore-type */ $fieldConfiguration->adapter);
Loading history...
167
        $currentFilepath = $classMetadata->getFieldValue($object, $fieldConfiguration->property);
168
        $this->fileInfoCacheHelper->deleteCaches([$currentFilepath], [null]);
169
        if ($this->imagineCacheManager) {
170
            $this->imagineCacheManager->remove([$currentFilepath], null);
171
        }
172
        if ($filesystem->fileExists($currentFilepath)) {
173
            $filesystem->delete($currentFilepath);
174
        }
175
    }
176
}
177