Completed
Push — 2.1 ( a01579...003d83 )
by Alexander
40:23 queued 18:44
created

UploadedFile::getInstanceByName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
ccs 0
cts 3
cp 0
cc 2
eloc 3
nc 2
nop 1
crap 6
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use yii\base\BaseObject;
11
use yii\helpers\Html;
12
13
/**
14
 * UploadedFile represents the information for an uploaded file.
15
 *
16
 * You can call [[getInstance()]] to retrieve the instance of an uploaded file,
17
 * and then use [[saveAs()]] to save it on the server.
18
 * You may also query other information about the file, including [[name]],
19
 * [[tempName]], [[type]], [[size]] and [[error]].
20
 *
21
 * For more details and usage information on UploadedFile, see the [guide article on handling uploads](guide:input-file-upload).
22
 *
23
 * @property string $baseName Original file base name. This property is read-only.
24
 * @property string $extension File extension. This property is read-only.
25
 * @property bool $hasError Whether there is an error with the uploaded file. Check [[error]] for detailed
26
 * error code information. This property is read-only.
27
 *
28
 * @author Qiang Xue <[email protected]>
29
 * @since 2.0
30
 */
31
class UploadedFile extends BaseObject
32
{
33
    /**
34
     * @var string the original name of the file being uploaded
35
     */
36
    public $name;
37
    /**
38
     * @var string the path of the uploaded file on the server.
39
     * Note, this is a temporary file which will be automatically deleted by PHP
40
     * after the current request is processed.
41
     */
42
    public $tempName;
43
    /**
44
     * @var string the MIME-type of the uploaded file (such as "image/gif").
45
     * Since this MIME type is not checked on the server-side, do not take this value for granted.
46
     * Instead, use [[\yii\helpers\FileHelper::getMimeType()]] to determine the exact MIME type.
47
     */
48
    public $type;
49
    /**
50
     * @var int the actual size of the uploaded file in bytes
51
     */
52
    public $size;
53
    /**
54
     * @var int an error code describing the status of this file uploading.
55
     * @see http://www.php.net/manual/en/features.file-upload.errors.php
56
     */
57
    public $error;
58
59
    private static $_files;
60
61
62
    /**
63
     * String output.
64
     * This is PHP magic method that returns string representation of an object.
65
     * The implementation here returns the uploaded file's name.
66
     * @return string the string representation of the object
67
     */
68
    public function __toString()
69
    {
70
        return $this->name;
71
    }
72
73
    /**
74
     * Returns an uploaded file for the given model attribute.
75
     * The file should be uploaded using [[\yii\widgets\ActiveField::fileInput()]].
76
     * @param \yii\base\Model $model the data model
77
     * @param string $attribute the attribute name. The attribute name may contain array indexes.
78
     * For example, '[1]file' for tabular file uploading; and 'file[1]' for an element in a file array.
79
     * @return UploadedFile the instance of the uploaded file.
80
     * Null is returned if no file is uploaded for the specified model attribute.
81
     * @see getInstanceByName()
82
     */
83
    public static function getInstance($model, $attribute)
84
    {
85
        $name = Html::getInputName($model, $attribute);
86
        return static::getInstanceByName($name);
87
    }
88
89
    /**
90
     * Returns all uploaded files for the given model attribute.
91
     * @param \yii\base\Model $model the data model
92
     * @param string $attribute the attribute name. The attribute name may contain array indexes
93
     * for tabular file uploading, e.g. '[1]file'.
94
     * @return UploadedFile[] array of UploadedFile objects.
95
     * Empty array is returned if no available file was found for the given attribute.
96
     */
97
    public static function getInstances($model, $attribute)
98
    {
99
        $name = Html::getInputName($model, $attribute);
100
        return static::getInstancesByName($name);
101
    }
102
103
    /**
104
     * Returns an uploaded file according to the given file input name.
105
     * The name can be a plain string or a string like an array element (e.g. 'Post[imageFile]', or 'Post[0][imageFile]').
106
     * @param string $name the name of the file input field.
107
     * @return null|UploadedFile the instance of the uploaded file.
108
     * Null is returned if no file is uploaded for the specified name.
109
     */
110
    public static function getInstanceByName($name)
111
    {
112
        $files = self::loadFiles();
113
        return isset($files[$name]) ? new static($files[$name]) : null;
114
    }
115
116
    /**
117
     * Returns an array of uploaded files corresponding to the specified file input name.
118
     * This is mainly used when multiple files were uploaded and saved as 'files[0]', 'files[1]',
119
     * 'files[n]'..., and you can retrieve them all by passing 'files' as the name.
120
     * @param string $name the name of the array of files
121
     * @return UploadedFile[] the array of UploadedFile objects. Empty array is returned
122
     * if no adequate upload was found. Please note that this array will contain
123
     * all files from all sub-arrays regardless how deeply nested they are.
124
     */
125
    public static function getInstancesByName($name)
126
    {
127
        $files = self::loadFiles();
128
        if (isset($files[$name])) {
129
            return [new static($files[$name])];
130
        }
131
        $results = [];
132
        foreach ($files as $key => $file) {
133
            if (strpos($key, "{$name}[") === 0) {
134
                $results[] = new static($file);
135
            }
136
        }
137
        return $results;
138
    }
139
140
    /**
141
     * Cleans up the loaded UploadedFile instances.
142
     * This method is mainly used by test scripts to set up a fixture.
143
     */
144
    public static function reset()
145
    {
146
        self::$_files = null;
147
    }
148
149
    /**
150
     * Saves the uploaded file.
151
     * Note that this method uses php's move_uploaded_file() method. If the target file `$file`
152
     * already exists, it will be overwritten.
153
     * @param string $file the file path used to save the uploaded file
154
     * @param bool $deleteTempFile whether to delete the temporary file after saving.
155
     * If true, you will not be able to save the uploaded file again in the current request.
156
     * @return bool true whether the file is saved successfully
157
     * @see error
158
     */
159
    public function saveAs($file, $deleteTempFile = true)
160
    {
161
        if ($this->error == UPLOAD_ERR_OK) {
162
            if ($deleteTempFile) {
163
                return move_uploaded_file($this->tempName, $file);
164
            } elseif (is_uploaded_file($this->tempName)) {
165
                return copy($this->tempName, $file);
166
            }
167
        }
168
        return false;
169
    }
170
171
    /**
172
     * @return string original file base name
173
     */
174 1
    public function getBaseName()
175
    {
176
        // https://github.com/yiisoft/yii2/issues/11012
177 1
        $pathInfo = pathinfo('_' . $this->name, PATHINFO_FILENAME);
178 1
        return mb_substr($pathInfo, 1, mb_strlen($pathInfo, '8bit'), '8bit');
179
    }
180
181
    /**
182
     * @return string file extension
183
     */
184 2
    public function getExtension()
185
    {
186 2
        return strtolower(pathinfo($this->name, PATHINFO_EXTENSION));
187
    }
188
189
    /**
190
     * @return bool whether there is an error with the uploaded file.
191
     * Check [[error]] for detailed error code information.
192
     */
193
    public function getHasError()
194
    {
195
        return $this->error != UPLOAD_ERR_OK;
196
    }
197
198
    /**
199
     * Creates UploadedFile instances from $_FILE.
200
     * @return array the UploadedFile instances
201
     */
202
    private static function loadFiles()
203
    {
204
        if (self::$_files === null) {
205
            self::$_files = [];
206
            if (isset($_FILES) && is_array($_FILES)) {
207
                foreach ($_FILES as $class => $info) {
208
                    self::loadFilesRecursive($class, $info['name'], $info['tmp_name'], $info['type'], $info['size'], $info['error']);
209
                }
210
            }
211
        }
212
        return self::$_files;
213
    }
214
215
    /**
216
     * Creates UploadedFile instances from $_FILE recursively.
217
     * @param string $key key for identifying uploaded file: class name and sub-array indexes
218
     * @param mixed $names file names provided by PHP
219
     * @param mixed $tempNames temporary file names provided by PHP
220
     * @param mixed $types file types provided by PHP
221
     * @param mixed $sizes file sizes provided by PHP
222
     * @param mixed $errors uploading issues provided by PHP
223
     */
224
    private static function loadFilesRecursive($key, $names, $tempNames, $types, $sizes, $errors)
225
    {
226
        if (is_array($names)) {
227
            foreach ($names as $i => $name) {
228
                self::loadFilesRecursive($key . '[' . $i . ']', $name, $tempNames[$i], $types[$i], $sizes[$i], $errors[$i]);
229
            }
230
        } elseif ((int) $errors !== UPLOAD_ERR_NO_FILE) {
231
            self::$_files[$key] = [
232
                'name' => $names,
233
                'tempName' => $tempNames,
234
                'type' => $types,
235
                'size' => $sizes,
236
                'error' => $errors,
237
            ];
238
        }
239
    }
240
}
241