| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Webauthn; |
| 6 |
|
| 7 |
use function assert; |
| 8 |
use CBOR\Stream; |
| 9 |
use function fclose; |
| 10 |
use function fopen; |
| 11 |
use function fread; |
| 12 |
use function fwrite; |
| 13 |
use function rewind; |
| 14 |
use function sprintf; |
| 15 |
use function strlen; |
| 16 |
use Webauthn\Exception\InvalidDataException; |
| 17 |
|
| 18 |
final class StringStream implements Stream |
| 19 |
{ |
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
private $data; |
| 24 |
|
| 25 |
private readonly int $length; |
| 26 |
|
| 27 |
private int $totalRead = 0; |
| 28 |
|
| 29 |
public function __construct(string $data) |
| 30 |
{ |
| 31 |
$this->length = strlen($data); |
| 32 |
$resource = fopen('php://memory', 'rb+'); |
| 33 |
assert($resource !== false, 'The resource could not be opened.'); |
| 34 |
fwrite($resource, $data); |
| 35 |
rewind($resource); |
| 36 |
$this->data = $resource; |
| 37 |
} |
| 38 |
|
| 39 |
public function read(int $length): string |
| 40 |
{ |
| 41 |
if ($length <= 0) { |
| 42 |
return ''; |
| 43 |
} |
| 44 |
$read = fread($this->data, $length); |
| 45 |
assert($read !== false, 'The data could not be read.'); |
| 46 |
$bytesRead = strlen($read); |
| 47 |
strlen($read) === $length || throw InvalidDataException::create(null, sprintf( |
| 48 |
'Out of range. Expected: %d, read: %d.', |
| 49 |
$length, |
| 50 |
$bytesRead |
| 51 |
)); |
| 52 |
$this->totalRead += $bytesRead; |
| 53 |
|
| 54 |
return $read; |
| 55 |
} |
| 56 |
|
| 57 |
public function close(): void |
| 58 |
{ |
| 59 |
fclose($this->data); |
| 60 |
} |
| 61 |
|
| 62 |
public function isEOF(): bool |
| 63 |
{ |
| 64 |
return $this->totalRead === $this->length; |
| 65 |
} |
| 66 |
} |