Passed
Pull Request — master (#150)
by Arnaud
07:48
created

AssetsHelper   A

Complexity

Total Complexity 15

Size/Duplication

Total Lines 164
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 53
c 1
b 0
f 0
dl 0
loc 164
rs 10
wmc 15

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getMediaDirectory() 0 7 2
A uploadAsset() 0 17 2
A getWebDirectory() 0 11 2
B getMediaPath() 0 36 6
A __construct() 0 18 2
A createFromFile() 0 3 1
1
<?php
2
3
namespace JK\CmsBundle\Assets;
4
5
use JK\CmsBundle\Exception\Exception;
0 ignored issues
show
Bug introduced by
The type JK\CmsBundle\Exception\Exception 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...
6
use JK\MediaBundle\Entity\MediaInterface;
0 ignored issues
show
Bug introduced by
The type JK\MediaBundle\Entity\MediaInterface 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...
7
use Liip\ImagineBundle\Imagine\Cache\CacheManager;
0 ignored issues
show
Bug introduced by
The type Liip\ImagineBundle\Imagine\Cache\CacheManager 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...
8
use Symfony\Component\Filesystem\Filesystem;
9
use Symfony\Component\HttpFoundation\File\UploadedFile;
10
use Symfony\Component\Routing\RouterInterface;
11
12
class AssetsHelper
13
{
14
    /**
15
     * @var array
16
     */
17
    private $assetsMapping;
18
19
    /**
20
     * @var RouterInterface
21
     */
22
    private $router;
23
24
    /**
25
     * @var string
26
     */
27
    private $environment;
28
29
    /**
30
     * @var CacheManager
31
     */
32
    private $assetsManager;
33
34
    /**
35
     * @var string
36
     */
37
    private $rootDir;
38
39
    /**
40
     * AssetsHelper constructor.
41
     *
42
     * @param string $rootDirectory
43
     */
44
    public function __construct(
45
        string $kernelEnvironment,
46
        array $assetsMapping,
47
        RouterInterface $router,
48
        CacheManager $assetsManager,
49
        $rootDirectory
50
    ) {
51
        $this->assetsMapping = $assetsMapping;
52
53
        if ([] === $this->assetsMapping) {
54
            $this->assetsMapping = [
55
                'gallery' => '/uploads/gallery',
56
            ];
57
        }
58
        $this->router = $router;
59
        $this->environment = $kernelEnvironment;
60
        $this->assetsManager = $assetsManager;
61
        $this->rootDir = $rootDirectory;
62
    }
63
64
    /**
65
     * Return the web path to a Media. If $cache is true, it returns the web path to the cached version.
66
     *
67
     * @param bool        $absolute
68
     * @param bool        $cache
69
     * @param string|null $mediaFilter
70
     *
71
     * @return string
72
     *
73
     * @throws Exception
74
     */
75
    public function getMediaPath(MediaInterface $media, $absolute = true, $cache = true, $mediaFilter = null)
76
    {
77
        if (!array_key_exists($media->getType(), $this->assetsMapping)) {
78
            throw new Exception('No assets mapping found for media type '.$media->getType());
79
        }
80
81
        if (null === $mediaFilter) {
82
            $mediaFilter = $media->getType();
83
        }
84
85
        $relativePath = sprintf(
86
            '%s/%s',
87
            $this->assetsMapping[$media->getType()],
88
            $media->getFileName()
89
        );
90
        $path = $relativePath;
91
92
        if (true === $absolute) {
93
            $context = $this
94
                ->router
95
                ->getContext();
96
            $path = $context->getScheme().'://'.$context->getHost().'/'.$path;
97
98
            // bug fix for development environment
99
            if ('prod' !== $this->environment) {
100
                $path = str_replace('app_'.$this->environment.'.php', '', $path);
101
            }
102
        }
103
104
        if ($cache) {
105
            $path = $this
106
                ->assetsManager
107
                ->getBrowserPath($relativePath, $mediaFilter);
108
        }
109
110
        return $path;
111
    }
112
113
    /**
114
     * Return the web directory according to the given mapping name. The mapping name should exists.
115
     *
116
     * @param string $mappingName
117
     *
118
     * @return string
119
     *
120
     * @throws Exception
121
     */
122
    public function getMediaDirectory($mappingName)
123
    {
124
        if (!array_key_exists($mappingName, $this->assetsMapping)) {
125
            throw new Exception('No assets mapping found for media type '.$mappingName);
126
        }
127
128
        return $this->assetsMapping[$mappingName];
129
    }
130
131
    /**
132
     * Upload a file into a media directory according to the mapping. Update the media entity with the new file data.
133
     */
134
    public function uploadAsset(MediaInterface $media, UploadedFile $file)
135
    {
136
        $fileSystem = new Filesystem();
137
        $filename = urlencode($file->getClientOriginalName());
138
        $directory = $this->getMediaDirectory($media->getType());
139
140
        // if a asset with the same name exists in the same directory, we generate a random file name
141
        if ($fileSystem->exists($this->getWebDirectory().'/'.$directory.'/'.$filename)) {
142
            $filename = uniqid('assets-').'.'.$file->getClientOriginalExtension();
143
        }
144
        // define the media attributes values
145
        $media->setFileName($filename);
146
        $media->setFileType($file->getClientOriginalExtension());
147
        $media->setSize($file->getSize());
148
149
        // move the uploaded files to the given directory
150
        $file->move($this->getWebDirectory().'/'.$directory, $media->getFileName());
151
    }
152
153
    public function createFromFile(UploadedFile $file)
0 ignored issues
show
Unused Code introduced by
The parameter $file is not used and could be removed. ( Ignorable by Annotation )

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

153
    public function createFromFile(/** @scrutinizer ignore-unused */ UploadedFile $file)

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
154
    {
155
        throw new Exception('Not implemented');
156
    }
157
158
    /**
159
     * Return the web directory. It should exists or an Exception is thrown.
160
     *
161
     * @return string
162
     *
163
     * @throws Exception
164
     */
165
    protected function getWebDirectory()
166
    {
167
        $fileSystem = new Filesystem();
168
        $webDirectory = realpath($this->rootDir.'/../web');
169
170
        // web directory must be found
171
        if (!$fileSystem->exists($webDirectory)) {
172
            throw new Exception('Web directory not found');
173
        }
174
175
        return $webDirectory;
176
    }
177
}
178