File.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /**
  3. * This file is part of webman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace Webman;
  15. use SplFileInfo;
  16. use Webman\Exception\FileException;
  17. use function chmod;
  18. use function is_dir;
  19. use function mkdir;
  20. use function pathinfo;
  21. use function restore_error_handler;
  22. use function set_error_handler;
  23. use function sprintf;
  24. use function strip_tags;
  25. use function umask;
  26. class File extends SplFileInfo
  27. {
  28. /**
  29. * Move.
  30. * @param string $destination
  31. * @return File
  32. */
  33. public function move(string $destination): File
  34. {
  35. set_error_handler(function ($type, $msg) use (&$error) {
  36. $error = $msg;
  37. });
  38. $path = pathinfo($destination, PATHINFO_DIRNAME);
  39. if (!is_dir($path) && !mkdir($path, 0777, true)) {
  40. restore_error_handler();
  41. throw new FileException(sprintf('Unable to create the "%s" directory (%s)', $path, strip_tags($error)));
  42. }
  43. if (!rename($this->getPathname(), $destination)) {
  44. restore_error_handler();
  45. throw new FileException(sprintf('Could not move the file "%s" to "%s" (%s)', $this->getPathname(), $destination, strip_tags($error)));
  46. }
  47. restore_error_handler();
  48. @chmod($destination, 0666 & ~umask());
  49. return new self($destination);
  50. }
  51. }