StreamResponse.php 2.4 KB

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