File.php 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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\HttpFoundation\File;
  11. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  12. use Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException;
  13. use Symfony\Component\Mime\MimeTypes;
  14. /**
  15. * A file in the file system.
  16. *
  17. * @author Bernhard Schussek <bschussek@gmail.com>
  18. */
  19. class File extends \SplFileInfo
  20. {
  21. /**
  22. * Constructs a new file from the given path.
  23. *
  24. * @param string $path The path to the file
  25. * @param bool $checkPath Whether to check the path or not
  26. *
  27. * @throws FileNotFoundException If the given path is not a file
  28. */
  29. public function __construct(string $path, bool $checkPath = true)
  30. {
  31. if ($checkPath && !is_file($path)) {
  32. throw new FileNotFoundException($path);
  33. }
  34. parent::__construct($path);
  35. }
  36. /**
  37. * Returns the extension based on the mime type.
  38. *
  39. * If the mime type is unknown, returns null.
  40. *
  41. * This method uses the mime type as guessed by getMimeType()
  42. * to guess the file extension.
  43. *
  44. * @see MimeTypes
  45. * @see getMimeType()
  46. */
  47. public function guessExtension(): ?string
  48. {
  49. if (!class_exists(MimeTypes::class)) {
  50. throw new \LogicException('You cannot guess the extension as the Mime component is not installed. Try running "composer require symfony/mime".');
  51. }
  52. return MimeTypes::getDefault()->getExtensions($this->getMimeType())[0] ?? null;
  53. }
  54. /**
  55. * Returns the mime type of the file.
  56. *
  57. * The mime type is guessed using a MimeTypeGuesserInterface instance,
  58. * which uses finfo_file() then the "file" system binary,
  59. * depending on which of those are available.
  60. *
  61. * @see MimeTypes
  62. */
  63. public function getMimeType(): ?string
  64. {
  65. if (!class_exists(MimeTypes::class)) {
  66. throw new \LogicException('You cannot guess the mime type as the Mime component is not installed. Try running "composer require symfony/mime".');
  67. }
  68. return MimeTypes::getDefault()->guessMimeType($this->getPathname());
  69. }
  70. /**
  71. * Moves the file to a new location.
  72. *
  73. * @throws FileException if the target file could not be created
  74. */
  75. public function move(string $directory, ?string $name = null): self
  76. {
  77. $target = $this->getTargetFile($directory, $name);
  78. set_error_handler(function ($type, $msg) use (&$error) { $error = $msg; });
  79. try {
  80. $renamed = rename($this->getPathname(), $target);
  81. } finally {
  82. restore_error_handler();
  83. }
  84. if (!$renamed) {
  85. throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s).', $this->getPathname(), $target, strip_tags($error)));
  86. }
  87. @chmod($target, 0666 & ~umask());
  88. return $target;
  89. }
  90. public function getContent(): string
  91. {
  92. $content = file_get_contents($this->getPathname());
  93. if (false === $content) {
  94. throw new FileException(sprintf('Could not get the content of the file "%s".', $this->getPathname()));
  95. }
  96. return $content;
  97. }
  98. protected function getTargetFile(string $directory, ?string $name = null): self
  99. {
  100. if (!is_dir($directory)) {
  101. if (false === @mkdir($directory, 0777, true) && !is_dir($directory)) {
  102. throw new FileException(sprintf('Unable to create the "%s" directory.', $directory));
  103. }
  104. } elseif (!is_writable($directory)) {
  105. throw new FileException(sprintf('Unable to write in the "%s" directory.', $directory));
  106. }
  107. $target = rtrim($directory, '/\\').\DIRECTORY_SEPARATOR.(null === $name ? $this->getBasename() : $this->getName($name));
  108. return new self($target, false);
  109. }
  110. /**
  111. * Returns locale independent base name of the given path.
  112. */
  113. protected function getName(string $name): string
  114. {
  115. $originalName = str_replace('\\', '/', $name);
  116. $pos = strrpos($originalName, '/');
  117. $originalName = false === $pos ? $originalName : substr($originalName, $pos + 1);
  118. return $originalName;
  119. }
  120. }