Skip to content

Commit

Permalink
Make ByteStream use an actual stream handle
Browse files Browse the repository at this point in the history
  • Loading branch information
olafkryus committed Jun 20, 2019
1 parent 90e971c commit 35fc499
Showing 1 changed file with 32 additions and 10 deletions.
42 changes: 32 additions & 10 deletions src/ByteStream.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,11 @@

class ByteStream
{
/** @var string */
private $contents;
/** @var resource */
private $handle;

/** @var bool */
private $internalHandle = false;

/** @var int */
private $cursor = 0;
Expand All @@ -23,39 +26,58 @@ class ByteStream
private $endianness;

/**
* @param string $contents
* @param resource $handle
* @param int $endianness
* @throws \Exception
*/
public function __construct(string $contents, int $endianness = BinaryValue::ENDIANNESS_LITTLE_ENDIAN)
public function __construct($handle, int $endianness = BinaryValue::ENDIANNESS_LITTLE_ENDIAN)
{
if (!in_array($endianness, [BinaryValue::ENDIANNESS_LITTLE_ENDIAN, BinaryValue::ENDIANNESS_BIG_ENDIAN], true)) {
throw new \Exception('Invalid endianness type.');
}

$this->contents = $contents;
$this->handle = $handle;
$this->endianness = $endianness;
}

public function __destruct()
{
if ($this->internalHandle) {
$this->close();
}
}

/**
* @param string $filename
* @param string $mode
* @param int $endianness
* @return ByteStream
* @throws \Exception
*/
public static function createFromFilename(string $filename, int $endianness = BinaryValue::ENDIANNESS_LITTLE_ENDIAN): ByteStream
public static function createFromFilename(string $filename, string $mode, int $endianness = BinaryValue::ENDIANNESS_LITTLE_ENDIAN): ByteStream
{
$contents = file_get_contents($filename);
$handle = fopen($filename, $mode);

$stream = new self($handle, $endianness);
$stream->internalHandle = true;

return new self($contents, $endianness);
return $stream;
}

/**
* @return bool
*/
public function isEof(): bool
{
return $this->cursor === strlen($this->contents);
return feof($this->handle);
}

/**
* @return bool
*/
public function close(): bool
{
return fclose($this->handle);
}

/**
Expand All @@ -69,7 +91,7 @@ public function readBytes(int $count): string
throw new \Exception("Cannot read value: End of stream reached at position {$this->cursor}.");
}

$value = substr($this->contents, $this->cursor, $count);
$value = fread($this->handle, $count);
$this->cursor += $count;

if (strlen($value) !== $count) {
Expand Down

0 comments on commit 35fc499

Please sign in to comment.