Passed
Push — master ( c27252...10d571 )
by Kanstantsin
04:12
created

FileManager::getImageUrl()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 7
nc 3
nop 4
dl 0
loc 13
rs 8.8571
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace tkanstantsin\yii2fileupload;
5
6
use tkanstantsin\fileupload\FileManager as BaseFileManager;
7
use tkanstantsin\fileupload\model\IFile;
8
use tkanstantsin\fileupload\model\Type as FileType;
9
use yii\base\Component;
0 ignored issues
show
Bug introduced by
The type yii\base\Component 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...
10
use yii\base\InvalidConfigException;
0 ignored issues
show
Bug introduced by
The type yii\base\InvalidConfigException 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...
11
use yii\helpers\ArrayHelper;
0 ignored issues
show
Bug introduced by
The type yii\helpers\ArrayHelper 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...
12
use yii\helpers\Url;
0 ignored issues
show
Bug introduced by
The type yii\helpers\Url 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...
13
14
/**
15
 * Class FileComponent
16
 *
17
 * @todo: create repository only for yii2-filemanager widget
18
 * @todo: proxy all methods to the real filemanager.
19
 */
20
class FileManager extends Component
21
{
22
    /**
23
     * Will hide file formatting exception if true
24
     * @var bool
25
     */
26
    public $silentMode = true;
27
28
    /**
29
     * Base url for uploading files
30
     * @var string
31
     */
32
    public $uploadBaseUrl;
33
    /**
34
     * Path to folder which would contain cached files.
35
     * /cache-base-path/alias/part-of-hash/file-name
36
     * @var string
37
     */
38
    public $cacheBasePath;
39
40
    /**
41
     * Add updatedAt timestamp if it defined
42
     * @var bool
43
     */
44
    public $assetAppendTimestamp = true;
45
46
    /**
47
     * Url for default image
48
     * @var string|array
49
     */
50
    public $imageNotFoundUrl;
51
    /**
52
     * Url for 404 page for files
53
     * @var string|array
54
     */
55
    public $fileNotFoundUrl;
56
57
    /**
58
     * @var BaseFileManager
59
     */
60
    public $manager;
61
62
    /**
63
     * @inheritdoc
64
     * @throws \ErrorException
65
     * @throws \yii\base\InvalidConfigException
66
     */
67
    public function init(): void
68
    {
69
        if ($this->uploadBaseUrl === null) {
70
            throw new \ErrorException('Base upload url must be defined.');
71
        }
72
        if ($this->cacheBasePath === null) {
73
            throw new \ErrorException('Base path for cache must be defined.');
74
        }
75
        if ($this->imageNotFoundUrl === null || $this->fileNotFoundUrl === null) {
76
            throw new \ErrorException('URLs for not founded image and file must be defined.');
77
        }
78
79
        $this->manager['contentFS'] = \Yii::$app->{$this->manager['contentFS']}->getFileSystem();
0 ignored issues
show
Bug introduced by
The type Yii 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...
80
        $this->manager['cacheFS'] = \Yii::$app->{$this->manager['cacheFS']}->getFileSystem();
81
82
        $class = ArrayHelper::remove($this->manager, 'class', BaseFileManager::class);
83
        $this->manager = new $class($this->manager);
84
        if (!($this->manager instanceof BaseFileManager)) {
85
            throw new InvalidConfigException(\Yii::t('yii2fileupload', 'Invalid file manager config'));
86
        }
87
88
        parent::init();
89
    }
90
91
    /**
92
     * Generates url for upload file with upload widget.
93
     * Url format: $uploadBaseUrl/$alias/$id
94
     * @example /upload/product/555
95
     * @param string $aliasName
96
     * @param int $id of related model
97
     * @return string
98
     * @throws \yii\base\InvalidParamException
99
     */
100
    public function getUploadUrl(string $aliasName, int $id = null): string
101
    {
102
        return implode(DIRECTORY_SEPARATOR, array_filter([$this->uploadBaseUrl, $aliasName, $id]));
103
    }
104
105
    /**
106
     * @param IFile|null $file
107
     * @param string $format
108
     * @param array $formatterConfig
109
     * @return string
110
     * @throws \RuntimeException
111
     * @throws \InvalidArgumentException
112
     * @throws \Exception
113
     * @throws \yii\base\InvalidParamException
114
     */
115
    public function getFileUrl(?IFile $file, string $format, array $formatterConfig = []): string
116
    {
117
        $path = $this->getFilePath($file, $format, $formatterConfig);
118
        if ($path !== null) {
119
            return $this->cacheBasePath . DIRECTORY_SEPARATOR . $path;
120
        }
121
122
        $fileTypeId = $file !== null && $file->getType() !== null
123
            ? $file->getType()
124
            : FileType::FILE;
125
126
        return $this->getNotFoundUrl($fileTypeId);
127
    }
128
129
    /**
130
     * Format file and return image link if failed
131
     * @param IFile|null $file
132
     * @param string $format
133
     * @param array $formatterConfig
134
     * @param string|null $notFoundUrl
135
     * @return string
136
     * @throws \RuntimeException
137
     * @throws \InvalidArgumentException
138
     * @throws \Exception
139
     * @throws \yii\base\InvalidParamException
140
     */
141
    public function getImageUrl(?IFile $file, string $format, array $formatterConfig = [], string $notFoundUrl = null): string
142
    {
143
        $path = $this->getFilePath($file, $format, $formatterConfig);
144
        if ($path !== null) {
145
            $url = $this->cacheBasePath . DIRECTORY_SEPARATOR . $path;
146
            if ($this->assetAppendTimestamp && $file !== null && $file->getUpdatedAt() !== null) {
147
                $url = '?' . $file->getUpdatedAt();
148
            }
149
150
            return $url;
151
        }
152
153
        return $notFoundUrl ?? $this->getNotFoundUrl(FileType::IMAGE);
154
    }
155
156
    /**
157
     * Choose 404 url
158
     * @param int $fileTypeId
159
     * @return string
160
     * @throws \yii\base\InvalidParamException
161
     */
162
    public function getNotFoundUrl(int $fileTypeId): string
163
    {
164
        switch ($fileTypeId) {
165
            case FileType::IMAGE:
166
                return Url::to($this->imageNotFoundUrl);
167
            case FileType::FILE:
168
            default:
169
                return Url::to($this->fileNotFoundUrl);
170
        }
171
    }
172
173
    /**
174
     * Caches file and returns url to it. Return 404 image or link if fails
175
     * without exception.
176
     * @param IFile|null $file
177
     * @param string $format
178
     * @param array $formatterConfig
179
     * @return string|null
180
     * @throws \InvalidArgumentException
181
     * @throws \yii\base\InvalidParamException
182
     * @throws \RuntimeException
183
     * @throws \Exception
184
     */
185
    protected function getFilePath(?IFile $file, string $format, array $formatterConfig = []): ?string
186
    {
187
        if ($file === null || $file->getId() === null /*null if file is not saved yet*/) {
188
            return null;
189
        }
190
191
        try {
192
            return $this->manager->getFilePath($file, $format, $formatterConfig);
193
        } catch (\Exception $e) {
194
            if (!$this->silentMode) {
195
                throw $e;
196
            }
197
        }
198
199
        return null;
200
    }
201
}
202