Upload   A
last analyzed

Complexity

Total Complexity 31

Size/Duplication

Total Lines 266
Duplicated Lines 5.26 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 6
Bugs 0 Features 1
Metric Value
c 6
b 0
f 1
dl 14
loc 266
wmc 31
lcom 1
cbo 3
rs 9.8

16 Methods

Rating   Name   Duplication   Size   Complexity  
A setName() 0 13 3
B createUpload() 0 27 3
A asyncUploading() 14 14 3
A syncUploading() 0 18 3
A addFile() 0 9 1
A __construct() 0 14 3
A upload() 0 12 2
A async() 0 5 1
A initParams() 0 8 3
A path() 0 4 1
A fullPath() 0 4 1
A realName() 0 4 1
A name() 0 4 1
A mimeType() 0 4 1
A extension() 0 4 3
A size() 0 4 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
namespace samsonphp\upload;
3
4
/**
5
 * Generic file uploader
6
 * @package samsonphp\upload
7
 * @author Vitaly Iegorov <[email protected]>
8
 * @author Nikita Kotenko <[email protected]>
9
 */
10
class Upload
11
{
12
    /** @var string|boolean real file path */
13
    private $filePath;
14
15
    /** @var string Name of uploaded file */
16
    private $realName;
17
18
    /** @var string Generated file name */
19
    private $fileName;
20
21
    /** @var string File MIME type */
22
    private $mimeType;
23
24
    /** @var string extension */
25
    private $extension;
26
27
    /** @var int File size */
28
    private $size;
29
30
    /** Supported file extensions */
31
    protected $extensions = array();
32
33
    /** @var array Parameters for callable handlers */
34
    protected $relPathParameters = array();
35
36
    /** @var bool Method of uploading */
37
    protected $async = true;
38
39
    /** @var UploadController Pointer to module controller */
40
    public $config;
41
42
    /** Upload server path */
43
    public $uploadDir = 'upload/';
44
45
    /** @var iHandler Handler for processing file option requests */
46
    public $handler;
47
48
    public $files = array();
49
50
    /**
51
     * Init module main fields
52
     * @param array $extensions Allowed file types
53
     * @param null $relPathParameters Parameters for callback functions
54
     */
55
    protected function initParams($extensions = array(), $relPathParameters = null)
56
    {
57
        // Set additional relative path parameters
58
        $this->relPathParameters = !is_array($relPathParameters) ? array($relPathParameters) : $relPathParameters;
59
60
        // Set file extension limitations, form array if isn't an array
61
        $this->extensions = is_array($extensions) ? $extensions : array($extensions);
62
    }
63
64
    /**
65
     * Try to create unique file name using external callback handler
66
     */
67
    protected function setName()
68
    {
69
        // If we have callable handler for generating file name
70
        if (isset($this->config->fileNameHandler) && is_callable($this->config->fileNameHandler)) {
71
            // Add file extension as last parameter
72
            array_push($this->relPathParameters, $this->extension);
73
74
            // Call handler and create fileName
75
            $this->fileName = call_user_func_array($this->config->fileNameHandler, $this->relPathParameters);
76
        } else { // If we have not created filename - generic generate it
77
            $this->fileName = strtolower(md5(time() . $this->realName) . '.' . $this->extension);
78
        }
79
    }
80
81
    /**
82
     * Make file uploading
83
     * @param string $postName
84
     * @return bool Upload status
85
     */
86
    protected function createUpload($postName = '')
87
    {
88
        // Get file extension
89
        $this->extension = pathinfo($this->realName, PATHINFO_EXTENSION);
90
91
        // If we have no extension limitations or they are matched
92
        if (!sizeof($this->extensions) || in_array($this->extension, $this->extensions)) {
93
            // Try to set file name using external handler
94
            $this->setName();
95
96
            /** @var string $file Read uploaded file */
97
            $file = $this->handler->file($postName);
98
99
            // Create file
100
            $this->filePath = $this->handler->write($file, $this->fileName, $this->uploadDir);
101
102
            // Save size and mimeType
103
            $this->size = $this->handler->size($postName);
104
            $this->mimeType = $this->handler->type($postName);
105
106
            // Success
107
            return true;
108
        }
109
110
        // Failed
111
        return false;
112
    }
113
114
    /**
115
     * Asynchronous uploading method
116
     * @return bool
117
     */
118 View Code Duplication
    protected function asyncUploading()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
119
    {
120
        // Try to get upload file with new upload method
121
        $this->realName = $this->handler->name();
122
123
        // If upload data exists
124
        if (isset($this->realName) && $this->realName != '') {
125
            // Try to create upload
126
            return $this->createUpload();
127
        }
128
129
        // Failed
130
        return false;
131
    }
132
133
    /**
134
     * Synchronous uploading method
135
     * @return bool
136
     */
137
    protected function syncUploading()
138
    {
139
        foreach ($_FILES as $postName => $postArray) {
140
            // Try to get upload file with new upload method
141
            $this->realName = $this->handler->name($postName);
142
143
            // Return false if something went wrong
144
            if (!$this->createUpload($postName)) {
145
                return false;
146
            }
147
148
            // Save uploaded file to inner field
149
            $this->addFile($postName);
150
        }
151
152
        // Success
153
        return true;
154
    }
155
156
    /**
157
     * Add uploaded file to files array
158
     * @param $postName string Name of file in users form
159
     */
160
    protected function addFile($postName)
161
    {
162
        $this->files[$postName] = array();
163
        $this->files['size'] = $this->size;
164
        $this->files['extension'] = $this->extension;
165
        $this->files['path'] = $this->path();
166
        $this->files['fullPath'] = $this->fullPath();
167
        $this->files['name'] = $this->name();
168
    }
169
170
    /**
171
     * Constructor
172
     * @param mixed $extensions Collection or single excepted extension
173
     * @param mixed $relPathParameters Data to be passed to external rel. path builder
174
     * @param mixed $config External configuration class
175
     */
176
    public function __construct($extensions = array(), $relPathParameters = null, $config = null, $handler = null)
177
    {
178
        // Init main parameters of current object
179
        $this->initParams($extensions, $relPathParameters);
180
181
        // Get current upload adapter
182
        $this->config = !isset($config) ? m('upload') : $config;
183
184
        // Build relative path for uploading
185
        $this->uploadDir = call_user_func_array($this->config->uploadDirHandler, $this->relPathParameters);
186
187
        // Set file options handler
188
        $this->handler = isset($handler) ? $handler : new AsyncHandler();
189
    }
190
191
    /**
192
     * Perform file uploading logic
193
     * @param string $filePath Uploaded file path
194
     * @param string $uploadName Uploaded file name real name to return on success upload
195
     * @param string $fileName Uploaded file name on server to return on success upload
196
     * @return boolean True if file successfully uploaded
197
     */
198
    public function upload(& $filePath = '', & $uploadName = '', & $fileName = '')
199
    {
200
        $status = $this->async ?
201
            $this->asyncUploading() :
202
            $this->syncUploading();
203
204
        $filePath = $this->fullPath();
205
        $uploadName = $this->name();
206
        $fileName = $this->realName();
207
208
        return $status;
209
    }
210
211
    public function async($async = true)
212
    {
213
        $this->async = $async;
214
        return $this;
215
    }
216
217
    /** @return string Full path to file  */
218
    public function path()
219
    {
220
        return $this->config->pathPrefix.$this->filePath;
221
    }
222
223
    /** @return string Full path to file with file name */
224
    public function fullPath()
225
    {
226
        return $this->config->pathPrefix.$this->filePath.$this->fileName;
227
    }
228
229
    /**
230
     * Returns uploaded file name
231
     * @return string File name
232
     */
233
    public function realName()
234
    {
235
        return $this->realName;
236
    }
237
238
    /**
239
     * Returns stored file name
240
     * @return string File name
241
     */
242
    public function name()
243
    {
244
        return $this->fileName;
245
    }
246
247
    /**
248
     * Returns MIME type of uploaded file
249
     * @return string MIME type
250
     */
251
    public function mimeType()
252
    {
253
        return $this->mimeType;
254
    }
255
256
    /**
257
     * If $extension is set, tries to compare file extension to input extension and return a result
258
     * Otherwise returns file extension
259
     * @param string $extension Supposed file extension
260
     * @return bool|string Result of extension comparison or extension by itself.
261
     */
262
    public function extension($extension = null)
263
    {
264
        return isset($extension) ? ($extension === $this->extension ? true : false) : $this->extension;
265
    }
266
267
    /**
268
     * Returns file size
269
     * @return int File size
270
     */
271
    public function size()
272
    {
273
        return $this->size;
274
    }
275
}
276