FilesManagement::rmove()   B
last analyzed

Complexity

Conditions 11
Paths 7

Size

Total Lines 31

Duplication

Lines 31
Ratio 100 %

Importance

Changes 0
Metric Value
cc 11
nc 7
nop 2
dl 31
loc 31
rs 7.3166
c 0
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
namespace XoopsModules\Xnewsletter\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
     * @return void
29
     */
30
    public static function createFolder($folder)
31
    {
32
        try {
33
            if (!file_exists($folder)) {
34
                if (!is_dir($folder) && !mkdir($folder) && !is_dir($folder)) {
35
                    throw new \RuntimeException(sprintf('Unable to create the %s directory', $folder));
36
                }
37
38
                file_put_contents($folder . '/index.html', '<script>history.go(-1);</script>');
39
            }
40
        } catch (\Exception $e) {
41
            echo 'Caught exception: ', $e->getMessage(), '<br>';
42
        }
43
    }
44
45
    /**
46
     * @param $file
47
     * @param $folder
48
     * @return bool
49
     */
50
    public static function copyFile($file, $folder)
51
    {
52
        return copy($file, $folder);
53
    }
54
55
    /**
56
     * @param $src
57
     * @param $dst
58
     */
59
    public static function recurseCopy($src, $dst)
60
    {
61
        $dir = opendir($src);
62
        //        @mkdir($dst);
63 View Code Duplication
        if (!@mkdir($dst) && !is_dir($dst)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
64
            throw new \RuntimeException('The directory ' . $dst . ' could not be created.');
65
        }
66
        while (false !== ($file = readdir($dir))) {
67
            if (('.' !== $file) && ('..' !== $file)) {
68
                if (is_dir($src . '/' . $file)) {
69
                    self::recurseCopy($src . '/' . $file, $dst . '/' . $file);
70
                } else {
71
                    copy($src . '/' . $file, $dst . '/' . $file);
72
                }
73
            }
74
        }
75
        closedir($dir);
76
    }
77
78
    /**
79
     * Copy a file, or recursively copy a folder and its contents
80
     * @author      Aidan Lister <[email protected]>
81
     * @version     1.0.1
82
     * @link        http://aidanlister.com/2004/04/recursively-copying-directories-in-php/
83
     * @param       string $source Source path
84
     * @param       string $dest   Destination path
85
     * @return      bool     Returns true on success, false on failure
86
     */
87
    public static function xcopy($source, $dest)
88
    {
89
        // Check for symlinks
90
        if (is_link($source)) {
91
            return symlink(readlink($source), $dest);
92
        }
93
94
        // Simple copy for a file
95
        if (is_file($source)) {
96
            return copy($source, $dest);
97
        }
98
99
        // Make destination directory
100 View Code Duplication
        if (!is_dir($dest)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
101
            if (!mkdir($dest) && !is_dir($dest)) {
102
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $dest));
103
            }
104
        }
105
106
        // Loop through the folder
107
        $dir = dir($source);
108
        if (@is_dir($dir)) {
109
            while (false !== $entry = $dir->read()) {
110
                // Skip pointers
111
                if ('.' === $entry || '..' === $entry) {
112
                    continue;
113
                }
114
                // Deep copy directories
115
                self::xcopy("$source/$entry", "$dest/$entry");
116
            }
117
            // Clean up
118
            $dir->close();
119
        }
120
121
        return true;
122
    }
123
124
    /**
125
     * Remove files and (sub)directories
126
     *
127
     * @param string $src source directory to delete
128
     *
129
     * @uses \Xmf\Module\Helper::getHelper()
130
     * @uses \Xmf\Module\Helper::isUserAdmin()
131
     *
132
     * @return bool true on success
133
     */
134
    public static function deleteDirectory($src)
135
    {
136
        // Only continue if user is a 'global' Admin
137
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
0 ignored issues
show
Bug introduced by
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
138
            return false;
139
        }
140
141
        $success = true;
142
        // remove old files
143
        $dirInfo = new \SplFileInfo($src);
144
        // validate is a directory
145
        if ($dirInfo->isDir()) {
146
            $fileList = array_diff(scandir($src, SCANDIR_SORT_NONE), ['..', '.']);
147
            foreach ($fileList as $k => $v) {
148
                $fileInfo = new \SplFileInfo("{$src}/{$v}");
149
                if ($fileInfo->isDir()) {
150
                    // recursively handle subdirectories
151
                    if (!$success = self::deleteDirectory($fileInfo->getRealPath())) {
152
                        break;
153
                    }
154
                } else {
155
                    // delete the file
156
                    if (!($success = @unlink($fileInfo->getRealPath()))) {
157
                        break;
158
                    }
159
                }
160
            }
161
            // now delete this (sub)directory if all the files are gone
162
            if ($success) {
163
                $success = rmdir($dirInfo->getRealPath());
164
            }
165
        } else {
166
            // input is not a valid directory
167
            $success = false;
168
        }
169
170
        return $success;
171
    }
172
173
    /**
174
     * Recursively remove directory
175
     *
176
     * @todo currently won't remove directories with hidden files, should it?
177
     *
178
     * @param string $src directory to remove (delete)
179
     *
180
     * @return bool true on success
181
     */
182
    public static function rrmdir($src)
183
    {
184
        // Only continue if user is a 'global' Admin
185
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
0 ignored issues
show
Bug introduced by
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
186
            return false;
187
        }
188
189
        // If source is not a directory stop processing
190
        if (!is_dir($src)) {
191
            return false;
192
        }
193
194
        $success = true;
0 ignored issues
show
Unused Code introduced by
$success is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
195
196
        // Open the source directory to read in files
197
        $iterator = new \DirectoryIterator($src);
198
        foreach ($iterator as $fObj) {
199
            if ($fObj->isFile()) {
200
                $filename = $fObj->getPathname();
201
                $fObj     = null; // clear this iterator object to close the file
202
                if (!@unlink($filename)) {
203
                    return false; // couldn't delete the file
204
                }
205
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
206
                // Try recursively on directory
207
                self::rrmdir($fObj->getPathname());
208
            }
209
        }
210
        $iterator = null;   // clear iterator Obj to close file/directory
0 ignored issues
show
Unused Code introduced by
$iterator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
211
        return rmdir($src); // remove the directory & return results
212
    }
213
214
    /**
215
     * Recursively move files from one directory to another
216
     *
217
     * @param string $src  - Source of files being moved
218
     * @param string $dest - Destination of files being moved
219
     *
220
     * @return bool true on success
221
     */
222 View Code Duplication
    public static function rmove($src, $dest)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
223
    {
224
        // Only continue if user is a 'global' Admin
225
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
0 ignored issues
show
Bug introduced by
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
226
            return false;
227
        }
228
229
        // If source is not a directory stop processing
230
        if (!is_dir($src)) {
231
            return false;
232
        }
233
234
        // If the destination directory does not exist and could not be created stop processing
235
        if (!is_dir($dest) && !mkdir($dest) && !is_dir($dest)) {
236
            return false;
237
        }
238
239
        // Open the source directory to read in files
240
        $iterator = new \DirectoryIterator($src);
241
        foreach ($iterator as $fObj) {
242
            if ($fObj->isFile()) {
243
                rename($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
244
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
245
                // Try recursively on directory
246
                self::rmove($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
247
                //                rmdir($fObj->getPath()); // now delete the directory
248
            }
249
        }
250
        $iterator = null;   // clear iterator Obj to close file/directory
0 ignored issues
show
Unused Code introduced by
$iterator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
251
        return rmdir($src); // remove the directory & return results
252
    }
253
254
    /**
255
     * Recursively copy directories and files from one directory to another
256
     *
257
     * @param string $src  - Source of files being moved
258
     * @param string $dest - Destination of files being moved
259
     *
260
     * @uses \Xmf\Module\Helper::getHelper()
261
     * @uses \Xmf\Module\Helper::isUserAdmin()
262
     *
263
     * @return bool true on success
264
     */
265 View Code Duplication
    public static function rcopy($src, $dest)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
266
    {
267
        // Only continue if user is a 'global' Admin
268
        if (!($GLOBALS['xoopsUser'] instanceof \XoopsUser) || !$GLOBALS['xoopsUser']->isAdmin()) {
0 ignored issues
show
Bug introduced by
The class XoopsUser does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
269
            return false;
270
        }
271
272
        // If source is not a directory stop processing
273
        if (!is_dir($src)) {
274
            return false;
275
        }
276
277
        // If the destination directory does not exist and could not be created stop processing
278
        if (!is_dir($dest) && !mkdir($dest) && !is_dir($dest)) {
279
            return false;
280
        }
281
282
        // Open the source directory to read in files
283
        $iterator = new \DirectoryIterator($src);
284
        foreach ($iterator as $fObj) {
285
            if ($fObj->isFile()) {
286
                copy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
287
            } elseif (!$fObj->isDot() && $fObj->isDir()) {
288
                self::rcopy($fObj->getPathname(), "{$dest}/" . $fObj->getFilename());
289
            }
290
        }
291
292
        return true;
293
    }
294
}
295