StreamResponse.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * 重庆赤晓店信息科技有限公司
  4. * https://www.chixiaodian.com
  5. * Copyright (c) 2023 赤店商城 All rights reserved.
  6. */
  7. /*
  8. * This file is part of the overtrue/wechat.
  9. *
  10. * (c) overtrue <i@overtrue.me>
  11. *
  12. * This source file is subject to the MIT license that is bundled
  13. * with this source code in the file LICENSE.
  14. */
  15. namespace ByteDance\Kernel\Http;
  16. use ByteDance\Kernel\Exceptions\InvalidArgumentException;
  17. use ByteDance\Kernel\Exceptions\RuntimeException;
  18. use ByteDance\Kernel\Support\File;
  19. /**
  20. * Class StreamResponse.
  21. *
  22. * @author overtrue <i@overtrue.me>
  23. */
  24. class StreamResponse extends Response
  25. {
  26. /**
  27. * @param string $directory
  28. * @param string $filename
  29. * @param bool $appendSuffix
  30. *
  31. * @return bool|int
  32. *
  33. * @throws \ByteDance\Kernel\Exceptions\InvalidArgumentException
  34. * @throws \ByteDance\Kernel\Exceptions\RuntimeException
  35. */
  36. public function save(string $directory, string $filename = '', bool $appendSuffix = true)
  37. {
  38. $this->getBody()->rewind();
  39. $directory = rtrim($directory, '/');
  40. if (!is_dir($directory)) {
  41. mkdir($directory, 0755, true); // @codeCoverageIgnore
  42. }
  43. if (!is_writable($directory)) {
  44. throw new InvalidArgumentException(sprintf("'%s' is not writable.", $directory));
  45. }
  46. $contents = $this->getBody()->getContents();
  47. if (empty($contents) || '{' === $contents[0]) {
  48. throw new RuntimeException('Invalid media response content.');
  49. }
  50. if (empty($filename)) {
  51. if (preg_match('/filename="(?<filename>.*?)"/', $this->getHeaderLine('Content-Disposition'), $match)) {
  52. $filename = $match['filename'];
  53. } else {
  54. $filename = md5($contents);
  55. }
  56. }
  57. if ($appendSuffix && empty(pathinfo($filename, PATHINFO_EXTENSION))) {
  58. $filename .= File::getStreamExt($contents);
  59. }
  60. file_put_contents($directory.'/'.$filename, $contents);
  61. return $filename;
  62. }
  63. /**
  64. * @param string $directory
  65. * @param string $filename
  66. * @param bool $appendSuffix
  67. *
  68. * @return bool|int
  69. *
  70. * @throws \ByteDance\Kernel\Exceptions\InvalidArgumentException
  71. * @throws \ByteDance\Kernel\Exceptions\RuntimeException
  72. */
  73. public function saveAs(string $directory, string $filename, bool $appendSuffix = true)
  74. {
  75. return $this->save($directory, $filename, $appendSuffix);
  76. }
  77. }