StreamResponse.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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 App\Libs\TikTok\Kernel\Http;
  11. use App\Libs\TikTok\Kernel\Exceptions\InvalidArgumentException;
  12. use App\Libs\TikTok\Kernel\Exceptions\RuntimeException;
  13. use App\Libs\TikTok\Kernel\Support\File;
  14. /**
  15. * Class StreamResponse.
  16. *
  17. * @author overtrue <i@overtrue.me>
  18. */
  19. class StreamResponse extends Response {
  20. /**
  21. * @param string $directory
  22. * @param string $filename
  23. * @param bool $appendSuffix
  24. *
  25. * @return bool|int
  26. *
  27. * @throws InvalidArgumentException
  28. * @throws RuntimeException
  29. */
  30. public function save(string $directory, string $filename = '', bool $appendSuffix = true) {
  31. $this->getBody()->rewind();
  32. $directory = rtrim($directory, '/');
  33. if (!is_dir($directory) && !mkdir($directory, 0755, true) && !is_dir($directory)) {
  34. throw new RuntimeException(sprintf('Directory "%s" was not created', $directory));
  35. }
  36. if (!is_writable($directory)) {
  37. throw new InvalidArgumentException(sprintf("'%s' is not writable.", $directory));
  38. }
  39. $contents = $this->getBody()->getContents();
  40. if (empty($contents) || '{' === $contents[0]) {
  41. throw new RuntimeException('Invalid media response content.');
  42. }
  43. if (empty($filename)) {
  44. if (preg_match('/filename="(?<filename>.*?)"/', $this->getHeaderLine('Content-Disposition'), $match)) {
  45. $filename = $match['filename'];
  46. } else {
  47. $filename = md5($contents);
  48. }
  49. }
  50. if ($appendSuffix && empty(pathinfo($filename, PATHINFO_EXTENSION))) {
  51. $filename .= File::getStreamExt($contents);
  52. }
  53. file_put_contents($directory . '/' . $filename, $contents);
  54. return $filename;
  55. }
  56. /**
  57. * @param string $directory
  58. * @param string $filename
  59. * @param bool $appendSuffix
  60. *
  61. * @return bool|int
  62. *
  63. * @throws InvalidArgumentException
  64. * @throws RuntimeException
  65. */
  66. public function saveAs(string $directory, string $filename, bool $appendSuffix = true) {
  67. return $this->save($directory, $filename, $appendSuffix);
  68. }
  69. }