Passed
Pull Request — master (#1500)
by Michael
09:16
created

FilesManagement::rcopy()   B

Complexity

Conditions 11
Paths 7

Size

Total Lines 28
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 13
c 1
b 0
f 0
nc 7
nop 2
dl 0
loc 28
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 declare(strict_types=1);
2
3
namespace XoopsModules\Moduleinstaller\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
use DirectoryIterator;
16
use RuntimeException;
17
use SplFileInfo;
18
use XoopsUser;
19
20
/**
21
 * @copyright   XOOPS Project (https://xoops.org)
22
 * @license     GNU GPL 2.0 or later (https://www.gnu.org/licenses/gpl-2.0.html)
23
 * @author      mamba <[email protected]>
24
 */
25
trait FilesManagement
26
{
27
    /**
28
     * Function responsible for checking if a directory exists, we can also write in and create an index.html file
29
     *
30
     * @param string $folder The full path of the directory to check
31
     */
32
    public static function createFolder($folder): void
33
    {
34
        try {
35
            if (!\is_dir($folder)) {
36
                if (!\is_dir($folder) && !\mkdir($folder) && !\is_dir($folder)) {
37
                    throw new RuntimeException(\sprintf('Unable to create the %s directory', $folder));
38
                }
39
40
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
41
            }
42
        } catch (\Throwable $e) {
43
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
44
        }
45
    }
46
47
    /**
48
     * @param $file
49
     * @param $folder
50
     * @return bool
51
     */
52
    public static function copyFile(string $file, string $folder): bool
53
    {
54
        return \copy($file, $folder);
55
    }
56
57
    /**
58
     * @param $src
59
     * @param $dst
60
     */
61
    public static function recurseCopy($src, $dst): void
62
    {
63
        $dir = \opendir($src);
64
        //        @mkdir($dst);
65
        if (!@\mkdir($dst) && !\is_dir($dst)) {
66
            throw new RuntimeException('The directory ' . $dst . ' could not be created.');
67
        }
68
        while (false !== ($file = \readdir($dir))) {
69
            if (('.' !== $file) && ('..' !== $file)) {
70
                if (\is_dir($src . '/' . $file)) {
71
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
72
                } else {
73
                    \copy($src . '/' . $file, $dst . '/' . $file);
74
                }
75
            }
76
        }
77
        \closedir($dir);
78
    }
79
80
    /**
81
     * Remove files and (sub)directories
82
     *
83
     * @param string $src source directory to delete
84
     *
85
     * @return bool true on success
86
     * @uses \Xmf\Module\Helper::isUserAdmin()
87
     *
88
     * @uses \Xmf\Module\Helper::getHelper()
89
     */
90
    public static function deleteDirectory($src)
91
    {
92
        // Only continue if user is a 'global' Admin
93
        if (!($GLOBALS['xoopsUser'] instanceof XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
94
            return false;
95
        }
96
97
        $success = true;
98
        // remove old files
99
        $dirInfo = new SplFileInfo($src);
100
        // validate is a directory
101
        if ($dirInfo->isDir()) {
102
            $fileList = \array_diff(\scandir($src, \SCANDIR_SORT_NONE), ['..', '.']);
103
            foreach ($fileList as $k => $v) {
104
                $fileInfo = new SplFileInfo("{$src}/{$v}");
105
                if ($fileInfo->isDir()) {
106
                    // recursively handle subdirectories
107
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
108
                        break;
109
                    }
110
                } elseif (!($success = \unlink($fileInfo->getRealPath()))) {
111
                    break;
112
                }
113
            }
114
            // now delete this (sub)directory if all the files are gone
115
            if ($success) {
116
                $success = \rmdir($dirInfo->getRealPath());
117
            }
118
        } else {
119
            // input is not a valid directory
120
            $success = false;
121
        }
122
123
        return $success;
124
    }
125
126
    /**
127
     * Recursively remove directory
128
     *
129
     * @todo currently won't remove directories with hidden files, should it?
130
     *
131
     * @param string $src directory to remove (delete)
132
     *
133
     * @return bool true on success
134
     */
135
    public static function rrmdir($src)
136
    {
137
        // Only continue if user is a 'global' Admin
138
        if (!($GLOBALS['xoopsUser'] instanceof XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
139
            return false;
140
        }
141
142
        // If source is not a directory stop processing
143
        if (!\is_dir($src)) {
144
            return false;
145
        }
146
147
        $success = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
148
149
        // Open the source directory to read in files
150
        $iterator = new DirectoryIterator($src);
151
        foreach ($iterator as $fObj) {
152
            if ($fObj->isFile()) {
153
                $filename = $fObj->getPathname();
154
                $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...
155
                if (!\unlink($filename)) {
156
                    return false; // couldn't delete the file
157
                }
158
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
159
                // Try recursively on directory
160
                self::rrmdir($fObj->getPathname());
161
            }
162
        }
163
        $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...
164
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
206
        return \rmdir($src); // remove the directory & return results
207
    }
208
209
    /**
210
     * Recursively copy directories and files from one directory to another
211
     *
212
     * @param string $src  - Source of files being moved
213
     * @param string $dest - Destination of files being moved
214
     *
215
     * @return bool true on success
216
     * @uses \Xmf\Module\Helper::isUserAdmin()
217
     *
218
     * @uses \Xmf\Module\Helper::getHelper()
219
     */
220
    public static function rcopy($src, $dest)
221
    {
222
        // Only continue if user is a 'global' Admin
223
        if (!($GLOBALS['xoopsUser'] instanceof XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
224
            return false;
225
        }
226
227
        // If source is not a directory stop processing
228
        if (!\is_dir($src)) {
229
            return false;
230
        }
231
232
        // If the destination directory does not exist and could not be created stop processing
233
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
234
            return false;
235
        }
236
237
        // Open the source directory to read in files
238
        $iterator = new DirectoryIterator($src);
239
        foreach ($iterator as $fObj) {
240
            if ($fObj->isFile()) {
241
                \copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
242
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
243
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
244
            }
245
        }
246
247
        return true;
248
    }
249
}
250