Last active
October 21, 2015 16:58
-
-
Save deathlyfrantic/086bba7b2a25ec8e57cc to your computer and use it in GitHub Desktop.
miscellaneous recursive file system functions for PHP that I shouldn't have to write myself
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class RecursiveUtils | |
{ | |
/** | |
* Return the entire contents of a directory as SplFileInfo objects including all subdirectories. | |
* @param string $path The path of the directory whose contents you want. | |
* @return array An array of the full paths of those contents. | |
*/ | |
public static function rscandir($path) | |
{ | |
$results = []; | |
try { | |
$iterator = new \RecursiveDirectoryIterator($path, \FilesystemIterator::SKIP_DOTS); | |
foreach($iterator as $i) { | |
$results[] = $i; | |
if($i->isDir()) { | |
$results = array_merge($results, static::rscandir($i->getRealPath())); | |
} | |
} | |
} catch(\UnexpectedValueException $e) { | |
// $results is an empty array so nothing to do here, we'll just return it as is. | |
} | |
return $results; | |
} | |
/** | |
* Equivalent to rm -rf $path. | |
* @param string $path Directory to remove. | |
* @param string $removeRoot If true, removes $path as well. If false, remove's the contents of $path | |
* but not $path itself. | |
* @return boolean True if successful, false if not. | |
*/ | |
public static function rrmdir($path, $removeRoot = true) | |
{ | |
$pathObjects = static::rscandir($path); | |
$success = true; | |
$contents = array_map( | |
function ($pathObject) { | |
return $pathObject->getRealPath(); | |
}, | |
array_reverse($pathObjects) | |
); | |
foreach($contents as $content) { | |
if(is_dir($content)) { | |
$success = rmdir($content) && $success; | |
} else { | |
$success = unlink($content) && $success; | |
} | |
} | |
if($removeRoot) { | |
$success = rmdir($path) && $success; | |
} | |
return $success; | |
} | |
/** | |
* Recursive glob. Equivalent of find $path -name $glob. | |
* @param string $glob The pattern to find. Should follow format of $pattern from glob(). | |
* @param string $path The root path. Defaults to current directory (.). | |
* @param int $globtions A bitmask of glob() option flags. | |
* @return array The results of the find. | |
*/ | |
public static function rglob($glob, $path = ".", $globtions = 0) | |
{ | |
$results = glob($path . DIRECTORY_SEPARATOR . $glob, $globtions); | |
$paths = static::rscandir($path); | |
$dirs = array_filter( | |
$paths, | |
function ($path) { | |
return $path->isDir(); | |
} | |
); | |
foreach($dirs as $dir) { | |
$results = array_merge($results, glob($dir . DIRECTORY_SEPARATOR . $glob, $globtions)); | |
} | |
return $results; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment