FilesManagement::rcopy()   B
last analyzed

Complexity

Conditions 11
Paths 7

Size

Total Lines 24
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 11
eloc 13
nc 7
nop 2
dl 0
loc 24
rs 7.3166
c 1
b 0
f 0

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