FilesManagement::xcopy()   B
last analyzed

Complexity

Conditions 10
Paths 5

Size

Total Lines 33
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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

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\Oledrion\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 (\Throwable $e) {
41
            echo 'Caught exception: ', $e->getMessage(), '<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
     */
59
    public static function recurseCopy($src, $dst)
60
    {
61
        $dir = opendir($src);
62
        //        @mkdir($dst);
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))) {
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);
76
    }
77
78
    /**
79
     * Copy a file, or recursively copy a folder and its contents
80
     * @author      Aidan Lister <[email protected]>
81
     * @version     1.0.1
82
     * @link        http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
83
     * @param       string $source Source path
84
     * @param       string $dest   Destination path
85
     * @return      bool     Returns true on success, false on failure
86
     */
87
    public static function xcopy($source, $dest)
88
    {
89
        // Check for symlinks
90
        if (is_link($source)) {
91
            return symlink(readlink($source), $dest);
92
        }
93
94
        // Simple copy for a file
95
        if (is_file($source)) {
96
            return copy($source, $dest);
97
        }
98
99
        // Make destination directory
100
        if (!is_dir($dest) && !mkdir($dest) && !is_dir($dest)) {
101
            throw new \RuntimeException(sprintf('Directory "%s" was not created', $dest));
102
        }
103
104
        // Loop through the folder
105
        $dir = dir($source);
106
        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

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