Http.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\File\Transfer\Adapter;
  7. class Http
  8. {
  9. /**
  10. * @var \Magento\Framework\HTTP\PhpEnvironment\Response
  11. */
  12. private $response;
  13. /**
  14. * @var \Magento\Framework\File\Mime
  15. */
  16. private $mime;
  17. /**
  18. * @param \Magento\Framework\App\Response\Http $response
  19. * @param \Magento\Framework\File\Mime $mime
  20. */
  21. public function __construct(
  22. \Magento\Framework\HTTP\PhpEnvironment\Response $response,
  23. \Magento\Framework\File\Mime $mime
  24. ) {
  25. $this->response = $response;
  26. $this->mime = $mime;
  27. }
  28. /**
  29. * Send the file to the client (Download)
  30. *
  31. * @param string|array $options Options for the file(s) to send
  32. * @throws \UnexpectedValueException
  33. * @throws \InvalidArgumentException
  34. * @return void
  35. */
  36. public function send($options = null)
  37. {
  38. $filepath = $this->getFilePath($options);
  39. if (!is_file($filepath) || !is_readable($filepath)) {
  40. throw new \InvalidArgumentException("File '{$filepath}' does not exists.");
  41. }
  42. $mimeType = $this->mime->getMimeType($filepath);
  43. if (is_array($options) && isset($options['headers']) && $options['headers'] instanceof \Zend\Http\Headers) {
  44. $this->response->setHeaders($options['headers']);
  45. }
  46. $this->response->setHeader('Content-length', filesize($filepath));
  47. $this->response->setHeader('Content-Type', $mimeType);
  48. $this->response->sendHeaders();
  49. $handle = fopen($filepath, 'r');
  50. if ($handle) {
  51. while (($buffer = fgets($handle, 4096)) !== false) {
  52. echo $buffer;
  53. }
  54. if (!feof($handle)) {
  55. throw new \UnexpectedValueException("Unexpected end of file");
  56. }
  57. fclose($handle);
  58. }
  59. }
  60. /**
  61. * Get filepath by provided parameter $optons.
  62. * If the $options is a string it assumes it's a file path. If the option is an array method will look for the
  63. * 'filepath' key and return it's value.
  64. *
  65. * @param string|array|null $options
  66. * @return string
  67. * @throws \InvalidArgumentException
  68. */
  69. private function getFilePath($options): string
  70. {
  71. if (is_string($options)) {
  72. $filePath = $options;
  73. } elseif (is_array($options) && isset($options['filepath'])) {
  74. $filePath = $options['filepath'];
  75. } else {
  76. throw new \InvalidArgumentException("Filename is not set.");
  77. }
  78. return $filePath;
  79. }
  80. }