From f7175bc195b1895fca908d99033c4d68f076d87c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrgen=20Steitz?= Date: Sat, 18 Feb 2017 10:38:55 +0100 Subject: [PATCH] Filter invalid file types and use default list as fallback --- src/Indexer.php | 2 +- src/Options.php | 60 ++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 50 insertions(+), 12 deletions(-) diff --git a/src/Indexer.php b/src/Indexer.php index 4cd85d3..c341dd2 100644 --- a/src/Indexer.php +++ b/src/Indexer.php @@ -112,7 +112,7 @@ class Indexer public function index(): Promise { return coroutine(function () { - $fileTypes = implode(',', $this->options->fileTypes); + $fileTypes = implode(',', $this->options->getFileTypes()); $pattern = Path::makeAbsolute('**/*{' . $fileTypes . '}', $this->rootPath); $uris = yield $this->filesFinder->find($pattern); diff --git a/src/Options.php b/src/Options.php index 3a4842e..d7e7884 100644 --- a/src/Options.php +++ b/src/Options.php @@ -9,29 +9,67 @@ class Options * * @var array */ - public $fileTypes = [".php"]; + private $fileTypes = [".php"]; /** - * @param \stdClass|null $options + * @param \Traversable|\stdClass|array|null $options */ - public function __construct(\stdClass $options = null) + public function __construct($options = null) { // Do nothing when the $options parameter is not an object - if (!is_object($options)) { + if (!is_object($options) && !is_array($options) && (!$options instanceof \Traversable)) { return; } - $this->fileTypes = $options->fileTypes ?? $this->normalizeFileTypes($this->fileTypes); + foreach ($options as $option => $value) { + $method = 'set' . ucfirst($option); + + call_user_func([$this, $method], $value); + } } - private function normalizeFileTypes(array $fileTypes): array + /** + * Validate and set options for file types + * + * @param array $fileTypes List of file types + */ + public function setFileTypes(array $fileTypes) { - return array_map(function (string $fileType) { - if (substr($fileType, 0, 1) !== '.') { - $fileType = '.' . $fileType; - } + $fileTypes = filter_var_array($fileTypes, FILTER_SANITIZE_STRING); + $fileTypes = filter_var($fileTypes, FILTER_CALLBACK, ['options' => [$this, 'filterFileTypes']]); + $fileTypes = array_filter($fileTypes); + $this->fileTypes = !empty($fileTypes) ? $fileTypes : $this->fileTypes; + } + + /** + * Get list of registered file types + * + * @return array + */ + public function getFileTypes(): array + { + return $this->fileTypes; + } + + /** + * Filter valid file type + * + * @param string $fileType The file type to filter + * @return string|bool If valid it returns the file type, otherwise false + */ + private function filterFileTypes(string $fileType) + { + $fileType = trim($fileType); + + if (empty($fileType)) { return $fileType; - }, $fileTypes); + } + + if (substr($fileType, 0, 1) !== '.') { + return false; + } + + return $fileType; } }