I'm pulling results from a recursive directory listing into an array, and was wondering if there is a better (read faster, briefer, etc.) way of doing it. Specifically, I'm creating an array of:
path_relative_to_somedir => absolute_path
Right now I've got:
$map = array();
$base_realpath = realpath('/path/to/dir');
$iterator = new \RecursiveDirectoryIterator($base_realpath);
foreach((new \RecursiveIteratorIterator($iterator)) as $node){
$node_realpath = $node->getRealpath();
$map[substr($node_realpath, strlen($base_realpath) + 1)] = $node_realpath;
}
This works fine (seemingly) but I'm worried about edge cases that, while I'm sure they will come out in testing, others may be able to point out. So:
- Is there a better (read faster, more accurate, more reliable) way to get the node path relative to the
$base_realpath
? - Should I consider options such as
glob()
, orreaddir()
as faster alternatives? (this is a somewhat time sensitive operation, I saw a question pertaining to directory recursion in PHP with some benchmarks in an answer, will link when found)
--Question ends--
--Possibly unnecessary detail begins--
Purpose being; I'm creating a virtual working directory for an application, so that calls to a given file are mapped to the actual file. For example: (I'm elaborating in case someone has an overall better alternative approach based on what I'm actually doing)
Given dir1
is the "root" of the virtual working directory, and we wish to merge in dir2
:
path/ path/
| |
+-- to/ +-- to/
| |
+-- dir1/ +-- dir2/
| |
+-- script1.php +-- script2.php
| |
+-- script2.php +-- subdir/
| |
+-- subdir/ +-- script4.php
|
+-- script3.php
It would yield an array like so:
[script1.php] => path/to/dir1/script1.php
[script2.php] => path/to/dir2/script2.php
[subdir/script3.php] => path/to/dir1/subdir/script3.php
[subdir/script4.php] => path/to/dir2/subdir/script4.php
Notice that the merging replaces existing relative paths, and each element is mapped to it's actual path. I'm simply using array_replace()
here, here's the method snippet:
public function mergeModule($name){
$path = realpath($this->_application->getPath() . 'modules/' . $name);
if(!is_dir($path) || !is_readable($path)){
// @todo; throw exception
}
$map = array();
try{
$directory_iterator = new \RecursiveDirectoryIterator($path);
foreach((new \RecursiveIteratorIterator($directory_iterator)) as $node){
$node_realpath = $node->getRealpath();
$map[substr($node_realpath, strlen($path) + 1)] = $node_realpath;
}
}catch(\Exception $exception){
// @todo; handle
}
$this->_map = array_replace($this->_map, $map);
}