FileReader.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. /**
  25. * @var null|string
  26. */
  27. private $stdinContent;
  28. public static function createSingleton(): self
  29. {
  30. static $instance = null;
  31. if (!$instance) {
  32. $instance = new self();
  33. }
  34. return $instance;
  35. }
  36. public function read(string $filePath): string
  37. {
  38. if ('php://stdin' === $filePath) {
  39. if (null === $this->stdinContent) {
  40. $this->stdinContent = $this->readRaw($filePath);
  41. }
  42. return $this->stdinContent;
  43. }
  44. return $this->readRaw($filePath);
  45. }
  46. private function readRaw(string $realPath): string
  47. {
  48. $content = @file_get_contents($realPath);
  49. if (false === $content) {
  50. $error = error_get_last();
  51. throw new \RuntimeException(sprintf(
  52. 'Failed to read content from "%s".%s',
  53. $realPath,
  54. null !== $error ? ' '.$error['message'] : ''
  55. ));
  56. }
  57. return $content;
  58. }
  59. }