1
0

StreamResponse.php 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCP\AppFramework\Http;
  8. use OCP\AppFramework\Http;
  9. /**
  10. * Class StreamResponse
  11. *
  12. * @since 8.1.0
  13. * @template S of int
  14. * @template H of array<string, mixed>
  15. * @template-extends Response<int, array<string, mixed>>
  16. */
  17. class StreamResponse extends Response implements ICallbackResponse {
  18. /** @var string */
  19. private $filePath;
  20. /**
  21. * @param string|resource $filePath the path to the file or a file handle which should be streamed
  22. * @param S $status
  23. * @param H $headers
  24. * @since 8.1.0
  25. */
  26. public function __construct(mixed $filePath, int $status = Http::STATUS_OK, array $headers = []) {
  27. parent::__construct($status, $headers);
  28. $this->filePath = $filePath;
  29. }
  30. /**
  31. * Streams the file using readfile
  32. *
  33. * @param IOutput $output a small wrapper that handles output
  34. * @since 8.1.0
  35. */
  36. public function callback(IOutput $output) {
  37. // handle caching
  38. if ($output->getHttpResponseCode() !== Http::STATUS_NOT_MODIFIED) {
  39. if (!(is_resource($this->filePath) || file_exists($this->filePath))) {
  40. $output->setHttpResponseCode(Http::STATUS_NOT_FOUND);
  41. } elseif ($output->setReadfile($this->filePath) === false) {
  42. $output->setHttpResponseCode(Http::STATUS_BAD_REQUEST);
  43. }
  44. }
  45. }
  46. }