FilesManagement::rmove()   B
last analyzed

Complexity

Conditions 11
Paths 7

Size

Total Lines 30
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 14
c 1
b 0
f 0
nc 7
nop 2
dl 0
loc 30
rs 7.3166

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\Blocksadmin\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 (!\is_dir($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
        } catch (\Exception $e) {
40
            echo 'Caught exception: ', $e->getMessage(), '<br>';
41
        }
42
    }
43
44
    /**
45
     * @param $file
46
     * @param $folder
47
     * @return bool
48
     */
49
    public static function copyFile($file, $folder)
50
    {
51
        return \copy($file, $folder);
52
    }
53
54
    /**
55
     * @param $src
56
     * @param $dst
57
     */
58
    public static function recurseCopy($src, $dst)
59
    {
60
        $dir = \opendir($src);
61
        //        @mkdir($dst);
62
        if (!@\mkdir($dst) && !\is_dir($dst)) {
63
            throw new \RuntimeException('The directory ' . $dst . ' could not be created.');
64
        }
65
        while (false !== ($file = \readdir($dir))) {
66
            if (('.' !== $file) && ('..' !== $file)) {
67
                if (\is_dir($src . '/' . $file)) {
68
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
69
                } else {
70
                    \copy($src . '/' . $file, $dst . '/' . $file);
71
                }
72
            }
73
        }
74
        \closedir($dir);
75
    }
76
77
    /**
78
     * Copy a file, or recursively copy a folder and its contents
79
     * @param string $source Source path
80
     * @param string $dest   Destination path
81
     * @return      bool     Returns true on success, false on failure
82
     * @author      Aidan Lister <[email protected]>
83
     * @version     1.0.1
84
     * @link        http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
85
     */
86
    public static function xcopy($source, $dest)
87
    {
88
        // Check for symlinks
89
        if (\is_link($source)) {
90
            return \symlink(\readlink($source), $dest);
91
        }
92
93
        // Simple copy for a file
94
        if (\is_file($source)) {
95
            return \copy($source, $dest);
96
        }
97
98
        // Make destination directory
99
        if (!\is_dir($dest)) {
100
            if (!\mkdir($dest) && !\is_dir($dest)) {
101
                throw new \RuntimeException(\sprintf('Directory "%s" was not created', $dest));
102
            }
103
        }
104
105
        // Loop through the folder
106
        $dir = \dir($source);
107
        if (@\is_dir($dir)) {
0 ignored issues
show
Bug introduced by
$dir of type Directory is incompatible with the type string expected by parameter $filename of is_dir(). ( Ignorable by Annotation )

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

107
        if (@\is_dir(/** @scrutinizer ignore-type */ $dir)) {
Loading history...
108
            while (false !== $entry = $dir->read()) {
109
                // Skip pointers
110
                if ('.' === $entry || '..' === $entry) {
111
                    continue;
112
                }
113
                // Deep copy directories
114
                self::xcopy("$source/$entry", "$dest/$entry");
115
            }
116
            // Clean up
117
            $dir->close();
118
        }
119
120
        return true;
121
    }
122
123
    /**
124
     * Remove files and (sub)directories
125
     *
126
     * @param string $src source directory to delete
127
     *
128
     * @return bool true on success
129
     * @uses \Xmf\Module\Helper::isUserAdmin()
130
     *
131
     * @uses \Xmf\Module\Helper::getHelper()
132
     */
133
    public static function deleteDirectory($src)
134
    {
135
        // Only continue if user is a 'global' Admin
136
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
137
            return false;
138
        }
139
140
        $success = true;
141
        // remove old files
142
        $dirInfo = new \SplFileInfo($src);
143
        // validate is a directory
144
        if ($dirInfo->isDir()) {
145
            $fileList = \array_diff(\scandir($src, \SCANDIR_SORT_NONE), ['..', '.']);
146
            foreach ($fileList as $k => $v) {
147
                $fileInfo = new \SplFileInfo("{$src}/{$v}");
148
                if ($fileInfo->isDir()) {
149
                    // recursively handle subdirectories
150
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
151
                        break;
152
                    }
153
                } elseif (!($success = \unlink($fileInfo->getRealPath()))) {
154
                    break;
155
                }
156
            }
157
            // now delete this (sub)directory if all the files are gone
158
            if ($success) {
159
                $success = \rmdir($dirInfo->getRealPath());
160
            }
161
        } else {
162
            // input is not a valid directory
163
            $success = false;
164
        }
165
166
        return $success;
167
    }
168
169
    /**
170
     * Recursively remove directory
171
     *
172
     * @todo currently won't remove directories with hidden files, should it?
173
     *
174
     * @param string $src directory to remove (delete)
175
     *
176
     * @return bool true on success
177
     */
178
    public static function rrmdir($src)
179
    {
180
        // Only continue if user is a 'global' Admin
181
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
182
            return false;
183
        }
184
185
        // If source is not a directory stop processing
186
        if (!\is_dir($src)) {
187
            return false;
188
        }
189
190
        $success = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
191
192
        // Open the source directory to read in files
193
        $iterator = new \DirectoryIterator($src);
194
        foreach ($iterator as $fObj) {
195
            if ($fObj->isFile()) {
196
                $filename = $fObj->getPathname();
197
                $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...
198
                if (!\unlink($filename)) {
199
                    return false; // couldn't delete the file
200
                }
201
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
202
                // Try recursively on directory
203
                self::rrmdir($fObj->getPathname());
204
            }
205
        }
206
        $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...
207
        return \rmdir($src); // remove the directory & return results
208
    }
209
210
    /**
211
     * Recursively move files from one directory to another
212
     *
213
     * @param string $src  - Source of files being moved
214
     * @param string $dest - Destination of files being moved
215
     *
216
     * @return bool true on success
217
     */
218
    public static function rmove($src, $dest)
219
    {
220
        // Only continue if user is a 'global' Admin
221
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
222
            return false;
223
        }
224
225
        // If source is not a directory stop processing
226
        if (!\is_dir($src)) {
227
            return false;
228
        }
229
230
        // If the destination directory does not exist and could not be created stop processing
231
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
232
            return false;
233
        }
234
235
        // Open the source directory to read in files
236
        $iterator = new \DirectoryIterator($src);
237
        foreach ($iterator as $fObj) {
238
            if ($fObj->isFile()) {
239
                \rename($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
240
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
241
                // Try recursively on directory
242
                self::rmove($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
243
                //                rmdir($fObj->getPath()); // now delete the directory
244
            }
245
        }
246
        $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...
247
        return \rmdir($src); // remove the directory & return results
248
    }
249
250
    /**
251
     * Recursively copy directories and files from one directory to another
252
     *
253
     * @param string $src  - Source of files being moved
254
     * @param string $dest - Destination of files being moved
255
     *
256
     * @return bool true on success
257
     * @uses \Xmf\Module\Helper::isUserAdmin()
258
     *
259
     * @uses \Xmf\Module\Helper::getHelper()
260
     */
261
    public static function rcopy($src, $dest)
262
    {
263
        // Only continue if user is a 'global' Admin
264
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
265
            return false;
266
        }
267
268
        // If source is not a directory stop processing
269
        if (!\is_dir($src)) {
270
            return false;
271
        }
272
273
        // If the destination directory does not exist and could not be created stop processing
274
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
275
            return false;
276
        }
277
278
        // Open the source directory to read in files
279
        $iterator = new \DirectoryIterator($src);
280
        foreach ($iterator as $fObj) {
281
            if ($fObj->isFile()) {
282
                \copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
283
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
284
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
285
            }
286
        }
287
288
        return true;
289
    }
290
}
291