Passed
Push — master ( eec3d3...7b6eed )
by Michael
02:45
created

FilesManagement::xcopy()   B

Complexity

Conditions 10
Paths 5

Size

Total Lines 33
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 14
nc 5
nop 2
dl 0
loc 33
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\Xoopsheadline\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
 * @copyright   XOOPS Project (https://xoops.org)
19
 * @license     http://www.fsf.org/copyleft/gpl.html GNU public license
20
 * @author      mamba <[email protected]>
21
 */
22
trait FilesManagement
23
{
24
    /**
25
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
26
     *
27
     * @param string $folder The full path of the directory to check
28
     */
29
    public static function createFolder(string $folder): void
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(), "\n", '<br>';
41
        }
42
    }
43
44
    public static function copyFile(string $file, string $folder): bool
45
    {
46
        return \copy($file, $folder);
47
    }
48
49
50
    public static function recurseCopy(string $src, string $dst): void
51
    {
52
        $dir = \opendir($src);
53
        //        @mkdir($dst);
54
        if (!@\mkdir($dst) && !\is_dir($dst)) {
55
            throw new \RuntimeException('The directory ' . $dst . ' could not be created.');
56
        }
57
        while (false !== ($file = \readdir($dir))) {
58
            if (('.' !== $file) && ('..' !== $file)) {
59
                if (\is_dir($src . '/' . $file)) {
60
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
61
                } else {
62
                    \copy($src . '/' . $file, $dst . '/' . $file);
63
                }
64
            }
65
        }
66
        \closedir($dir);
67
    }
68
69
    /**
70
     * Copy a file, or recursively copy a folder and its contents
71
     * @param string $source Source path
72
     * @param string $dest   Destination path
73
     * @return      bool     Returns true on success, false on failure
74
     * @author      Aidan Lister <[email protected]>
75
     * @version     1.0.1
76
     * @link        http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
77
     */
78
    public static function xcopy($source, $dest): bool
79
    {
80
        // Check for symlinks
81
        if (\is_link($source)) {
82
            return \symlink(\readlink($source), $dest);
83
        }
84
85
        // Simple copy for a file
86
        if (\is_file($source)) {
87
            return \copy($source, $dest);
88
        }
89
90
        // Make destination directory
91
        if (!\is_dir($dest) && (!\mkdir($dest) && !\is_dir($dest))) {
92
            throw new \RuntimeException(\sprintf('Directory "%s" was not created', $dest));
93
        }
94
95
        // Loop through the folder
96
        $dir = \dir($source);
97
        if (@\is_dir((string)$dir)) {
98
            while (false !== $entry = $dir->read()) {
99
                // Skip pointers
100
                if ('.' === $entry || '..' === $entry) {
101
                    continue;
102
                }
103
                // Deep copy directories
104
                self::xcopy("${source}/${entry}", "${dest}/${entry}");
105
            }
106
            // Clean up
107
            $dir->close();
108
        }
109
110
        return true;
111
    }
112
113
    /**
114
     * Remove files and (sub)directories
115
     *
116
     * @param string $src source directory to delete
117
     *
118
     * @return bool true on success
119
     * @uses \Xmf\Module\Helper::isUserAdmin()
120
     *
121
     * @uses \Xmf\Module\Helper::getHelper()
122
     */
123
    public static function deleteDirectory(string $src): bool
124
    {
125
        // Only continue if user is a 'global' Admin
126
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
127
            return false;
128
        }
129
130
        $success = true;
131
        // remove old files
132
        $dirInfo = new \SplFileInfo($src);
133
        // validate is a directory
134
        if ($dirInfo->isDir()) {
135
            $fileList = \array_diff(\scandir($src, \SCANDIR_SORT_NONE), ['..', '.']);
136
            foreach ($fileList as $k => $v) {
137
                $fileInfo = new \SplFileInfo("{$src}/{$v}");
138
                if ($fileInfo->isDir()) {
139
                    // recursively handle subdirectories
140
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
141
                        break;
142
                    }
143
                } elseif (!($success = \unlink($fileInfo->getRealPath()))) {
144
                    break;
145
                }
146
            }
147
            // now delete this (sub)directory if all the files are gone
148
            if ($success) {
149
                $success = \rmdir($dirInfo->getRealPath());
150
            }
151
        } else {
152
            // input is not a valid directory
153
            $success = false;
154
        }
155
156
        return $success;
157
    }
158
159
    /**
160
     * Recursively remove directory
161
     *
162
     * @todo currently won't remove directories with hidden files, should it?
163
     *
164
     * @param string $src directory to remove (delete)
165
     *
166
     * @return bool true on success
167
     */
168
    public static function rrmdir(string $src): bool
169
    {
170
        // Only continue if user is a 'global' Admin
171
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
172
            return false;
173
        }
174
175
        // If source is not a directory stop processing
176
        if (!\is_dir($src)) {
177
            return false;
178
        }
179
180
        $success = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
181
182
        // Open the source directory to read in files
183
        $iterator = new \DirectoryIterator($src);
184
        foreach ($iterator as $fObj) {
185
            if ($fObj->isFile()) {
186
                $filename = $fObj->getPathname();
187
                $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...
188
                if (!\unlink($filename)) {
189
                    return false; // couldn't delete the file
190
                }
191
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
192
                // Try recursively on directory
193
                self::rrmdir($fObj->getPathname());
194
            }
195
        }
196
        $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...
197
        return \rmdir($src); // remove the directory & return results
198
    }
199
200
    /**
201
     * Recursively move files from one directory to another
202
     *
203
     * @param string $src  - Source of files being moved
204
     * @param string $dest - Destination of files being moved
205
     *
206
     * @return bool true on success
207
     */
208
    public static function rmove(string $src, string $dest): bool
209
    {
210
        // Only continue if user is a 'global' Admin
211
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
212
            return false;
213
        }
214
215
        // If source is not a directory stop processing
216
        if (!\is_dir($src)) {
217
            return false;
218
        }
219
220
        // If the destination directory does not exist and could not be created stop processing
221
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
222
            return false;
223
        }
224
225
        // Open the source directory to read in files
226
        $iterator = new \DirectoryIterator($src);
227
        foreach ($iterator as $fObj) {
228
            if ($fObj->isFile()) {
229
                \rename($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
230
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
231
                // Try recursively on directory
232
                self::rmove($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
233
                //                rmdir($fObj->getPath()); // now delete the directory
234
            }
235
        }
236
        $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...
237
        return \rmdir($src); // remove the directory & return results
238
    }
239
240
    /**
241
     * Recursively copy directories and files from one directory to another
242
     *
243
     * @param string $src  - Source of files being moved
244
     * @param string $dest - Destination of files being moved
245
     *
246
     * @return bool true on success
247
     * @uses \Xmf\Module\Helper::isUserAdmin()
248
     *
249
     * @uses \Xmf\Module\Helper::getHelper()
250
     */
251
    public static function rcopy(string $src, string $dest): bool
252
    {
253
        // Only continue if user is a 'global' Admin
254
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
255
            return false;
256
        }
257
258
        // If source is not a directory stop processing
259
        if (!\is_dir($src)) {
260
            return false;
261
        }
262
263
        // If the destination directory does not exist and could not be created stop processing
264
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
265
            return false;
266
        }
267
268
        // Open the source directory to read in files
269
        $iterator = new \DirectoryIterator($src);
270
        foreach ($iterator as $fObj) {
271
            if ($fObj->isFile()) {
272
                \copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
273
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
274
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
275
            }
276
        }
277
278
        return true;
279
    }
280
}
281