-
-
Save AmyStephen/4677117 to your computer and use it in GitHub Desktop.
| <?php | |
| $this->path = BASE_FOLDER . '/x/y/z'; | |
| if (file_exists($this->path)) { | |
| $objects = new RecursiveIteratorIterator ( | |
| new RecursiveDirectoryIterator($this->path), | |
| RecursiveIteratorIterator::SELF_FIRST); | |
| $directories = array(); | |
| $i = 0; | |
| /** Recursive process of Folders */ | |
| foreach ($objects as $name => $object) { | |
| /** Remove files as found */ | |
| if (is_file($name)) { | |
| unlink($name); | |
| /** Hold folders until end */ | |
| } elseif (is_dir($name)) { | |
| $directories[$i++] = $name; | |
| } | |
| } | |
| /** Sort folders in reverse order and delete one at a time */ | |
| arsort($directories); | |
| foreach ($directories as $name) { | |
| rmdir($name); | |
| } | |
| /** Remove the seed path folder */ | |
| rmdir($this->path); | |
| } | |
| ?> |
Also, apparently (I've not written much php at all), arrays can be added to as
$directories[] = $name
which will add $name at the next highest index. So, if you initialize the array as
$directories = array(0 => $this->path)
then the added arrays found during the looping will just add at numerical index 1, 2, 3, 4, etc.
This eliminates the need for the $i index variable (never fun to have one of those floating around)
If I wrote this, also, I'd probably do a loop gathering up the files and directories into 2 lists, then loop over them to do the action.
I'm not a huge fan of mixing the discovery with the action, especially since the discovery phase (looping over $objects) has 2 possible outcomes: deleting a file or adding a directory to a list. By mixing the "discovery" and "action" phases, the code becomes a bit more difficult to change. For example, if you find a better way to do the recursive looping, you might have a harder time extracting it out. So, I'd probably do
foreach ($objects as $name => $object) {
if (is_file($name)) {
$files[] = $name;
} elseif (is_dir($name)) {
$directories[] = $name;
}
}
/** now loop over $files and unlink them **/
/** followed by looping over $directories and rmdir them **/There we go. Got github to let me fork it. Here are my thoughts in the actual script:
https://gist.github.com/4677586
Would it make sense to initialize $directories with $this -> path, so the directory removal loop will remove it. This will eliminate the need to have a separate, final rmdir