easier access to source metadata

This commit is contained in:
Robin Appelman 2022-06-09 15:41:06 +02:00
commit 6e347e48d4
2 changed files with 29 additions and 3 deletions

View file

@ -44,7 +44,7 @@ abstract class Wrapper extends WrapperHandler implements File, Directory {
public function stream_seek($offset, $whence = SEEK_SET) { public function stream_seek($offset, $whence = SEEK_SET) {
$result = fseek($this->source, $offset, $whence); $result = fseek($this->source, $offset, $whence);
return $result == 0 ? true : false; return $result == 0;
} }
public function stream_tell() { public function stream_tell() {
@ -94,8 +94,6 @@ abstract class Wrapper extends WrapperHandler implements File, Directory {
public function stream_close() { public function stream_close() {
if (is_resource($this->source)) { if (is_resource($this->source)) {
return fclose($this->source); return fclose($this->source);
} else {
return true;
} }
} }
@ -115,4 +113,19 @@ abstract class Wrapper extends WrapperHandler implements File, Directory {
public function getSource() { public function getSource() {
return $this->source; return $this->source;
} }
/**
* Retrieves header/metadata from the source stream.
*
* This is equivalent to calling `stream_get_meta_data` on the source stream except nested stream wrappers are handled transparently
*
* @return array
*/
public function getMetaData(): array {
$meta = stream_get_meta_data($this->source);
while (isset($meta['wrapper_data']) && $meta['wrapper_data'] instanceof Wrapper) {
$meta = $meta['wrapper_data']->getMetaData();
}
return $meta;
}
} }

View file

@ -7,6 +7,7 @@
namespace Icewind\Streams\Tests; namespace Icewind\Streams\Tests;
use Icewind\Streams\Wrapper;
use PHPUnit\Framework\TestCase; use PHPUnit\Framework\TestCase;
abstract class WrapperTest extends TestCase { abstract class WrapperTest extends TestCase {
@ -151,4 +152,16 @@ abstract class WrapperTest extends TestCase {
fclose($wrapped); fclose($wrapped);
$this->assertFalse(is_resource($source)); $this->assertFalse(is_resource($source));
} }
public function testGetMetaData() {
$source = fopen(__FILE__, 'r+');
$sourceMeta = stream_get_meta_data($source);
$wrapped = $this->wrapSource($source);
$wrappedMeta = stream_get_meta_data($wrapped);
$wrapper = $wrappedMeta['wrapper_data'];
$this->assertInstanceOf(Wrapper::class, $wrapper);
$this->assertEquals($sourceMeta, $wrapper->getMetaData());
}
} }