<?php

declare(strict_types=1);

namespace App\Service\Utils;

use Path\Path;

/**
 * Various methods to manipulate file paths.
 */
class PathUtils
{
    /**
     * Returns the application directory.
     */
    public static function getProjectDir(): string
    {
        return (string) (new Path(__FILE__))->parent(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']       >  '/def'
     * ['/abc','def']       >  '/abc/def'
     * ['','foo.jpg']       >  'foo.jpg'
     * ['dir','0','a.jpg']  >  'dir/0/a.jpg'
     *
     * @param string ...$paths
     */
    public static function join(string|int ...$paths): string
    {
        // Cast args to string
        $paths = array_map('strval', $paths);

        $basePath = array_shift($paths);

        return (string) (new Path($basePath))->append(...$paths);
    }
}
