UploadedFile.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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\Bridge\PsrHttpMessage\Factory;
  11. use Psr\Http\Message\UploadedFileInterface;
  12. use Symfony\Component\HttpFoundation\File\Exception\FileException;
  13. use Symfony\Component\HttpFoundation\File\File;
  14. use Symfony\Component\HttpFoundation\File\UploadedFile as BaseUploadedFile;
  15. /**
  16. * @author Nicolas Grekas <p@tchwork.com>
  17. */
  18. class UploadedFile extends BaseUploadedFile
  19. {
  20. private $psrUploadedFile;
  21. private $test = false;
  22. public function __construct(UploadedFileInterface $psrUploadedFile, callable $getTemporaryPath)
  23. {
  24. $error = $psrUploadedFile->getError();
  25. $path = '';
  26. if (\UPLOAD_ERR_NO_FILE !== $error) {
  27. $path = $psrUploadedFile->getStream()->getMetadata('uri') ?? '';
  28. if ($this->test = !\is_string($path) || !is_uploaded_file($path)) {
  29. $path = $getTemporaryPath();
  30. $psrUploadedFile->moveTo($path);
  31. }
  32. }
  33. parent::__construct(
  34. $path,
  35. (string) $psrUploadedFile->getClientFilename(),
  36. $psrUploadedFile->getClientMediaType(),
  37. $psrUploadedFile->getError(),
  38. $this->test
  39. );
  40. $this->psrUploadedFile = $psrUploadedFile;
  41. }
  42. /**
  43. * {@inheritdoc}
  44. */
  45. public function move(string $directory, string $name = null): File
  46. {
  47. if (!$this->isValid() || $this->test) {
  48. return parent::move($directory, $name);
  49. }
  50. $target = $this->getTargetFile($directory, $name);
  51. try {
  52. $this->psrUploadedFile->moveTo((string) $target);
  53. } catch (\RuntimeException $e) {
  54. throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $target, $e->getMessage()), 0, $e);
  55. }
  56. @chmod($target, 0666 & ~umask());
  57. return $target;
  58. }
  59. }