| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <?php
- declare(strict_types=1);
- namespace App\Service\Utils;
- use RuntimeException;
- use Symfony\Component\Config\FileLocator;
- /**
- * 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;
- }
- /**
- * Locate a file in the given directories and return its absolute path
- *
- * @param array<string> $directories
- * @param string $filename
- * @return string
- */
- public static function locate(array $directories, string $filename): string {
- $fileLocator = new FileLocator($directories);
- return $fileLocator->locate($filename, null, false)[0];
- }
- }
|