Path.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Utils;
  4. use RuntimeException;
  5. use Symfony\Component\Config\FileLocator;
  6. /**
  7. * Various methods to manipulate file paths
  8. */
  9. class Path
  10. {
  11. /**
  12. * Returns the application directory
  13. *
  14. * @return string
  15. */
  16. public static function getProjectDir(): string
  17. {
  18. return dirname(__file__, 4);
  19. }
  20. /**
  21. * Properly join the $path and $tail as a new valid file's path
  22. * @see https://stackoverflow.com/a/15575293/4279120
  23. *
  24. * Ex:
  25. * Path.join('/var/www/', '/html/') > '/var/www/html'
  26. *
  27. * Input Result
  28. * ['',''] > ''
  29. * ['','/'] > '/'
  30. * ['/','a'] > '/a'
  31. * ['/','/a'] > '/a'
  32. * ['abc','def'] > 'abc/def'
  33. * ['abc','/def'] > 'abc/def'
  34. * ['/abc','def'] > '/abc/def'
  35. * ['','foo.jpg'] > 'foo.jpg'
  36. * ['dir','0','a.jpg'] > 'dir/0/a.jpg'
  37. *
  38. * @return string
  39. */
  40. public static function join(): string
  41. {
  42. $paths = array_filter(func_get_args(), static function ($s) { return $s !== ''; });
  43. return preg_replace('#/+#','/',implode('/', $paths));
  44. }
  45. /**
  46. * List the files located in the given directory
  47. *
  48. * @param string $path
  49. * @param string $glob
  50. * @return list<string>
  51. */
  52. public static function list(string $path, string $glob = '*'): array
  53. {
  54. return glob(self::join($path, $glob));
  55. }
  56. public static function read(string $path): string
  57. {
  58. $content = file_get_contents($path);
  59. if ($content === false) {
  60. throw new RuntimeException("File could not be read");
  61. }
  62. return $content;
  63. }
  64. /**
  65. * Locate a file in the given directories and return its absolute path
  66. *
  67. * @param array<string> $directories
  68. * @param string $filename
  69. * @return string
  70. */
  71. public static function locate(array $directories, string $filename): string {
  72. $fileLocator = new FileLocator($directories);
  73. return $fileLocator->locate($filename, null, false)[0];
  74. }
  75. }