FileReader.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4. * This file is part of PHP CS Fixer.
  5. *
  6. * (c) Fabien Potencier <fabien@symfony.com>
  7. * Dariusz Rumiński <dariusz.ruminski@gmail.com>
  8. *
  9. * This source file is subject to the MIT license that is bundled
  10. * with this source code in the file LICENSE.
  11. */
  12. namespace PhpCsFixer;
  13. /**
  14. * File reader that unify access to regular file and stdin-alike file.
  15. *
  16. * Regular file could be read multiple times with `file_get_contents`, but file provided on stdin cannot.
  17. * Consecutive try will provide empty content for stdin-alike file.
  18. * This reader unifies access to them.
  19. *
  20. * @internal
  21. */
  22. final class FileReader
  23. {
  24. private ?string $stdinContent = null;
  25. public static function createSingleton(): self
  26. {
  27. static $instance = null;
  28. if (!$instance) {
  29. $instance = new self();
  30. }
  31. return $instance;
  32. }
  33. public function read(string $filePath): string
  34. {
  35. if ('php://stdin' === $filePath) {
  36. if (null === $this->stdinContent) {
  37. $this->stdinContent = $this->readRaw($filePath);
  38. }
  39. return $this->stdinContent;
  40. }
  41. return $this->readRaw($filePath);
  42. }
  43. private function readRaw(string $realPath): string
  44. {
  45. $content = @file_get_contents($realPath);
  46. if (false === $content) {
  47. $error = error_get_last();
  48. throw new \RuntimeException(\sprintf(
  49. 'Failed to read content from "%s".%s',
  50. $realPath,
  51. null !== $error ? ' '.$error['message'] : ''
  52. ));
  53. }
  54. return $content;
  55. }
  56. }