Skip to content

Commit

Permalink
Merge pull request #12 from ElGigi/reuse-stream
Browse files Browse the repository at this point in the history
Reuse stream of HTTP request instead of create new stream
  • Loading branch information
RoyVoetman authored Dec 16, 2020
2 parents c3c3656 + a857cea commit f57138c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 10 deletions.
16 changes: 16 additions & 0 deletions src/Client.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Psr7\Response;
use InvalidArgumentException;
use Psr\Http\Message\StreamInterface;

/**
* Class GitlabAdapter
Expand Down Expand Up @@ -80,6 +81,21 @@ public function read($path)

return $this->responseContents($response);
}

/**
* @param $path
*
* @return resource|null
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function readStream($path)
{
$path = urlencode($path);

$response = $this->request('GET', "files/$path/raw");

return $response->getBody()->detach();
}

/**
* @param $path
Expand Down
16 changes: 7 additions & 9 deletions src/GitlabAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,17 +147,15 @@ public function read(string $path): string
*/
public function readStream(string $path)
{
if (false === ($fp = fopen('php://memory', 'r+'))) {
throw UnableToReadFile::fromLocation($path, 'Unable to open memory stream');
}
try {
if (null === ($resource = $this->client->readStream($this->prefixer->prefixPath($path)))) {
throw UnableToReadFile::fromLocation($path, 'Empty content');
}

if (false === fwrite($fp, $this->read($path))) {
throw UnableToReadFile::fromLocation($path, 'Unable to write stream');
return $resource;
} catch (Throwable $e) {
throw UnableToReadFile::fromLocation($path, $e->getMessage(), $e);
}

fseek($fp, 0);

return $fp;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion tests/GitlabAdapterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public function it_can_read_a_file_into_a_stream()
$stream = $this->gitlabAdapter->readStream('README.md');

$this->assertIsResource($stream);
$this->assertEquals(stream_get_contents($stream, null, 0), $this->gitlabAdapter->read('README.md'));
$this->assertEquals(stream_get_contents($stream, -1, 0), $this->gitlabAdapter->read('README.md'));
}

/**
Expand Down

0 comments on commit f57138c

Please sign in to comment.