diff --git a/library/Icinga/Util/DirectoryIterator.php b/library/Icinga/Util/DirectoryIterator.php new file mode 100644 index 000000000..34bb937f2 --- /dev/null +++ b/library/Icinga/Util/DirectoryIterator.php @@ -0,0 +1,191 @@ +path = $path; + if (! empty($extension)) { + $this->extension = '.' . ltrim($extension, '.'); + } + } + + /** + * Check whether the given path is a directory and is readable + * + * @param string $path The path of the directory + * + * @return bool + */ + public static function isReadable($path) + { + return is_dir($path) && is_readable($path); + } + + /** + * {@inheritdoc} + */ + public function current() + { + return $this->current; + } + + /** + * {@inheritdoc} + */ + public function next() + { + do { + $file = readdir($this->handle); + if ($file === false) { + $key = false; + break; + } else { + $skip = false; + do { + if ($this->skipHidden && $file[0] === '.') { + $skip = true; + break; + } + + $path = $this->path . '/' . $file; + + if (is_dir($path)) { + $skip = true; + break; + } + + if ($this->skipEmpty && ! filesize($path)) { + $skip = true; + break; + } + + if ($this->extension && ! String::endsWith($file, $this->extension)) { + $skip = true; + break; + } + + $key = $file; + $file = $path; + } while (0); + } + } while ($skip); + + $this->current = $file; + /** @noinspection PhpUndefinedVariableInspection */ + $this->key = $key; + } + + /** + * {@inheritdoc} + */ + public function key() + { + return $this->key; + } + + /** + * {@inheritdoc} + */ + public function valid() + { + return $this->current !== false; + } + + /** + * {@inheritdoc} + */ + public function rewind() + { + if ($this->handle === null) { + $this->handle = opendir($this->path); + } else { + rewinddir($this->handle); + } + $this->next(); + } + + /** + * Close directory handle if created + */ + public function __destruct() + { + if ($this->handle !== null) { + closedir($this->handle); + } + } +}