fix!: handle php errors with custom error handling
This commit changes the api of the stream classes, since indication of success or failure is no longer necessary.
This commit is contained in:
52
src/StreamTrait.php
Normal file
52
src/StreamTrait.php
Normal file
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Nih\CommandBuilder;
|
||||
|
||||
use InvalidArgumentException;
|
||||
|
||||
trait StreamTrait
|
||||
{
|
||||
/**
|
||||
* @param resource $stream
|
||||
*
|
||||
* @throws InvalidArgumentException When stream is not a stream
|
||||
*/
|
||||
public function __construct(private readonly mixed $stream)
|
||||
{
|
||||
if (get_resource_type($stream) !== 'stream') {
|
||||
throw new InvalidArgumentException('resource is not a stream');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the stream.
|
||||
*
|
||||
* Noop if the stream was already closed.
|
||||
*
|
||||
* @throws StreamException
|
||||
*/
|
||||
public function close(): void
|
||||
{
|
||||
if (get_resource_type($this->stream) !== 'stream') {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
set_error_handler(StreamException::handleError(...));
|
||||
$success = fclose($this->stream);
|
||||
} finally {
|
||||
restore_error_handler();
|
||||
}
|
||||
|
||||
assert($success);
|
||||
}
|
||||
|
||||
public function __destruct()
|
||||
{
|
||||
if (get_resource_type($this->stream) === 'stream') {
|
||||
fclose($this->stream);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user