Skip to content

Commit

Permalink
Change set/restore error handler to a try/catch block
Browse files Browse the repository at this point in the history
Signed-off-by: George Steel <george@net-glue.co.uk>
  • Loading branch information
gsteel committed Jul 6, 2022
1 parent 091cd93 commit 122bc9b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 28 deletions.
10 changes: 0 additions & 10 deletions psalm-baseline.xml
Expand Up @@ -270,13 +270,6 @@
</MoreSpecificReturnType>
</file>
<file src="src/Stream.php">
<InvalidArgument occurrences="1"/>
<PossiblyInvalidArgument occurrences="1">
<code>$resource</code>
</PossiblyInvalidArgument>
<PossiblyInvalidPropertyAssignmentValue occurrences="1">
<code>$resource</code>
</PossiblyInvalidPropertyAssignmentValue>
<PossiblyNullArgument occurrences="4">
<code>$resource</code>
<code>$this-&gt;resource</code>
Expand All @@ -286,9 +279,6 @@
<PropertyNotSetInConstructor occurrences="1">
<code>$stream</code>
</PropertyNotSetInConstructor>
<RedundantConditionGivenDocblockType occurrences="1">
<code>is_resource($resource)</code>
</RedundantConditionGivenDocblockType>
</file>
<file src="src/StreamFactory.php">
<ParamNameMismatch occurrences="1">
Expand Down
26 changes: 8 additions & 18 deletions src/Stream.php
Expand Up @@ -7,6 +7,7 @@
use GdImage;
use Psr\Http\Message\StreamInterface;
use RuntimeException;
use Throwable;

use function array_key_exists;
use function fclose;
Expand All @@ -22,13 +23,10 @@
use function is_int;
use function is_resource;
use function is_string;
use function restore_error_handler;
use function set_error_handler;
use function stream_get_contents;
use function stream_get_meta_data;
use function strstr;

use const E_WARNING;
use const PHP_VERSION_ID;
use const SEEK_SET;

Expand Down Expand Up @@ -320,23 +318,14 @@ public function getMetadata($key = null)
*/
private function setStream($stream, string $mode = 'r'): void
{
$error = null;
$resource = $stream;

if (is_string($stream)) {
set_error_handler(function ($e) use (&$error) {
if ($e !== E_WARNING) {
return;
}

$error = $e;
});
$resource = fopen($stream, $mode);
restore_error_handler();
}

if ($error) {
throw new Exception\RuntimeException('Invalid stream reference provided');
try {
$resource = fopen($stream, $mode);
} catch (Throwable $e) {
throw new Exception\RuntimeException('Invalid stream reference provided');
}
}

if (! $this->isValidStreamResourceType($resource)) {
Expand All @@ -355,7 +344,8 @@ private function setStream($stream, string $mode = 'r'): void
/**
* Determine if a resource is one of the resource types allowed to instantiate a Stream
*
* @param resource $resource Stream resource.
* @param mixed $resource Stream resource.
* @psalm-assert-if-true resource $resource
*/
private function isValidStreamResourceType($resource): bool
{
Expand Down

0 comments on commit 122bc9b

Please sign in to comment.