Files.php

<?php

namespace Lia\Utility;

/**
 * Utility class to work with files & directories
 * @todo move to my util repo & depend upon this class.
 */
class Files {

    /**
     * Get all files in a directory. Does not return directories
     *
     * @param $dir the directory to search in
     * @param $fPathsRelTo To get relative paths, this is removed from the beginning of each file path returned
     * @param $endingWith only get files that end with the given string, like `.php` or `.md`, etc
     * @return array of files
     */
    static public function all($dir,$fPathsRelTo='', $endingWith=''){
        if (!is_dir($dir))return [];
        $dir = str_replace(['///','//'],'/','/'.$dir.'/');
        $fPathsRelTo = $fPathsRelTo ? str_replace(['///','//'],'/','/'.$fPathsRelTo.'/') : null;
        $dh = opendir($dir);
        $allFiles = [];
        while ($file=readdir($dh)){
            if ($file=='.'||$file=='..')continue;
            if (is_dir($dir.$file)){
                $subFiles = self::all($dir.'/'.$file,$fPathsRelTo,$endingWith);
                $allFiles = array_merge($allFiles,$subFiles);
                continue;
            }
            $path = str_replace(['///','//'],'/',$dir.'/'.$file);
            if ($fPathsRelTo!==null){
                $path = '/'.substr($path,strlen($fPathsRelTo));
            }
            if ($endingWith!=''
                &&substr($path,-strlen($endingWith))!=$endingWith)continue;
            $allFiles[] = $path;
        }
        return $allFiles;
    }
}