Passed
Push — master ( 919ce4...d1101e )
by Michael
03:15 queued 11s
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
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
declare(strict_types=1);
4
5
namespace XoopsModules\Adslight\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
     * @throws \RuntimeException
30
     */
31
    public static function createFolder($folder): void
32
    {
33
        try {
34
            if (!\is_dir($folder)) {
35
                if (!\is_dir($folder) && !\mkdir($folder) && !\is_dir($folder)) {
36
                    throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder));
37
                }
38
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
39
            }
40
        } catch (\Throwable $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): bool
51
    {
52
        return \copy($file, $folder);
53
    }
54
55
    /**
56
     * @param $src
57
     * @param $dst
58
     */
59
    public static function recurseCopy($src, $dst): void
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
     * @param string $source Source path
81
     * @param string $dest   Destination path
82
     * @return      bool     Returns true on success, false on failure
83
     * @author      Aidan Lister <[email protected]>
84
     * @version     1.0.1
85
     * @link        http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
86
     */
87
    public static function xcopy($source, $dest): bool
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((string)$dir)) {
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
     * @return bool true on success
128
     * @uses \Xmf\Module\Helper::isUserAdmin()
129
     *
130
     * @uses \Xmf\Module\Helper::getHelper()
131
     */
132
    public static function deleteDirectory($src): bool
133
    {
134
        // Only continue if user is a 'global' Admin
135
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
136
            return false;
137
        }
138
        $success = true;
139
        // remove old files
140
        $dirInfo = new \SplFileInfo($src);
141
        // validate is a directory
142
        if ($dirInfo->isDir()) {
143
            $fileList = \array_diff(\scandir($src, \SCANDIR_SORT_NONE), ['..', '.']);
144
            foreach ($fileList as $k => $v) {
145
                $fileInfo = new \SplFileInfo("${src}/${v}");
146
                if ($fileInfo->isDir()) {
147
                    // recursively handle subdirectories
148
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
149
                        break;
150
                    }
151
                } elseif (!($success = \unlink($fileInfo->getRealPath()))) {
152
                    break;
153
                }
154
            }
155
            // now delete this (sub)directory if all the files are gone
156
            if ($success) {
157
                $success = \rmdir($dirInfo->getRealPath());
158
            }
159
        } else {
160
            // input is not a valid directory
161
            $success = false;
162
        }
163
        return $success;
164
    }
165
166
    /**
167
     * Recursively remove directory
168
     *
169
     * @todo currently won't remove directories with hidden files, should it?
170
     *
171
     * @param string $src directory to remove (delete)
172
     *
173
     * @return bool true on success
174
     */
175
    public static function rrmdir($src): bool
176
    {
177
        // Only continue if user is a 'global' Admin
178
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
179
            return false;
180
        }
181
        // If source is not a directory stop processing
182
        if (!\is_dir($src)) {
183
            return false;
184
        }
185
        $success = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
186
        // Open the source directory to read in files
187
        $iterator = new \DirectoryIterator($src);
188
        foreach ($iterator as $fObj) {
189
            if ($fObj->isFile()) {
190
                $filename = $fObj->getPathname();
191
                $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...
192
                if (!\unlink($filename)) {
193
                    return false; // couldn't delete the file
194
                }
195
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
196
                // Try recursively on directory
197
                self::rrmdir($fObj->getPathname());
198
            }
199
        }
200
        $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...
201
        return \rmdir($src); // remove the directory & return results
202
    }
203
204
    /**
205
     * Recursively move files from one directory to another
206
     *
207
     * @param string $src  - Source of files being moved
208
     * @param string $dest - Destination of files being moved
209
     *
210
     * @return bool true on success
211
     */
212
    public static function rmove($src, $dest): bool
213
    {
214
        // Only continue if user is a 'global' Admin
215
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
216
            return false;
217
        }
218
        // If source is not a directory stop processing
219
        if (!\is_dir($src)) {
220
            return false;
221
        }
222
        // If the destination directory does not exist and could not be created stop processing
223
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
224
            return false;
225
        }
226
        // Open the source directory to read in files
227
        $iterator = new \DirectoryIterator($src);
228
        foreach ($iterator as $fObj) {
229
            if ($fObj->isFile()) {
230
                \rename($fObj->getPathname(), "${dest}/" . $fObj->getFilename());
231
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
232
                // Try recursively on directory
233
                self::rmove($fObj->getPathname(), "${dest}/" . $fObj->getFilename());
234
                //                rmdir($fObj->getPath()); // now delete the directory
235
            }
236
        }
237
        $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...
238
        return \rmdir($src); // remove the directory & return results
239
    }
240
241
    /**
242
     * Recursively copy directories and files from one directory to another
243
     *
244
     * @param string $src  - Source of files being moved
245
     * @param string $dest - Destination of files being moved
246
     *
247
     * @return bool true on success
248
     * @uses \Xmf\Module\Helper::isUserAdmin()
249
     *
250
     * @uses \Xmf\Module\Helper::getHelper()
251
     */
252
    public static function rcopy($src, $dest): bool
253
    {
254
        // Only continue if user is a 'global' Admin
255
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
256
            return false;
257
        }
258
        // If source is not a directory stop processing
259
        if (!\is_dir($src)) {
260
            return false;
261
        }
262
        // If the destination directory does not exist and could not be created stop processing
263
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
264
            return false;
265
        }
266
        // Open the source directory to read in files
267
        $iterator = new \DirectoryIterator($src);
268
        foreach ($iterator as $fObj) {
269
            if ($fObj->isFile()) {
270
                \copy($fObj->getPathname(), "${dest}/" . $fObj->getFilename());
271
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
272
                self::rcopy($fObj->getPathname(), "${dest}/" . $fObj->getFilename());
273
            }
274
        }
275
        return true;
276
    }
277
}
278