FilesManagement   C
last analyzed

Complexity

Total Complexity 54

Size/Duplication

Total Lines 225
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 54
eloc 80
c 0
b 0
f 0
dl 0
loc 225
rs 6.4799

7 Methods

Rating   Name   Duplication   Size   Complexity  
A copyFile() 0 3 1
A createFolder() 0 12 6
B recurseCopy() 0 17 7
B deleteDirectory() 0 34 9
B rrmdir() 0 31 9
B rmove() 0 31 11
B rcopy() 0 28 11

How to fix   Complexity   

Complex Class

Complex classes like FilesManagement often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use FilesManagement, and based on these observations, apply Extract Interface, too.

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