From 076784f2c9d9de6f57da95bff1f6e9a086bd5504 Mon Sep 17 00:00:00 2001 From: Eric Lippmann Date: Tue, 24 Nov 2015 15:54:16 +0100 Subject: [PATCH] lib: Add util DirectoryIterator refs #10705 --- library/Icinga/Util/DirectoryIterator.php | 191 ++++++++++++++++++++++ 1 file changed, 191 insertions(+) create mode 100644 library/Icinga/Util/DirectoryIterator.php 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); + } + } +}