Skip to content

Instantly share code, notes, and snippets.

@bobmagicii
Forked from jakefolio/gist:3411185
Created August 21, 2012 03:33
Show Gist options
  • Save bobmagicii/3411283 to your computer and use it in GitHub Desktop.
Save bobmagicii/3411283 to your computer and use it in GitHub Desktop.
<?php
class AncientFileFilter extends \FilterIterator {
protected $DaysOld = 7;
public function __construct($dir,$days=null) {
// is the specified directory valid?
if(!is_string($dir) || !is_dir($dir) || !is_readable($dir))
throw new Exception("This '{$dir}' is not valid or readable.");
// construct with an inner filesystem iterator.
parent::__construct(new \FilesystemIterator($dir));
// how old is old in this day of age?
if(is_int($days) || is_float($days))
$this->DaysOld = $days;
return;
}
public function accept() {
$file = $this->current();
// list the file as ancient if it has been stale for more than
// x days.
if($file->getMTime() <= (time()-(86400*$this->DaysOld)))
return true;
// else do not list the file.
else return false;
}
}
// delete files more than 30 days stale.
$diter = new AncientFileFilter('.', 30);
// iterator_apply($diter, 'unlink', $diter->current()->getPathname());
// getpathname on non-object. that makes sense since at this point no iterations
// have actually happened for current to be pointing to a valid object.
// theory crafting: assuming rewind() fixed the no object for current, at this
// point we have assigned a reference to the first fileobject object returned
// so each iteration it would actually try to unlink the same file over and
// over, yes? each iteration being a new fileinfo object for the next file in
// line while this callback held open a reference to the first one during the
// original assignment.
// this based on the php manual for iterator_apply.
iterator_apply(
$diter,
function($i){ echo $i->current()->getFilename(), PHP_EOL; },
array($diter)
);
// but at this point i think there are probably lulz and flamewars to be had
// over what people think is good.
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment