Completed
Push — master ( c2641b...470b70 )
by Kanstantsin
03:53 queued 01:06
created

Uploader::uploadFile()   B

Complexity

Conditions 5
Paths 9

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 13
nc 9
nop 2
dl 0
loc 23
rs 8.5906
c 0
b 0
f 0
1
<?php
2
3
namespace tkanstantsin\fileupload\saver;
4
5
use League\Flysystem\FilesystemInterface;
6
use tkanstantsin\fileupload\config\Alias;
7
use tkanstantsin\fileupload\FileManager;
8
use tkanstantsin\fileupload\model\Type;
9
use tkanstantsin\yii2fileupload\model\File;
10
use yii\helpers\ArrayHelper;
11
use yii\web\UploadedFile;
12
13
/**
14
 * Class FileUpload
15
 *
16
 * @todo: create Yii2 independent Uploader and/or split existed uploader.
17
 */
18
class Uploader extends File
19
{
20
    /**
21
     * @var FileManager
22
     */
23
    public $fileManager;
24
    /**
25
     * @var UploadedFile
26
     */
27
    public $uploadedFile;
28
    /**
29
     * @var Alias
30
     */
31
    private $aliasConfig;
32
    /**
33
     * @var FilesystemInterface
34
     */
35
    private $filesystem;
36
37
    /**
38
     * FileUpload constructor.
39
     * @param FileManager $fileManager
40
     * @param UploadedFile $uploadedFile
41
     * @param array $aliasConfig
42
     * @param FilesystemInterface $filesystem
43
     * @param array $config
44
     */
45
    public function __construct(FileManager $fileManager, UploadedFile $uploadedFile, Alias $aliasConfig, FilesystemInterface $filesystem, array $config = [])
46
    {
47
        $this->fileManager = $fileManager;
48
        $this->uploadedFile = $uploadedFile;
49
        $this->aliasConfig = $aliasConfig;
50
        $this->filesystem = $filesystem;
51
52
        parent::__construct($config);
53
    }
54
55
    public function init(): void
56
    {
57
        parent::init();
58
59
        $this->parent_model = $this->aliasConfig->name;
60
        $this->name = pathinfo($this->uploadedFile->name, PATHINFO_FILENAME);
61
        $this->extension = $this->uploadedFile->extension;
62
        $this->size = (int) $this->uploadedFile->size;
63
        $this->mime_type = $this->uploadedFile->type;
64
        $this->type_id = Type::getByMimeType((string) $this->mime_type);
65
        $this->hash = \is_resource($this->uploadedFile->tempName)
66
            ? hash('md5', stream_get_contents($this->uploadedFile->tempName))
67
            : hash_file('md5', $this->uploadedFile->tempName);
68
    }
69
70
    /**
71
     * @return array
72
     */
73
    public function rules(): array
74
    {
75
        return ArrayHelper::merge(parent::rules(), [
76
            [['uploadedFile', 'parent_model'], 'required'],
77
            [['uploadedFile'], 'file', 'maxSize' => $this->aliasConfig->maxSize],
78
        ]);
79
    }
80
81
    /**
82
     * Saves file
83
     * @return bool
84
     * @throws \League\Flysystem\FileExistsException
85
     * @throws \InvalidArgumentException
86
     * @throws \ErrorException
87
     */
88
    public function upload(): bool
89
    {
90
        $saved = $this->save();
91
92
        // ignore saving error
93
        $this->uploadFile($this->aliasConfig->getFileDirectory($this), $this->aliasConfig->getFileName($this));
94
95
        return $saved;
96
    }
97
98
    /**
99
     * Copy file into FileSaver::$filesystem
100
     * @param string $dirPath
101
     * @param string $fileName
102
     * @return bool
103
     * @throws \League\Flysystem\FileExistsException
104
     * @throws \InvalidArgumentException
105
     */
106
    public function uploadFile(string $dirPath, string $fileName): bool
107
    {
108
        try {
109
            if (!$this->filesystem->createDir($dirPath)) {
110
                return false;
111
            }
112
113
            $targetFilePath = $dirPath . DIRECTORY_SEPARATOR . $fileName;
114
115
            if ($this->filesystem->has($targetFilePath)) {
116
                $this->addError('', "File by path `{$targetFilePath}` already exists.");
117
118
                return false;
119
            }
120
121
            $contentResource = $this->getFileContent();
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $contentResource is correct as $this->getFileContent() targeting tkanstantsin\fileupload\...oader::getFileContent() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
122
            if ($contentResource === null) {
123
                return false;
124
            }
125
126
            return $this->filesystem->writeStream($targetFilePath, $contentResource);
127
        } catch (\Exception $e) {
128
            return false;
129
        }
130
    }
131
132
    /**
133
     * @return resource|null
134
     */
135
    private function getFileContent()
136
    {
137
        $resource = \is_resource($this->uploadedFile->tempName)
138
            ? $this->uploadedFile->tempName
139
            : fopen($this->uploadedFile->tempName, 'rb');
140
141
        return $resource ?: null;
142
    }
143
}
144
145