Skip to content

Commit

Permalink
Merge pull request aws#656 from aws/s3-streamwrapper-size
Browse files Browse the repository at this point in the history
Determining object size correctly
  • Loading branch information
mtdowling committed Jun 25, 2015
2 parents d17abb8 + 63c4e97 commit a00fe9b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
18 changes: 17 additions & 1 deletion src/S3/StreamWrapper.php
Expand Up @@ -67,6 +67,9 @@ class StreamWrapper
/** @var StreamInterface Underlying stream resource */
private $body;

/** @var int Size of the body that is opened */
private $size;

/** @var array Hash of opened stream parameters */
private $params = [];

Expand Down Expand Up @@ -209,7 +212,7 @@ public function unlink($path)
public function stream_stat()
{
$stat = $this->getStatTemplate();
$stat[7] = $stat['size'] = (int) $this->body->getSize();
$stat[7] = $stat['size'] = $this->getSize();
$stat[2] = $stat['mode'] = $this->mode;

return $stat;
Expand Down Expand Up @@ -647,6 +650,7 @@ private function openReadStream()
$command = $client->getCommand('GetObject', $this->getOptions(true));
$command['@http']['stream'] = true;
$result = $client->execute($command);
$this->size = $result['ContentLength'];
$this->body = $result['Body'];

// Wrap the body in a caching entity body if seeking is allowed
Expand Down Expand Up @@ -898,4 +902,16 @@ private function clearCacheKey($key)
clearstatcache(true, $key);
$this->getCacheStorage()->remove($key);
}

/**
* Returns the size of the opened object body.
*
* @return int|null
*/
private function getSize()
{
$size = $this->body->getSize();

return $size !== null ? $size : $this->size;
}
}
15 changes: 15 additions & 0 deletions tests/S3/StreamWrapperTest.php
Expand Up @@ -818,4 +818,19 @@ public function testCachesReaddirs()
$this->assertEquals(2, filesize('s3://bucket/key/' . $file2));
closedir($r);
}

public function testReturnsStreamSizeFromHeaders()
{
$stream = Psr7\stream_for('12345');
$stream = Psr7\FnStream::decorate($stream, [
'getSize' => function () { return null; }
]);
$result = [
'Body' => $stream,
'ContentLength' => 5
];
$this->addMockResults($this->client, [$result]);
$resource = fopen('s3://foo/bar', 'r');
$this->assertEquals(5, fstat($resource)['size']);
}
}

0 comments on commit a00fe9b

Please sign in to comment.