FilesManagement   C
last analyzed

Complexity

Total Complexity 54

Size/Duplication

Total Lines 229
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 80
dl 0
loc 229
rs 6.4799
c 1
b 0
f 0
wmc 54

7 Methods

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

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