FilesManagement   C
last analyzed

Complexity

Total Complexity 54

Size/Duplication

Total Lines 212
Duplicated Lines 0 %

Importance

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

7 Methods

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

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