FilesManagement   C
last analyzed

Complexity

Total Complexity 55

Size/Duplication

Total Lines 210
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 80
dl 0
loc 210
rs 6
c 0
b 0
f 0
wmc 55

7 Methods

Rating   Name   Duplication   Size   Complexity  
B deleteDirectory() 0 32 9
B rcopy() 0 24 11
B rmove() 0 27 11
B rrmdir() 0 27 10
B recurseCopy() 0 16 7
A copyFile() 0 3 1
A createFolder() 0 11 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
namespace XoopsModules\Xsitemap\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     http://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
     * @throws \RuntimeException
28
     */
29
    public static function createFolder($folder)
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
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
37
            }
38
        } catch (\RuntimeException $e) {
39
            echo 'Caught exception: ', $e->getMessage(), "\n", '<br>';
40
        }
41
    }
42
43
    /**
44
     * @param $file
45
     * @param $folder
46
     * @return bool
47
     */
48
    public static function copyFile($file, $folder)
49
    {
50
        return \copy($file, $folder);
51
    }
52
53
    /**
54
     * @param $src
55
     * @param $dst
56
     */
57
    public static function recurseCopy($src, $dst)
58
    {
59
        $dir = \opendir($src);
60
        //        @mkdir($dst);
61
        if (!@\mkdir($dst) && !\is_dir($dst)) {
62
            throw new \RuntimeException('The directory ' . $dst . ' could not be created.');
63
        }
64
        while (false !== ($file = \readdir($dir))) {
65
            if (('.' !== $file) && ('..' !== $file)) {
66
                if (\is_dir($src . '/' . $file)) {
67
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
68
                } else {
69
                    \copy($src . '/' . $file, $dst . '/' . $file);
70
                }
71
            }
72
            \closedir($dir);
73
        }
74
    }
75
76
    /**
77
     * Remove files and (sub)directories
78
     *
79
     * @param string $src source directory to delete
80
     *
81
     * @return bool true on success
82
     * @uses \Xmf\Module\Helper::isUserAdmin()
83
     *
84
     * @uses \Xmf\Module\Helper::getHelper()
85
     */
86
    public static function deleteDirectory($src)
87
    {
88
        // Only continue if user is a 'global' Admin
89
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
90
            return false;
91
        }
92
        $success = true;
93
        // remove old files
94
        $dirInfo = new \SplFileInfo($src);
95
        // validate is a directory
96
        if ($dirInfo->isDir()) {
97
            $fileList = \array_diff(\scandir($src, \SCANDIR_SORT_NONE), ['..', '.']);
98
            foreach ($fileList as $k => $v) {
99
                $fileInfo = new \SplFileInfo("{$src}/{$v}");
100
                if ($fileInfo->isDir()) {
101
                    // recursively handle subdirectories
102
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
103
                        break;
104
                    }
105
                } elseif (!($success = \unlink($fileInfo->getRealPath()))) {
106
                    break;
107
                }
108
            }
109
            // now delete this (sub)directory if all the files are gone
110
            if ($success) {
111
                $success = \rmdir($dirInfo->getRealPath());
112
            }
113
        } else {
114
            // input is not a valid directory
115
            $success = false;
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
        // If source is not a directory stop processing
136
        if (!\is_dir($src)) {
137
            return false;
138
        }
139
        $success = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $success is dead and can be removed.
Loading history...
140
        // Open the source directory to read in files
141
        $iterator = new \DirectoryIterator($src);
142
        foreach ($iterator as $fObj) {
143
            if (null !== $fObj && $fObj->isFile()) {
144
                $filename = $fObj->getPathname();
145
                $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...
146
                if (!\unlink($filename)) {
147
                    return false; // couldn't delete the file
148
                }
149
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
150
                // Try recursively on directory
151
                self::rrmdir($fObj->getPathname());
152
            }
153
        }
154
        $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...
155
        return \rmdir($src); // remove the directory & return results
156
    }
157
158
    /**
159
     * Recursively move files from one directory to another
160
     *
161
     * @param string $src  - Source of files being moved
162
     * @param string $dest - Destination of files being moved
163
     *
164
     * @return bool true on success
165
     */
166
    public static function rmove($src, $dest)
167
    {
168
        // Only continue if user is a 'global' Admin
169
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
170
            return false;
171
        }
172
        // If source is not a directory stop processing
173
        if (!\is_dir($src)) {
174
            return false;
175
        }
176
        // If the destination directory does not exist and could not be created stop processing
177
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
178
            return false;
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($src, $dest)
207
    {
208
        // Only continue if user is a 'global' Admin
209
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
210
            return false;
211
        }
212
        // If source is not a directory stop processing
213
        if (!\is_dir($src)) {
214
            return false;
215
        }
216
        // If the destination directory does not exist and could not be created stop processing
217
        if (!\is_dir($dest) && !\mkdir($dest) && !\is_dir($dest)) {
218
            return false;
219
        }
220
        // Open the source directory to read in files
221
        $iterator = new \DirectoryIterator($src);
222
        foreach ($iterator as $fObj) {
223
            if ($fObj->isFile()) {
224
                \copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
225
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
226
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
227
            }
228
        }
229
        return true;
230
    }
231
}
232