<?php
namespace nur;

/**
 * Class shutils: des outils donnant le même confort que le shell
 */
class shutils {
  static function ls_all(string $dir, ?string $pattern=null, int $sorting_order=SCANDIR_SORT_ASCENDING): array {
    $all = scandir($dir, $sorting_order);
    if ($all === false) return [];
    return array_values(array_filter($all,
      function ($file) use ($pattern) {
        if ($file === "." || $file === "..") return false;
        return $pattern === null || fnmatch($pattern, $file);
      }
    ));
  }

  static function ls_dirs(string $dir, ?string $pattern=null, int $sorting_order=SCANDIR_SORT_ASCENDING): array {
    return array_values(array_filter(self::ls_all($dir, $pattern, $sorting_order),
      function ($file) use ($dir) {
        return path::is_dir(path::join($dir, $file));
      }
    ));
  }

  static function ls_files(string $dir, ?string $pattern=null, int $sorting_order=SCANDIR_SORT_ASCENDING): array {
    return array_values(array_filter(self::ls_all($dir, $pattern, $sorting_order),
      function ($file) use ($dir) {
        return path::is_file(path::join($dir, $file));
      }
    ));
  }

  static function ls_pall(string $dir, ?string $pattern=null, int $sorting_order=SCANDIR_SORT_ASCENDING): array {
    return array_map(function(string $name) use ($dir) {
      return path::join($dir, $name);
    }, self::ls_all($dir, $pattern, $sorting_order));
  }

  static function ls_pdirs(string $dir, ?string $pattern=null, int $sorting_order=SCANDIR_SORT_ASCENDING): array {
    return array_map(function(string $name) use ($dir) {
      return path::join($dir, $name);
    }, self::ls_dirs($dir, $pattern, $sorting_order));
  }

  static function ls_pfiles(string $dir, ?string $pattern=null, int $sorting_order=SCANDIR_SORT_ASCENDING): array {
    return array_map(function(string $name) use ($dir) {
      return path::join($dir, $name);
    }, self::ls_files($dir, $pattern, $sorting_order));
  }
}