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

FilesManagement::xcopy()   B

Complexity

Conditions 10
Paths 7

Size

Total Lines 35
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 10
eloc 15
c 1
b 0
f 0
nc 7
nop 2
dl 0
loc 35
rs 7.6666

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