Passed
Pull Request — master (#5)
by Michael
02:50
created

FilesManagement::rmove()   B

Complexity

Conditions 11
Paths 7

Size

Total Lines 30
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 14
nc 7
nop 2
dl 0
loc 30
rs 7.3166
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
namespace XoopsModules\Tdmdownloads\Common;
4
5
/*
6
 You may not change or alter any portion of this comment or credits
7
 of supporting developers from this source code or any supporting source code
8
 which is considered copyrighted (c) material of the original comment or credit authors.
9
10
 This program is distributed in the hope that it will be useful,
11
 but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
 */
14
15
/**
16
 * @copyright   XOOPS Project (https://xoops.org)
17
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
18
 * @author      mamba <[email protected]>
19
 */
20
trait FilesManagement
21
{
22
    /**
23
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
24
     *
25
     * @param string $folder The full path of the directory to check
26
     *
27
     * @throws \RuntimeException
28
     */
29
    public static function createFolder($folder)
30
    {
31
        try {
32
            if (!file_exists($folder)) {
33
                if (!is_dir($folder) && !mkdir($folder) && !is_dir($folder)) {
34
                    throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
35
                }
36
37
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
38
            }
39
        }
40
        catch (\Exception $e) {
41
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
42
        }
43
    }
44
45
    /**
46
     * @param $file
47
     * @param $folder
48
     * @return bool
49
     */
50
    public static function copyFile($file, $folder)
51
    {
52
        return copy($file, $folder);
53
    }
54
55
    /**
56
     * @param $src
57
     * @param $dst
58
     * @throws \RuntimeException
59
     */
60
    public static function recurseCopy($src, $dst)
61
    {
62
        $dir = opendir($src);
63
        if (!mkdir($dst) && !is_dir($dst)) {
64
            throw new \RuntimeException('The directory ' . $dst . ' could not be created.');
65
        }
66
        while (false !== ($file = readdir($dir))) {
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type false; however, parameter $dir_handle of readdir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

66
        while (false !== ($file = readdir(/** @scrutinizer ignore-type */ $dir))) {
Loading history...
67
            if (('.' !== $file) && ('..' !== $file)) {
68
                if (is_dir($src . '/' . $file)) {
69
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
70
                } else {
71
                    copy($src . '/' . $file, $dst . '/' . $file);
72
                }
73
            }
74
        }
75
        closedir($dir);
0 ignored issues
show
Bug introduced by
It seems like $dir can also be of type false; however, parameter $dir_handle of closedir() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

75
        closedir(/** @scrutinizer ignore-type */ $dir);
Loading history...
76
    }
77
78
    /**
79
     * Remove files and (sub)directories
80
     *
81
     * @param string $src source directory to delete
82
     *
83
     * @uses \Xmf\Module\Helper::getHelper()
84
     * @uses \Xmf\Module\Helper::isUserAdmin()
85
     *
86
     * @return bool true on success
87
     */
88
    public static function deleteDirectory($src)
89
    {
90
        // Only continue if user is a 'global' Admin
91
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
92
            return false;
93
        }
94
95
        $success = true;
96
        // remove old files
97
        $dirInfo = new \SplFileInfo($src);
98
        // validate is a directory
99
        if ($dirInfo->isDir()) {
100
            $fileList = array_diff(scandir($src, SCANDIR_SORT_NONE), ['..', '.']);
101
            foreach ($fileList as $k => $v) {
102
                $fileInfo = new \SplFileInfo("{$src}/{$v}");
103
                if ($fileInfo->isDir()) {
104
                    // recursively handle subdirectories
105
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
106
                        break;
107
                    }
108
                } else {
109
                    // delete the file
110
                    if (!($success = unlink($fileInfo->getRealPath()))) {
111
                        break;
112
                    }
113
                }
114
            }
115
            // now delete this (sub)directory if all the files are gone
116
            if ($success) {
117
                $success = rmdir($dirInfo->getRealPath());
118
            }
119
        } else {
120
            // input is not a valid directory
121
            $success = false;
122
        }
123
124
        return $success;
125
    }
126
127
    /**
128
     * Recursively remove directory
129
     *
130
     * @todo currently won't remove directories with hidden files, should it?
131
     *
132
     * @param string $src directory to remove (delete)
133
     *
134
     * @return bool true on success
135
     */
136
    public static function rrmdir($src)
137
    {
138
        // Only continue if user is a 'global' Admin
139
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
140
            return false;
141
        }
142
143
        // If source is not a directory stop processing
144
        if (!is_dir($src)) {
145
            return false;
146
        }
147
148
        $success = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
149
150
        // Open the source directory to read in files
151
        $iterator = new \DirectoryIterator($src);
152
        foreach ($iterator as $fObj) {
153
            if ($fObj->isFile()) {
154
                $filename = $fObj->getPathname();
155
                $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...
156
                if (!unlink($filename)) {
157
                    return false; // couldn't delete the file
158
                }
159
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
160
                // Try recursively on directory
161
                self::rrmdir($fObj->getPathname());
162
            }
163
        }
164
        $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...
165
        return rmdir($src); // remove the directory & return results
166
    }
167
168
    /**
169
     * Recursively move files from one directory to another
170
     *
171
     * @param string $src  - Source of files being moved
172
     * @param string $dest - Destination of files being moved
173
     *
174
     * @return bool true on success
175
     */
176
    public static function rmove($src, $dest)
177
    {
178
        // Only continue if user is a 'global' Admin
179
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
180
            return false;
181
        }
182
183
        // If source is not a directory stop processing
184
        if (!is_dir($src)) {
185
            return false;
186
        }
187
188
        // If the destination directory does not exist and could not be created stop processing
189
        if (!is_dir($dest) && !mkdir($dest) && !is_dir($dest)) {
190
            return false;
191
        }
192
193
        // Open the source directory to read in files
194
        $iterator = new \DirectoryIterator($src);
195
        foreach ($iterator as $fObj) {
196
            if ($fObj->isFile()) {
197
                rename($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
198
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
199
                // Try recursively on directory
200
                self::rmove($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
201
                //                rmdir($fObj->getPath()); // now delete the directory
202
            }
203
        }
204
        $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...
205
        return rmdir($src); // remove the directory & return results
206
    }
207
208
    /**
209
     * Recursively copy directories and files from one directory to another
210
     *
211
     * @param string $src  - Source of files being moved
212
     * @param string $dest - Destination of files being moved
213
     *
214
     * @uses \Xmf\Module\Helper::getHelper()
215
     * @uses \Xmf\Module\Helper::isUserAdmin()
216
     *
217
     * @return bool true on success
218
     */
219
    public static function rcopy($src, $dest)
220
    {
221
        // Only continue if user is a 'global' Admin
222
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
223
            return false;
224
        }
225
226
        // If source is not a directory stop processing
227
        if (!is_dir($src)) {
228
            return false;
229
        }
230
231
        // If the destination directory does not exist and could not be created stop processing
232
        if (!is_dir($dest) && !mkdir($dest) && !is_dir($dest)) {
233
            return false;
234
        }
235
236
        // Open the source directory to read in files
237
        $iterator = new \DirectoryIterator($src);
238
        foreach ($iterator as $fObj) {
239
            if ($fObj->isFile()) {
240
                copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
241
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
242
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
243
            }
244
        }
245
246
        return true;
247
    }
248
}
249