Get the list of files or directories in a given path.

@param string $path
@param string $prefix
@param string $mode
@param bool $recursive
@param null $filter
@return array
@SuppressWarnings(PHPMD.CyclomaticComplexity)
553140
protected function _list($path, $prefix = '', $mode = 'file', $recursive = false, $filter = null)
    {
        $files  = [];
        $ignore = ['.', '..', '.DS_Store', '.svn', '.git', '.gitignore', '.gitmodules', 'cgi-bin'];

        if ($scan = @scandir($path)) {
            foreach ($scan as $file) {
                // continue if ignore match
                if (Arr::in($file, $ignore)) {
                    continue;
                }

                if (is_dir($path . '/' . $file)) {
                    // add dir
                    if ($mode === 'dir') {
                        // continue if no regex filter match
                        if ($filter && !preg_match($filter, $file)) {
                            continue;
                        }

                        $files[] = $prefix . $file;
                    }

                    // continue if not recursive
                    if (!$recursive) {
                        continue;
                    }

                    // read subdirectory
                    $files = array_merge(
                        $files,
                        $this->_list($path . '/' . $file, $prefix . $file . '/', $mode, $recursive, $filter)
                    );

                } else {
                    // add file
                    if ($mode === 'file') {
                        // continue if no regex filter match
                        if ($filter && !preg_match($filter, $file)) {
                            continue;
                        }

                        $files[] = $prefix.$file;
                    }
                }
            }
        }

        return $files;
    }
302985
public function listContents(bool $recursion = true): array {
		if (!$this->isDirectory()) {
			throw new DirectoryNotFoundException();
		}
		$a        = [];
		$dirs     = [];
		$contents = $this->manager->listContents($this->getUrl(), $recursion);

		foreach ($contents as $file) {
			$file = Paths::normalize("/" . $file["path"]);
			$add  = str_replace($this->getAbsolutePath(), "", $file);


			$dirs[] = new File(Paths::appendPath($this->getUrl(), $add));
		}
		foreach ($dirs as $dir) {
			$add = true;
			foreach ($this->filter as $i => $filter) {
				if (Utils::isClosure($filter)) {
					/**
					 * @var \Closure $filter
					 */
					$add = $add && call_user_func($filter, $dir);
				} else {
					/**
					 * @var Filter $filter
					 */
					$add = $add && $filter->filter($dir);
				}
			}
			if ($add) {
				$a[] = $dir;
			}
		}

		return $a;
	}
31232
public function listContents($directory = '', $recursive = false)
    {
        list($prefix, $directory) = $this->getPrefixAndPath($directory);
        $filesystem = $this->getFilesystem($prefix);
        $result = $filesystem->listContents($directory, $recursive);

        foreach ($result as &$file) {
            $file['filesystem'] = $prefix;
        }

        return $result;
    }
1209752
public function ls($resource, $mode = self::LS_MODE_FILE, $recursive = false, $filter = null)
    {
        $files = [];
        list (, $paths, $path) = $this->_parse($resource);

        foreach ((array) $paths as $_path) {
            if (file_exists($_path . '/' . $path)) {
                foreach ($this->_list(FS::clean($_path . '/' . $path), '', $mode, $recursive, $filter) as $file) {
                    if (!Arr::in($file, $files)) {
                        $files[] = $file;
                    }
                }
            }
        }

        return $files;
    }
1370590
public function listFolder(string $path, bool $recursive = false) : array
	{
		$path = $this->normalizePath($path);
			
		$requestUrl = $this->siteUrl.'/sites/'.$this->siteName.'/_api/Web/GetFolderByServerRelativeUrl(\''.$this->folderPath.$path.'\')/Folders';
		
		$options = [
			'headers' => $this->requestHeaders,
		];
			
		$response = $this->send('GET', $requestUrl, $options);
			
		$folders = json_decode($response->getBody())->d ?? ['results' => []];
			
		// Making sure we convert the object to an array
		if (!is_array($folders)) {
			$folders = json_decode(json_encode($folders), true);
		}
			
		return $folders['results'];
	}
823992
private function findClassInPath($path, $class, $prefix)
    {
        if (!$path = realpath($path.'/'.strtr($prefix, '\\_', '//')) ?: realpath($path.'/'.dirname(strtr($prefix, '\\_', '//'))) ?: realpath($path)) {
            return array();
        }

        $classes = array();
        $filename = $class.'.php';
        foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
            if ($filename == $file->getFileName() && $class = $this->convertFileToClass($path, $file->getPathName(), $prefix)) {
                $classes[] = $class;
            }
        }

        return $classes;
    }
1238473
public function listDirectory($path, $recursive = false, $withHidden = true)
    {
        if ($recursive) {
            return $this->listDirectoryRecursive($path);
        }

        $all = $withHidden ? glob($path.'/{,.}[!.,!..]*', GLOB_MARK | GLOB_BRACE) : glob("$path/*");

        $all = array_map(function ($path) {
            return rtrim($path, '/\\');
        }, $all);

        sort($all);

        return $all;
    }
561427
public function listContents($directory = '', $recursive = false)
    {
        $directory = $this->applyPathPrefix($directory);

        $objects = $this->bucket->objects(
            [
                'prefix' => $directory,
            ]
        );

        $contents = [];
        foreach ($objects as $apiObject) {
            if (null !== $apiObject) {
                $contents[] = $this->convertObjectInfo($apiObject);
            }
        }

        // if directory, skip the directory object
        // if directory, truncate prefix + delimiter
        if ('' !== $directory) {
            foreach ($contents as $idx => $objectInfo) {
                if ('dir' === $objectInfo['type'] && $objectInfo['path'] === $directory) {
                    $contents[$idx] = false;
                }
            }
        }

        return array_filter($contents);
    }
10540
public function listContents(string $directory = '', bool $recursive = false): array
    {
        $list = [];
        $location = $this->applyBasePath($directory);

        if (! is_dir($location)) {
            return $list;
        }

        $iterator = $recursive ?
                    $this->getRecursiveDirectoryIterator($location) :
                    $this->getDirectoryIterator($location);

        foreach ($iterator as $file) {
            $path = $this->getFilePath($file);

            if (preg_match('#(^|/|\\\\)\.{1,2}$#', $path)) {
                continue;
            }

            $list[] = $this->normalizeFileInfo($file);

            unset($path);
        }

        unset($location, $iterator);

        return array_filter($list);
    }
955985
protected function listDirectoryContents($directory, $recursive = true)
    {
        $result = [];
        $connection = $this->getConnection();
        $location = $this->prefix($directory);
        $listing = $connection->rawlist($location);

        if ($listing === false) {
            return [];
        }

        foreach ($listing as $filename => $object) {
            if (in_array($filename, ['.', '..'])) {
                continue;
            }

            $path = empty($directory) ? $filename : ($directory.'/'.$filename);
            $result[] = $this->normalizeListingObject($path, $object);

            if ($recursive && isset($object['type']) && $object['type'] === NET_SFTP_TYPE_DIRECTORY) {
                $result = array_merge($result, $this->listDirectoryContents($path));
            }
        }

        return $result;
    }
327749
public static function dirs($path, $recursive = false, $toArray = false, $pathType = self::PATH_ABSOLUTE)
	{
		/**
		 * Files callback
		 *
		 * @param \SplFileInfo                $current  Current item's value
		 * @param string                      $key      Current item's key
		 * @param \RecursiveDirectoryIterator $iterator Iterator being filtered
		 *
		 * @return boolean   TRUE to accept the current item, FALSE otherwise
		 */
		$callback = function ($current, $key, $iterator) use ($path, $recursive)
		{
			if ($recursive)
			{
				// Ignore self
				if ($iterator->getRealPath() == static::cleanPath($path))
				{
					return false;
				}

				// If set to recursive, every returned folder name will include a dot (.),
				// so we can't using isDot() to detect folder.
				return $iterator->isDir() && ($iterator->getBasename() != '..');
			}
			else
			{
				return $iterator->isDir() && !$iterator->isDot();
			}
		};

		$files = static::findByCallback($path, $callback, $recursive);
		
		if ($toArray) {
		    $files = static::toArray($files, $pathType);
		}
	    
	    return $files;
	}
1355161
public static function files($path, $recursive = false, $pathType = self::PATH_ABSOLUTE)
    {
        $files = [];

        /** @var $file \SplFileInfo */
        foreach (Filesystem::files($path, $recursive) as $file) {
            switch ($pathType) {
                case ($pathType === self::PATH_BASENAME):
                    $name = $file->getBasename();
                    break;

                case ($pathType === static::PATH_RELATIVE):
                    $pathLength = strlen($path);
                    $name = $file->getRealPath();
                    $name = trim(substr($name, $pathLength), DIRECTORY_SEPARATOR);
                    break;

                case ($pathType === static::PATH_ABSOLUTE):
                default:
                    $name = $file->getPathname();
                    break;
            }

            $files[] = $name;
        }

        return $files;
    }
927374
protected function get_files( $path ) {
		$filtered_files = array();
		try {
			$files = new RecursiveIteratorIterator(
				new RecursiveDirectoryIterator(
					$path,
					RecursiveDirectoryIterator::SKIP_DOTS
				),
				RecursiveIteratorIterator::CHILD_FIRST
			);
			foreach ( $files as $file_info ) {
				$pathname = self::normalize_directory_separators( substr( $file_info->getPathname(), strlen( $path ) ) );
				if ( $file_info->isFile() && $this->filter_file( $pathname ) ) {
					$filtered_files[] = $pathname;
				}
			}
		} catch ( Exception $e ) {
			WP_CLI::error( $e->getMessage() );
		}

		return $filtered_files;
	}
1059645
private function scanFolders(string $dir, bool $recursive): array
    {
        $files = [];

        // $dir comes from the database. The actual folder may not exist.
        if (is_dir($dir)) {
            foreach (scandir($dir, SCANDIR_SORT_NONE) as $path) {
                if (is_dir($dir . $path)) {
                    // What if there are user-defined subfolders “thumbs” or “watermarks”?
                    if ($path !== '.' && $path !== '..' && $path !== 'thumbs' && $path !== 'watermark' && $recursive) {
                        foreach ($this->scanFolders($dir . $path . '/', $recursive) as $subpath) {
                            $files[] = $path . '/' . $subpath;
                        }
                    }
                } else {
                    $files[] = $path;
                }
            }
        }

        return $files;
    }
695795
protected function searchFiles(array $directories, $filter = null)
    {
        $finder = new Finder();
        $finder->files()
            ->name('*.php')
            ->in($directories)
            ->depth($this->depth);

        if (isset($filter) && is_callable($filter)) {
            $finder->filter($filter);
        }

        return $finder;
    }
189812
public function listPaths(string $path = '', bool $recursive = false)
    {
        $result = [];
        $contents = $this->listContents($path, $recursive);

        foreach ($contents as $object) {
            $result[] = $object['path'];
        }

        return $result;
    }
826394
protected function findFilesAsSplFileInfo(string $regex, string $path) {
		
		$objects = new RecursiveIteratorIterator(
			new RecursiveDirectoryIterator($path), 
			RecursiveIteratorIterator::SELF_FIRST
		);
		
		$filter = new RegexIterator($objects, $regex);
		$map = [];
		
		foreach ($filter as $entry) {
			$map[] = $entry;
		}
		
		return count($map) > 0 ? $map : [];
	}