SplFileInfo.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. /**
  19. * @param string $file The file name
  20. * @param string $relativePath The relative path
  21. * @param string $relativePathname The relative path name
  22. */
  23. public function __construct(
  24. string $file,
  25. private string $relativePath,
  26. private string $relativePathname,
  27. ) {
  28. parent::__construct($file);
  29. }
  30. /**
  31. * Returns the relative path.
  32. *
  33. * This path does not contain the file name.
  34. */
  35. public function getRelativePath(): string
  36. {
  37. return $this->relativePath;
  38. }
  39. /**
  40. * Returns the relative path name.
  41. *
  42. * This path contains the file name.
  43. */
  44. public function getRelativePathname(): string
  45. {
  46. return $this->relativePathname;
  47. }
  48. public function getFilenameWithoutExtension(): string
  49. {
  50. $filename = $this->getFilename();
  51. return pathinfo($filename, \PATHINFO_FILENAME);
  52. }
  53. /**
  54. * Returns the contents of the file.
  55. *
  56. * @throws \RuntimeException
  57. */
  58. public function getContents(): string
  59. {
  60. set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
  61. try {
  62. $content = file_get_contents($this->getPathname());
  63. } finally {
  64. restore_error_handler();
  65. }
  66. if (false === $content) {
  67. throw new \RuntimeException($error);
  68. }
  69. return $content;
  70. }
  71. }