FilesManagement::rmove()   B
last analyzed

Complexity

Conditions 10
Paths 7

Size

Total Lines 30
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 14
nc 7
nop 2
dl 0
loc 30
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace XoopsModules\Countdown\Common;
6
7
/*
8
 You may not change or alter any portion of this comment or credits
9
 of supporting developers from this source code or any supporting source code
10
 which is considered copyrighted (c) material of the original comment or credit authors.
11
12
 This program is distributed in the hope that it will be useful,
13
 but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15
*/
16
17
/**
18
 * Module: Countdown
19
 *
20
 * @category        Module
21
 * @package         countdown
22
 * @author          XOOPS Development Team <https://xoops.org>
23
 * @copyright       {@link https://xoops.org/ XOOPS Project}
24
 * @license         GNU GPL 2 or later (https://www.gnu.org/licenses/gpl-2.0.html)
25
 * @link            https://xoops.org/
26
 * @since           1.0.0
27
 */
28
trait FilesManagement
29
{
30
    /**
31
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
32
     *
33
     * @param string $folder The full path of the directory to check
34
     *
35
     * @return void
36
     * @throws \RuntimeException
37
     */
38
    public static function createFolder($folder)
39
    {
40
        try {
41
            if (!file_exists($folder)) {
42
                if (!mkdir($folder) && !is_dir($folder)) {
43
                    throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
44
                }
45
46
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
47
            }
48
        } catch (\Exception $e) {
49
            echo 'Caught exception: ', $e->getMessage(), '<br>';
50
        }
51
    }
52
53
    /**
54
     * @param $file
55
     * @param $folder
56
     * @return bool
57
     */
58
    public static function copyFile($file, $folder)
59
    {
60
        return copy($file, $folder);
61
    }
62
63
    /**
64
     * @param $src
65
     * @param $dst
66
     */
67
    public static function recurseCopy($src, $dst)
68
    {
69
        $dir = opendir($src);
70
        @mkdir($dst);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for mkdir(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

70
        /** @scrutinizer ignore-unhandled */ @mkdir($dst);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
71
        while (false !== ($file = readdir($dir))) {
72
            if (('.' !== $file) && ('..' !== $file)) {
73
                if (is_dir($src . '/' . $file)) {
74
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
75
                } else {
76
                    copy($src . '/' . $file, $dst . '/' . $file);
77
                }
78
            }
79
        }
80
        closedir($dir);
81
    }
82
83
    /**
84
     * Copy a file, or recursively copy a folder and its contents
85
     * @param string $source      Source path
86
     * @param string $dest        Destination path
87
     * @param int    $permissions New folder creation permissions
88
     * @return      bool     Returns true on success, false on failure
89
     * @version     1.0.1
90
     * @link        http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
91
     * @author      Aidan Lister <[email protected]>
92
     */
93
    public static function xcopy($source, $dest)
94
    {
95
        // Check for symlinks
96
        if (is_link($source)) {
97
            return symlink(readlink($source), $dest);
98
        }
99
100
        // Simple copy for a file
101
        if (is_file($source)) {
102
            return copy($source, $dest);
103
        }
104
105
        // Make destination directory
106
        if (!is_dir($dest)) {
107
            mkdir($dest);
108
        }
109
110
        if (@is_dir($source)) {
111
            // Loop through the folder
112
            $dir = dir($source);
113
            while (false !== $entry = $dir->read()) {
114
                // Skip pointers
115
                if ('.' === $entry || '..' === $entry) {
116
                    continue;
117
                }
118
                // Deep copy directories
119
                self::xcopy("$source/$entry", "$dest/$entry");
120
            }
121
            // Clean up
122
            $dir->close();
123
        }
124
        return true;
125
    }
126
127
    /**
128
     *
129
     * Remove files and (sub)directories
130
     *
131
     * @param string $src source directory to delete
132
     *
133
     * @return bool true on success
134
     * @uses \Xmf\Module\Helper::isUserAdmin()
135
     *
136
     * @uses \Xmf\Module\Helper::getHelper()
137
     */
138
    public static function deleteDirectory($src)
139
    {
140
        // Only continue if user is a 'global' Admin
141
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
142
            return false;
143
        }
144
145
        $success = true;
146
        // remove old files
147
        $dirInfo = new \SplFileInfo($src);
148
        // validate is a directory
149
        if ($dirInfo->isDir()) {
150
            $fileList = array_diff(scandir($src, SCANDIR_SORT_NONE), ['..', '.']);
151
            foreach ($fileList as $k => $v) {
152
                $fileInfo = new \SplFileInfo("{$src}/{$v}");
153
                if ($fileInfo->isDir()) {
154
                    // recursively handle subdirectories
155
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
156
                        break;
157
                    }
158
                } else {
159
                    // delete the file
160
                    if (!($success = unlink($fileInfo->getRealPath()))) {
161
                        break;
162
                    }
163
                }
164
            }
165
            // now delete this (sub)directory if all the files are gone
166
            if ($success) {
167
                $success = rmdir($dirInfo->getRealPath());
168
            }
169
        } else {
170
            // input is not a valid directory
171
            $success = false;
172
        }
173
        return $success;
174
    }
175
176
    /**
177
     *
178
     * Recursively remove directory
179
     *
180
     * @todo currently won't remove directories with hidden files, should it?
181
     *
182
     * @param string $src directory to remove (delete)
183
     *
184
     * @return bool true on success
185
     */
186
    public static function rrmdir($src)
187
    {
188
        // Only continue if user is a 'global' Admin
189
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
190
            return false;
191
        }
192
193
        // If source is not a directory stop processing
194
        if (!is_dir($src)) {
195
            return false;
196
        }
197
198
        $success = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
199
200
        // Open the source directory to read in files
201
        $iterator = new \DirectoryIterator($src);
202
        foreach ($iterator as $fObj) {
203
            if ($fObj->isFile()) {
204
                $filename = $fObj->getPathname();
205
                $fObj     = null; // clear this iterator object to close the file
0 ignored issues
show
Unused Code introduced by
The assignment to $fObj is dead and can be removed.
Loading history...
206
                if (!unlink($filename)) {
207
                    return false; // couldn't delete the file
208
                }
209
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
210
                // Try recursively on directory
211
                self::rrmdir($fObj->getPathname());
212
            }
213
        }
214
        $iterator = null;   // clear iterator Obj to close file/directory
0 ignored issues
show
Unused Code introduced by
The assignment to $iterator is dead and can be removed.
Loading history...
215
        return rmdir($src); // remove the directory & return results
216
    }
217
218
    /**
219
     * Recursively move files from one directory to another
220
     *
221
     * @param string $src  - Source of files being moved
222
     * @param string $dest - Destination of files being moved
223
     *
224
     * @return bool true on success
225
     */
226
    public static function rmove($src, $dest)
227
    {
228
        // Only continue if user is a 'global' Admin
229
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
230
            return false;
231
        }
232
233
        // If source is not a directory stop processing
234
        if (!is_dir($src)) {
235
            return false;
236
        }
237
238
        // If the destination directory does not exist and could not be created stop processing
239
        if (!is_dir($dest) && !mkdir($dest, 0755)) {
240
            return false;
241
        }
242
243
        // Open the source directory to read in files
244
        $iterator = new \DirectoryIterator($src);
245
        foreach ($iterator as $fObj) {
246
            if ($fObj->isFile()) {
247
                rename($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
248
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
249
                // Try recursively on directory
250
                self::rmove($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
251
                //                rmdir($fObj->getPath()); // now delete the directory
252
            }
253
        }
254
        $iterator = null;   // clear iterator Obj to close file/directory
0 ignored issues
show
Unused Code introduced by
The assignment to $iterator is dead and can be removed.
Loading history...
255
        return rmdir($src); // remove the directory & return results
256
    }
257
258
    /**
259
     * Recursively copy directories and files from one directory to another
260
     *
261
     * @param string $src  - Source of files being moved
262
     * @param string $dest - Destination of files being moved
263
     *
264
     * @return bool true on success
265
     * @uses \Xmf\Module\Helper::isUserAdmin()
266
     *
267
     * @uses \Xmf\Module\Helper::getHelper()
268
     */
269
    public static function rcopy($src, $dest)
270
    {
271
        // Only continue if user is a 'global' Admin
272
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
273
            return false;
274
        }
275
276
        // If source is not a directory stop processing
277
        if (!is_dir($src)) {
278
            return false;
279
        }
280
281
        // If the destination directory does not exist and could not be created stop processing
282
        if (!is_dir($dest) && !mkdir($dest, 0755)) {
283
            return false;
284
        }
285
286
        // Open the source directory to read in files
287
        $iterator = new \DirectoryIterator($src);
288
        foreach ($iterator as $fObj) {
289
            if ($fObj->isFile()) {
290
                copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
291
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
292
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
293
            }
294
        }
295
        return true;
296
    }
297
}
298