Skip to content

Commit

Permalink
Improve Cloak behaviour regarding exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
nyamsprod committed Nov 28, 2023
1 parent 1c0dd77 commit 866639e
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 7 deletions.
11 changes: 5 additions & 6 deletions src/Error/Cloak.php
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,7 @@ public function __invoke(mixed ...$arguments): mixed
restore_error_handler();
}

return match (true) {
$this->errors->isEmpty(),
$this->errorsAreSilenced() => $result,
default => throw $this->errors,
};
return $result;
}

protected function errorHandler(int $errno, string $errstr, string $errfile = null, int $errline = null): bool
Expand All @@ -115,7 +111,10 @@ protected function errorHandler(int $errno, string $errstr, string $errfile = nu

$this->errors->unshift(new ErrorException($errstr, 0, $errno, $errfile, $errline));

return true;
return match ($this->errorsAreThrown()) {
true => throw $this->errors(),
false => true,
};
}

public static function throwOnError(): void
Expand Down
21 changes: 20 additions & 1 deletion src/Error/CloakTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ public function it_can_detect_the_level_to_include(): void
}

#[Test]
public function it_can_collection_all_errors(): void
public function it_can_collection_all_errors_if_errors_are_silenced(): void
{
$closure = function (string $path): array|false {
touch($path);
Expand All @@ -145,6 +145,25 @@ public function it_can_collection_all_errors(): void
self::assertSame('file(/foobar): Failed to open stream: No such file or directory', $errors->last()?->getMessage() ?? '');
}

#[Test]
public function it_throws_with_the_first_error_if_errors_are_thrown(): void
{
$closure = function (string $path): array|false {
touch($path);

return file($path);
};

try {
$lambda = Cloak::warning($closure, Cloak::THROW);
$lambda('/foobar');
self::fail(CloakedErrors::class . ' was not thrown');
} catch (CloakedErrors $cloakedErrors) {
self::assertCount(1, $cloakedErrors);
self::assertStringContainsString('touch(): Unable to create file /foobar because', $cloakedErrors->first()?->getMessage() ?? '');
}
}

#[Test]
public function it_does_not_interfer_with_exception(): void
{
Expand Down

0 comments on commit 866639e

Please sign in to comment.