Skip to content

Instantly share code, notes, and snippets.

@madeindjs
Created November 25, 2016 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save madeindjs/b4ecc55d4a8525353ec12054315e0944 to your computer and use it in GitHub Desktop.
Save madeindjs/b4ecc55d4a8525353ec12054315e0944 to your computer and use it in GitHub Desktop.
List all files in the given directory into a Json prompt (or an array if you want)
<?php
/**
* Represent a custom Directory class more easy to use for my need
*/
class DirectoryLister implements JsonSerializable{
private $path;
/**
* Instanciate a Directory with a path
* @param string $path
*/
function __construct(string $path){
//check before if the file exists
if(file_exists($path)){
$this->path = $path;
}else{
throw \Exception("File not exist: $path");
}
}
/**
* Return filenames containing in this directory
*/
function walk(){
// scan directory and
foreach( scandir($this->path) as $basename){
$new_path = $this->path.DIRECTORY_SEPARATOR.$basename ;
// TODO: add a regex test
if(!in_array($basename, ['.', '..']) && file_exists($new_path) ){
yield $new_path;
}
}
}
/**
* Convert this object into an array
* @return array
*/
function to_a(&$directories=null):array{
if(!$directories){
$directories = [];
}
foreach($this->walk() as $file){
// if it's a directory, we loop on it
if(is_dir($file)){
$sub_dir = new DirectoryLister($file);
$name = basename($file) ;
$directories[$name] = [$name => $sub_dir->to_a($directories[$name]) ] ;
// if it's a file
}else{
$name = basename($file) ;
array_push($directories, $name);
}
}
return $directories;
}
/**
* Overwritted unction to specify json_encode() output
* @return array
*/
function jsonSerialize(){
$array = $this->to_a();
return $array;
}
function get_basename():string{return basename($this->path);}
}
$dir = new DirectoryLister('C:\xampp\htdocs');
$json = json_encode($dir, JSON_PRETTY_PRINT);
echo $json ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment