|
7 | 7 | use Psr\Http\Message\RequestInterface; |
8 | 8 | use Psr\Http\Message\ResponseFactoryInterface; |
9 | 9 | use Psr\Http\Message\ResponseInterface; |
| 10 | +use Psr\Http\Message\StreamFactoryInterface; |
| 11 | +use Psr\Http\Message\StreamInterface; |
10 | 12 |
|
11 | 13 | /** |
12 | 14 | * Class to fetch html pages |
13 | 15 | */ |
14 | 16 | final class CurlDispatcher |
15 | 17 | { |
| 18 | + private static int $contentLengthThreshold = 5000000; |
| 19 | + |
16 | 20 | private RequestInterface $request; |
| 21 | + private StreamFactoryInterface $streamFactory; |
17 | 22 | private $curl; |
18 | 23 | private $result; |
19 | 24 | private array $headers = []; |
20 | 25 | private $isBinary = false; |
21 | | - private $body; |
| 26 | + private ?StreamInterface $body = null; |
22 | 27 | private ?int $error = null; |
23 | 28 | private array $settings; |
24 | 29 |
|
@@ -77,11 +82,12 @@ public static function fetch(array $settings, ResponseFactoryInterface $response |
77 | 82 | ); |
78 | 83 | } |
79 | 84 |
|
80 | | - private function __construct(array $settings, RequestInterface $request) |
| 85 | + private function __construct(array $settings, RequestInterface $request, StreamFactoryInterface $streamFactory = null) |
81 | 86 | { |
82 | 87 | $this->request = $request; |
83 | 88 | $this->curl = curl_init((string) $request->getUri()); |
84 | 89 | $this->settings = $settings; |
| 90 | + $this->streamFactory = $streamFactory ?? FactoryDiscovery::getStreamFactory(); |
85 | 91 |
|
86 | 92 | $cookies = $settings['cookies_path'] ?? str_replace('//', '/', sys_get_temp_dir().'/embed-cookies.txt'); |
87 | 93 |
|
@@ -136,7 +142,9 @@ private function exec(ResponseFactoryInterface $responseFactory): ResponseInterf |
136 | 142 |
|
137 | 143 | if ($this->body) { |
138 | 144 | //5Mb max |
139 | | - $response->getBody()->write(stream_get_contents($this->body, 5000000, 0)); |
| 145 | + $this->body->rewind(); |
| 146 | + $response = $response->withBody($this->body); |
| 147 | + $this->body = null; |
140 | 148 | } |
141 | 149 |
|
142 | 150 | return $response; |
@@ -199,9 +207,13 @@ private function writeBody($curl, $string): int |
199 | 207 | } |
200 | 208 |
|
201 | 209 | if (!$this->body) { |
202 | | - $this->body = fopen('php://temp', 'w+'); |
| 210 | + $this->body = $this->streamFactory->createStreamFromFile('php://temp', 'w+'); |
| 211 | + } |
| 212 | + |
| 213 | + if ($this->body->getSize() > self::$contentLengthThreshold) { |
| 214 | + return count($string); |
203 | 215 | } |
204 | 216 |
|
205 | | - return fwrite($this->body, $string); |
| 217 | + return $this->body->write($string); |
206 | 218 | } |
207 | 219 | } |
0 commit comments