<?php
declare(strict_types=1);

namespace App\Service\Utils;

use RuntimeException;

/**
 * Various methods to manipulate file paths
 */
class Path
{
    /**
     * Returns the application directory
     *
     * @return string
     */
    public static function getProjectDir(): string
    {
        return dirname(__file__, 4);
    }

    /**
     * Properly join the $path and $tail as a new valid file's path
     * @see https://stackoverflow.com/a/15575293/4279120
     *
     * Ex:
     *   Path.join('/var/www/', '/html/') > '/var/www/html'
     *
     * Input                   Result
     * ['','']              >  ''
     * ['','/']             >  '/'
     * ['/','a']            >  '/a'
     * ['/','/a']           >  '/a'
     * ['abc','def']        >  'abc/def'
     * ['abc','/def']       >  'abc/def'
     * ['/abc','def']       >  '/abc/def'
     * ['','foo.jpg']       >  'foo.jpg'
     * ['dir','0','a.jpg']  >  'dir/0/a.jpg'
     *
     * @return string
     */
    public static function join(): string
    {
        $paths = array_filter(func_get_args(), static function ($s) { return $s !== ''; });
        return preg_replace('#/+#','/',implode('/', $paths));
    }

    /**
     * List the files located in the given directory
     *
     * @param string $path
     * @param string $glob
     * @return list<string>
     */
    public static function list(string $path, string $glob = '*'): array
    {
        return glob(self::join($path, $glob));
    }

    public static function read(string $path): string
    {
        $content = file_get_contents($path);
        if ($content === false) {
            throw new RuntimeException("File could not be read");
        }
        return $content;
    }
}
