LocalUpload::setParamsForDelete()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 3
c 1
b 0
f 0
nc 2
nop 0
dl 0
loc 7
rs 10
1
<?php
2
3
namespace Itstructure\MFUploader\models\upload;
4
5
use Yii;
6
use yii\imagine\Image;
7
use yii\base\InvalidConfigException;
8
use yii\helpers\{BaseFileHelper, Inflector};
9
use yii\web\UploadedFile;
10
use Itstructure\MFUploader\Module;
11
use Itstructure\MFUploader\models\Mediafile;
12
use Itstructure\MFUploader\components\ThumbConfig;
13
use Itstructure\MFUploader\interfaces\{ThumbConfigInterface, UploadModelInterface};
14
15
/**
16
 * Class LocalUpload
17
 *
18
 * @property string $uploadRoot Root directory for uploaded files.
19
 * @property string $directoryForDelete Directory for delete with all content.
20
 * @property Mediafile $mediafileModel Mediafile model to save files data.
21
 * @property UploadedFile $file File object.
22
 *
23
 * @package Itstructure\MFUploader\models
24
 *
25
 * @author Andrey Girnik <[email protected]>
26
 */
27
class LocalUpload extends BaseUpload implements UploadModelInterface
28
{
29
    const DIR_LENGTH_FIRST = 2;
30
    const DIR_LENGTH_SECOND = 4;
31
32
    /**
33
     * Root directory for uploaded files.
34
     *
35
     * @var string
36
     */
37
    public $uploadRoot;
38
39
    /**
40
     * Directory for delete with all content.
41
     *
42
     * @var string
43
     */
44
    private $directoryForDelete = [];
45
46
    /**
47
     * Initialize.
48
     */
49
    public function init()
50
    {
51
        if (null === $this->uploadRoot || !is_string($this->uploadRoot)) {
52
            throw new InvalidConfigException('The uploadRoot is not defined correctly.');
53
        }
54
55
        $this->uploadRoot = rtrim(rtrim($this->uploadRoot, '/'), '\\');
56
    }
57
58
    /**
59
     * Get storage type - local.
60
     *
61
     * @return string
62
     */
63
    protected function getStorageType(): string
64
    {
65
        return Module::STORAGE_TYPE_LOCAL;
66
    }
67
68
    /**
69
     * Set some params for send.
70
     * It is needed to set the next parameters:
71
     * $this->uploadDir
72
     * $this->uploadPath
73
     * $this->outFileName
74
     * $this->databaseUrl
75
     *
76
     * @throws InvalidConfigException
77
     *
78
     * @return void
79
     */
80
    protected function setParamsForSend(): void
81
    {
82
        $uploadDir = rtrim(rtrim($this->getUploadDirConfig($this->file->type), '/'), '\\');
83
84
        if (!empty($this->subDir)) {
85
            $uploadDir = $uploadDir . DIRECTORY_SEPARATOR . trim(trim($this->subDir, '/'), '\\');
86
        }
87
88
        $this->uploadDir = $uploadDir .
89
            DIRECTORY_SEPARATOR . substr(md5(time()), 0, self::DIR_LENGTH_FIRST) .
90
            DIRECTORY_SEPARATOR . substr(md5(microtime().$this->file->tempName), 0, self::DIR_LENGTH_SECOND);
91
92
        $this->uploadPath = $this->uploadRoot . DIRECTORY_SEPARATOR . ltrim(ltrim($this->uploadDir, '/'), '\\');
93
94
        $this->outFileName = $this->renameFiles ?
95
            md5(md5(microtime()).$this->file->tempName).'.'.$this->file->extension :
96
            Inflector::slug($this->file->baseName).'.'. $this->file->extension;
97
98
        $this->databaseUrl = $this->uploadDir . DIRECTORY_SEPARATOR . $this->outFileName;
99
    }
100
101
    /**
102
     * Set some params for delete.
103
     * It is needed to set the next parameters:
104
     * $this->directoryForDelete
105
     *
106
     * @return void
107
     */
108
    protected function setParamsForDelete(): void
109
    {
110
        $originalFile = pathinfo($this->uploadRoot . DIRECTORY_SEPARATOR . ltrim(ltrim($this->mediafileModel->url, '\\'), '/'));
111
112
        $dirnameParent = substr($originalFile['dirname'], 0, -(self::DIR_LENGTH_SECOND + 1));
113
114
        $this->directoryForDelete = count(BaseFileHelper::findDirectories($dirnameParent)) == 1 ? $dirnameParent : $originalFile['dirname'];
0 ignored issues
show
Bug introduced by
The method findDirectories() does not exist on yii\helpers\BaseFileHelper. ( Ignorable by Annotation )

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

114
        $this->directoryForDelete = count(BaseFileHelper::/** @scrutinizer ignore-call */ findDirectories($dirnameParent)) == 1 ? $dirnameParent : $originalFile['dirname'];

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
115
    }
116
117
    /**
118
     * Save file in local directory.
119
     *
120
     * @return bool
121
     */
122
    protected function sendFile(): bool
123
    {
124
        BaseFileHelper::createDirectory($this->uploadPath, 0777);
125
126
        $savePath = $this->uploadPath . DIRECTORY_SEPARATOR . $this->outFileName;
127
128
        $this->file->saveAs($savePath);
129
130
        return file_exists($savePath);
131
    }
132
133
    /**
134
     * Delete local directory with original file and thumbs.
135
     *
136
     * @return void
137
     */
138
    protected function deleteFiles(): void
139
    {
140
        BaseFileHelper::removeDirectory($this->directoryForDelete);
141
    }
142
143
    /**
144
     * Create thumb.
145
     *
146
     * @param ThumbConfigInterface|ThumbConfig $thumbConfig
147
     *
148
     * @return string
149
     */
150
    protected function createThumb(ThumbConfigInterface $thumbConfig)
151
    {
152
        $originalFile = pathinfo($this->mediafileModel->url);
153
154
        $thumbUrl = $originalFile['dirname'] .
155
            DIRECTORY_SEPARATOR .
156
            $this->getThumbFilename($originalFile['filename'],
157
                $originalFile['extension'],
158
                $thumbConfig->getAlias(),
159
                $thumbConfig->getWidth(),
160
                $thumbConfig->getHeight()
161
            );
162
163
        Image::thumbnail($this->uploadRoot . DIRECTORY_SEPARATOR . ltrim(ltrim($this->mediafileModel->url, '\\'), '/'),
164
            $thumbConfig->getWidth(),
165
            $thumbConfig->getHeight(),
166
            $thumbConfig->getMode()
167
        )->save($this->uploadRoot . DIRECTORY_SEPARATOR . ltrim(ltrim($thumbUrl, '\\'), '/'));
168
169
        return $thumbUrl;
170
    }
171
172
    /**
173
     * Actions after main save.
174
     *
175
     * @return mixed
176
     */
177
    protected function afterSave()
178
    {
179
        if (null !== $this->owner && null !== $this->ownerId && null != $this->ownerAttribute) {
180
            $this->mediafileModel->addOwner($this->ownerId, $this->owner, $this->ownerAttribute);
181
        }
182
    }
183
}
184