Skip to content

Instantly share code, notes, and snippets.

@mamchenkov
Forked from flangofas/FileFinder.php
Last active August 29, 2015 14:05
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 mamchenkov/1c3c34547dbbcfc7e5fd to your computer and use it in GitHub Desktop.
Save mamchenkov/1c3c34547dbbcfc7e5fd to your computer and use it in GitHub Desktop.
<?php
$obj = new FileFinder($argv[1]);
$obj->setFileType(array_slice($argv, 2));
$obj->setExcludingDirectories(array('test1'));
$pages = $obj->find();
print_r($pages);
class FileFinder {
private $directories;
private $type;
private $path;
public function __construct($path) {
if (empty($path)) {
throw new InvalidArgumentException("Must give a directory path");
}
if (!file_exists($path)) {
throw new InvalidArgumentException("Directory doesn't exist");
}
if (!is_dir($path)) {
throw new InvalidArgumentException("Must be a directory");
}
$this->path = $path;
}
public function setFileType(array $filter) {
$this->type = $filter;
}
public function setExcludingDirectories(array $directories) {
$this->directories = $directories;
}
public function getFileType() {
return (array)$this->type;
}
public function getExcludingDirectories() {
return (array)$this->directories;
}
public function find() {
$result = array();
$filters = $this->getFileType();
$directories = $this->getExcludingDirectories();
$it = new RecursiveDirectoryIterator($this->path, RecursiveDirectoryIterator::SKIP_DOTS);
$it = new FileFilter($it, $filters, $directories);
$it = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($it as $file) {
$id = md5($file->getRealPath());
$result[$id]['dirname'] = basename(dirname($file->getPathname()));
$result[$id]['fullpath'] = $file->getRealPath();
$result[$id]['mtime'] = $file->getMTime();
$result[$id]['extension'] = $file->getExtension();
}
return $result;
}
}
class FileFilter extends RecursiveFilterIterator {
private $filetypes;
private $excludedir;
public function __construct(RecursiveIterator $it, array $filtertypes = array(), array $directories = array()) {
parent::__construct($it);
$this->filetypes = $filtertypes;
$this->excludedir = $directories;
}
public function accept() {
$item = $this->current();
if ($item->isDir() && !in_array($item->getFilename(), $this->excludedir)) {
return true;
}
//No filetype filtering
if (empty($this->filetypes)) {
return true;
}
if ($item->isFile() && in_array($item->getExtension(), $this->filetypes)) {
return true;
}
return false;
}
public function getChildren() {
$children = parent::getChildren();
$children->filetypes = $this->filetypes;
$children->excludedir = $this->excludedir;
return $children;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment