GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

Nip_File_System   B
last analyzed

Complexity

Total Complexity 52

Size/Duplication

Total Lines 273
Duplicated Lines 2.93 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 8
loc 273
ccs 0
cts 103
cp 0
rs 7.9487
c 0
b 0
f 0
wmc 52
lcom 1
cbo 1

13 Methods

Rating   Name   Duplication   Size   Complexity  
A instance() 0 9 2
B getUploadError() 0 23 5
D getUploadErrorNo() 0 34 14
A getExtension() 0 4 1
C scanDirectory() 0 24 8
A createDirectory() 0 4 2
A directoryTree() 0 20 4
A emptyDirectory() 0 20 3
B removeDirectory() 0 21 5
A deleteFile() 0 8 2
A formatSize() 0 11 2
A chmod() 0 6 2
A copyDirectory() 8 9 2

How to fix   Duplicated Code    Complexity   

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:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Nip_File_System often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Nip_File_System, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
use Nip\Filesystem\Exception\IOException;
4
5
class Nip_File_System
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
6
{
7
8
    protected $_uploadErrors = array(
9
        0 => "There is no error, the file uploaded with success",
10
        1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini",
11
        2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
12
        3 => "The uploaded file was only partially uploaded",
13
        4 => "No file was uploaded",
14
        6 => "Missing a temporary folder",
15
    );
16
17
    /**
18
     * Singleton
19
     *
20
     * @return self
21
     */
22
    public static function instance()
23
    {
24
        static $instance;
25
        if (!($instance instanceof self)) {
26
            $instance = new self();
27
        }
28
29
        return $instance;
30
    }
31
32
    /**
33
     * Returns error message on upload, if any
34
     *
35
     * @param string $file
36
     * @param array $extensions
37
     * @return mixed
38
     */
39
    public function getUploadError($file, $extensions = array())
40
    {
41
        $messages = array(
42
            'max_post' => 'POST exceeded maximum allowed size.',
43
            'no_upload' => 'No upload found in \$_FILES',
44
            'bad_upload' => 'Upload failed is_uploaded_file test.',
45
            'no_name' => 'File has no name.',
46
            'bad_extension' => 'Invalid file extension',
47
        );
48
49
        $errorCode = $this->getUploadErrorNo($file, $extensions);
50
        if (is_int($errorCode)) {
51
            $translateSlug = 'general.errors.upload.code-'.$errorCode;
52
53
            return app('translator')->hasTranslation($translateSlug) ? __($translateSlug) : $this->_uploadErrors[$errorCode];
54
        } elseif (is_string($errorCode)) {
55
            $translateSlug = 'general.errors.upload.'.$errorCode;
56
57
            return app('translator')->hasTranslation($translateSlug) ? __($translateSlug) : $messages[$errorCode];
58
        }
59
60
        return false;
61
    }
62
63
    /**
64
     * Returns error message on upload, if any
65
     *
66
     * @param string $file
67
     * @param array $extensions
68
     * @return mixed
69
     */
70
    public function getUploadErrorNo($file, $extensions = array())
0 ignored issues
show
Coding Style introduced by
getUploadErrorNo uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
71
    {
72
        $result = false;
73
74
        $maxUpload = ini_get("post_max_size");
75
        $unit = strtoupper(substr($maxUpload, -1));
76
        $multiplier = $unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1));
77
78
        if ($maxUpload && ((int)$_SERVER['CONTENT_LENGTH'] > $multiplier * (int)$maxUpload)) {
79
            $result = "max_post";
80
        }
81
82
        if (!isset($file)) {
83
            $result = "no_upload";
84
        } else {
85
            if (isset($file["error"]) && $file["error"] != 0) {
86
                $result = $file["error"];
87
            } else {
88
                if (!isset($file["tmp_name"]) || !@is_uploaded_file($file["tmp_name"])) {
89
                    $result = "bad_upload";
90
                } else {
91
                    if (!isset($file['name'])) {
92
                        $result = "no_name";
93
                    }
94
                }
95
            }
96
        }
97
98
        if ($extensions && !in_array($this->getExtension($file['name']), $extensions)) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $extensions of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
99
            $result = "bad_extension";
100
        }
101
102
        return $result;
103
    }
104
105
    /**
106
     * Get file extension
107
     *
108
     * @param string $str
109
     * @return string
110
     */
111
    public function getExtension($str)
112
    {
113
        return strtolower(pathinfo($str, PATHINFO_EXTENSION));
114
    }
115
116
    /**
117
     * Gets list of all files within a directory
118
     *
119
     * @param string $dir
120
     * @param boolean $recursive
121
     * @return array
122
     */
123
    public function scanDirectory($dir, $recursive = false, $fullPaths = false)
124
    {
125
        $result = [];
126
127
        if (is_dir($dir)) {
128
            if ($recursive) {
129
                $iterator = new RecursiveDirectoryIterator($dir);
130
                foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file) {
131
                    if ($file->isFile()) {
132
                        $result[] = ($fullPaths ? $file->getPath().DIRECTORY_SEPARATOR : '').$file->getFilename();
133
                    }
134
                }
135
            } else {
136
                $iterator = new DirectoryIterator($dir);
137
                foreach ($iterator as $file) {
138
                    if ($file->isFile()) {
139
                        $result[] = $file->getFilename();
140
                    }
141
                }
142
            }
143
        }
144
145
        return $result;
146
    }
147
148
    /**
149
     * Recursively create a directory and set it's permissions
150
     *
151
     * @param string $dir
152
     * @param int $mode
153
     * @return boolean
154
     */
155
    public function createDirectory($dir, $mode = 0777)
156
    {
157
        return is_dir($dir) ? true : mkdir($dir, $mode, true);
158
    }
159
160
    /**
161
     * Builds array-tree of directory, with files as final nodes
162
     *
163
     * @param string $dir
164
     * @param array $tree
165
     * @return array
166
     */
167
    public function directoryTree($dir, $tree = array())
168
    {
169
        $dir = realpath($dir);
170
        $d = dir($dir);
171
172
        while (false != ($entry = $d->read())) {
173
            $complete = $d->path."/".$entry;
0 ignored issues
show
Bug introduced by
The property path does not seem to exist in Directory.

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
174
            if (!in_array($entry, array(".", "..", ".svn"))) {
175
                if (is_dir($complete)) {
176
                    $tree[$entry] = $this->directoryTree($complete, $tree[$dir][$entry]);
177
                } else {
178
                    $tree[] = $entry;
179
                }
180
            }
181
        }
182
183
        $d->close();
184
185
        return $tree;
186
    }
187
188
    /**
189
     * Recursively empties a directory
190
     * @param string $dir
191
     */
192
    public function emptyDirectory($dir)
193
    {
194
        $dir = rtrim($dir, "/");
195
196
        $files = scandir($dir);
197
198
        array_shift($files);
199
        array_shift($files);
200
201
        foreach ($files as $file) {
202
            $file = $dir.'/'.$file;
203
            if (is_dir($file)) {
204
                $this->removeDirectory($file);
205
            } else {
206
                unlink($file);
207
            }
208
        }
209
210
        return $this;
211
    }
212
213
    /**
214
     * Recursively removes a directory
215
     * @param string $dir
216
     */
217
    public function removeDirectory($dir)
218
    {
219
        $dir = rtrim($dir, "/");
220
221
        if (is_dir($dir)) {
222
            $files = scandir($dir);
223
224
            foreach ($files as $file) {
225
                if (!in_array($file, array(".", ".."))) {
226
                    $file = $dir.DIRECTORY_SEPARATOR.$file;
227
                    if (is_dir($file)) {
228
                        $this->removeDirectory($file);
229
                    } else {
230
                        unlink($file);
231
                    }
232
                }
233
            }
234
235
            rmdir($dir);
236
        }
237
    }
238
239
    public function deleteFile($path)
240
    {
241
        if (file_exists($path)) {
242
            unlink($path);
243
        }
244
245
        return $this;
246
    }
247
248 View Code Duplication
    public function copyDirectory($source, $destination)
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...
249
    {
250
        if (!is_dir($destination)) {
251
            mkdir($destination, 0755, true);
252
        }
253
        $process = new Nip_Process("cp -R -f $source/* $destination");
254
255
        return $process->run();
256
    }
257
258
    public function formatSize($bytes)
259
    {
260
        if (!$bytes) {
261
            return "0 kb";
262
        }
263
264
        $s = array('b', 'kb', 'MB', 'GB', 'TB', 'PB');
265
        $e = floor(log($bytes) / log(1024));
266
267
        return sprintf('%.2f '.$s[$e], ($bytes / pow(1024, floor($e))));
268
    }
269
270
    public function chmod($file, $mode)
271
    {
272
        if (true !== @chmod($file, $mode)) {
273
            throw new IOException(sprintf('Failed to chmod file "%s".', $file), 0, null, $file);
274
        }
275
    }
276
277
}
278