Passed
Pull Request — master (#8)
by Michael
11:33
created

FilesManagement::rcopy()   B

Complexity

Conditions 11
Paths 7

Size

Total Lines 28
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 13
c 0
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\Myiframe\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     https://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
    public static function createFolder($folder): void
28
    {
29
        try {
30
            if (!\is_dir($folder)) {
31
                if (!\is_dir($folder) && !\mkdir($folder) && !\is_dir($folder)) {
32
                    throw new \RuntimeException(\sprintf('Unable to create the %s directory', $folder));
33
                }
34
35
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
36
            }
37
        } catch (\Throwable $e) {
38
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
39
        }
40
    }
41
42
    /**
43
     * @param $file
44
     * @param $folder
45
     */
46
    public static function copyFile(string $file, string $folder): bool
47
    {
48
        return \copy($file, $folder);
49
    }
50
51
    /**
52
     * @param $src
53
     * @param $dst
54
     */
55
    public static function recurseCopy($src, $dst): void
56
    {
57
        $dir = \opendir($src);
58
        //        @mkdir($dst);
59
        if (!@\mkdir($dst) && !\is_dir($dst)) {
60
            throw new \RuntimeException('The directory ' . $dst . ' could not be created.');
61
        }
62
        while (false !== ($file = \readdir($dir))) {
63
            if (('.' !== $file) && ('..' !== $file)) {
64
                if (\is_dir($src . '/' . $file)) {
65
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
66
                } else {
67
                    \copy($src . '/' . $file, $dst . '/' . $file);
68
                }
69
            }
70
        }
71
        \closedir($dir);
72
    }
73
74
    /**
75
     * Remove files and (sub)directories
76
     *
77
     * @param string $src source directory to delete
78
     *
79
     * @return bool true on success
80
     * @uses \Xmf\Module\Helper::isUserAdmin()
81
     *
82
     * @uses \Xmf\Module\Helper::getHelper()
83
     */
84
    public static function deleteDirectory($src)
85
    {
86
        // Only continue if user is a 'global' Admin
87
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
88
            return false;
89
        }
90
91
        $success = true;
92
        // remove old files
93
        $dirInfo = new \SplFileInfo($src);
94
        // validate is a directory
95
        if ($dirInfo->isDir()) {
96
            $fileList = \array_diff(\scandir($src, \SCANDIR_SORT_NONE), ['..', '.']);
97
            foreach ($fileList as $k => $v) {
98
                $fileInfo = new \SplFileInfo("{$src}/{$v}");
99
                if ($fileInfo->isDir()) {
100
                    // recursively handle subdirectories
101
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
102
                        break;
103
                    }
104
                } elseif (!($success = \unlink($fileInfo->getRealPath()))) {
105
                    break;
106
                }
107
            }
108
            // now delete this (sub)directory if all the files are gone
109
            if ($success) {
110
                $success = \rmdir($dirInfo->getRealPath());
111
            }
112
        } else {
113
            // input is not a valid directory
114
            $success = false;
115
        }
116
117
        return $success;
118
    }
119
120
    /**
121
     * Recursively remove directory
122
     *
123
     * @todo currently won't remove directories with hidden files, should it?
124
     *
125
     * @param string $src directory to remove (delete)
126
     *
127
     * @return bool true on success
128
     */
129
    public static function rrmdir($src)
130
    {
131
        // Only continue if user is a 'global' Admin
132
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
133
            return false;
134
        }
135
136
        // If source is not a directory stop processing
137
        if (!\is_dir($src)) {
138
            return false;
139
        }
140
141
        $success = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
142
143
        // Open the source directory to read in files
144
        $iterator = new \DirectoryIterator($src);
145
        foreach ($iterator as $fObj) {
146
            if ($fObj->isFile()) {
147
                $filename = $fObj->getPathname();
148
                $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...
149
                if (!\unlink($filename)) {
150
                    return false; // couldn't delete the file
151
                }
152
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
153
                // Try recursively on directory
154
                self::rrmdir($fObj->getPathname());
155
            }
156
        }
157
        $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...
158
159
        return \rmdir($src); // remove the directory & return results
160
    }
161
162
    /**
163
     * Recursively move files from one directory to another
164
     *
165
     * @param string $src  - Source of files being moved
166
     * @param string $dest - Destination of files being moved
167
     *
168
     * @return bool true on success
169
     */
170
    public static function rmove($src, $dest)
171
    {
172
        // Only continue if user is a 'global' Admin
173
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
174
            return false;
175
        }
176
177
        // If source is not a directory stop processing
178
        if (!\is_dir($src)) {
179
            return false;
180
        }
181
182
        // If the destination directory does not exist and could not be created stop processing
183
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
184
            return false;
185
        }
186
187
        // Open the source directory to read in files
188
        $iterator = new \DirectoryIterator($src);
189
        foreach ($iterator as $fObj) {
190
            if ($fObj->isFile()) {
191
                \rename($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
192
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
193
                // Try recursively on directory
194
                self::rmove($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
195
                //                rmdir($fObj->getPath()); // now delete the directory
196
            }
197
        }
198
        $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...
199
200
        return \rmdir($src); // remove the directory & return results
201
    }
202
203
    /**
204
     * Recursively copy directories and files from one directory to another
205
     *
206
     * @param string $src  - Source of files being moved
207
     * @param string $dest - Destination of files being moved
208
     *
209
     * @return bool true on success
210
     * @uses \Xmf\Module\Helper::isUserAdmin()
211
     *
212
     * @uses \Xmf\Module\Helper::getHelper()
213
     */
214
    public static function rcopy($src, $dest)
215
    {
216
        // Only continue if user is a 'global' Admin
217
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
218
            return false;
219
        }
220
221
        // If source is not a directory stop processing
222
        if (!\is_dir($src)) {
223
            return false;
224
        }
225
226
        // If the destination directory does not exist and could not be created stop processing
227
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
228
            return false;
229
        }
230
231
        // Open the source directory to read in files
232
        $iterator = new \DirectoryIterator($src);
233
        foreach ($iterator as $fObj) {
234
            if ($fObj->isFile()) {
235
                \copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
236
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
237
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
238
            }
239
        }
240
241
        return true;
242
    }
243
}
244