Skip to content

Commit

Permalink
Fixes memory exhaustion when downloading big files
Browse files Browse the repository at this point in the history
Makes parsing the body of a response (as JSON) a lazy operation, rather
than eager. Parsing the body causes the entire response to be loaded
into memory at once, which can lead to memory exhaustion when attempted
on very large responses (e.g., the binary contents of a very large
file).

Fixes #18
  • Loading branch information
louismrose committed Apr 22, 2024
1 parent b508ab3 commit 7d8e0b4
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions lib/ApiResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,22 +14,36 @@ class ApiResponse
private $body;
private $code;
private $headers;
private $parsedBody;

public function __construct($body, $code, $headers)
{
$this->body = json_decode($body, true);
$this->body = $body;
$this->code = $code;
$this->headers = $headers;
}

/**
* Get the body of the response. Returns an array if the body is valid JSON.
*
* Note that this method will attempt to convert the entire request body to a string in memory. Callers must
* ensure that the content length of the response is not so large that it would cause memory exhaustion. Use
* getBodyRaw() to get the raw body without loading its entire contents into memory.
*
* @return array|null
*/
public function getBody()
{
return $this->body;
if (is_null($this->parsedBody)) {
$this->parsedBody = json_decode($this->body, true);
}

return $this->parsedBody;
}

public function getBodyRaw()
{
return json_encode($this->body);
return $this->body;
}

public function getCode()
Expand Down

0 comments on commit 7d8e0b4

Please sign in to comment.