SplFileInfo.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Finder;
  11. /**
  12. * Extends \SplFileInfo to support relative paths.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class SplFileInfo extends \SplFileInfo
  17. {
  18. private string $relativePath;
  19. private string $relativePathname;
  20. /**
  21. * @param string $file The file name
  22. * @param string $relativePath The relative path
  23. * @param string $relativePathname The relative path name
  24. */
  25. public function __construct(string $file, string $relativePath, string $relativePathname)
  26. {
  27. parent::__construct($file);
  28. $this->relativePath = $relativePath;
  29. $this->relativePathname = $relativePathname;
  30. }
  31. /**
  32. * Returns the relative path.
  33. *
  34. * This path does not contain the file name.
  35. */
  36. public function getRelativePath(): string
  37. {
  38. return $this->relativePath;
  39. }
  40. /**
  41. * Returns the relative path name.
  42. *
  43. * This path contains the file name.
  44. */
  45. public function getRelativePathname(): string
  46. {
  47. return $this->relativePathname;
  48. }
  49. public function getFilenameWithoutExtension(): string
  50. {
  51. $filename = $this->getFilename();
  52. return pathinfo($filename, \PATHINFO_FILENAME);
  53. }
  54. /**
  55. * Returns the contents of the file.
  56. *
  57. * @throws \RuntimeException
  58. */
  59. public function getContents(): string
  60. {
  61. set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
  62. try {
  63. $content = file_get_contents($this->getPathname());
  64. } finally {
  65. restore_error_handler();
  66. }
  67. if (false === $content) {
  68. throw new \RuntimeException($error);
  69. }
  70. return $content;
  71. }
  72. }