From d2114541a5402cb7fcff99548b246ff187e9ac68 Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Thu, 18 Apr 2024 12:31:59 +0200 Subject: [PATCH] feat: narrow ResultInterface to concrete implementation after calling `isSucceeded()` and `isFailed()` (#466) --- src/Psl/Result/ResultInterface.php | 4 ++ .../Result/result_interface.php | 42 +++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 tests/static-analysis/Result/result_interface.php diff --git a/src/Psl/Result/ResultInterface.php b/src/Psl/Result/ResultInterface.php index a37731cb..1e180e49 100644 --- a/src/Psl/Result/ResultInterface.php +++ b/src/Psl/Result/ResultInterface.php @@ -115,6 +115,8 @@ public function getThrowable(): Throwable; * @return bool - `true` if the operation succeeded; `false` otherwise * * @psalm-mutation-free + * + * @psalm-assert-if-true Success $this */ public function isSucceeded(): bool; @@ -126,6 +128,8 @@ public function isSucceeded(): bool; * @return bool - `true` if the operation failed; `false` otherwise * * @psalm-mutation-free + * + * @psalm-assert-if-true Failure $this */ public function isFailed(): bool; diff --git a/tests/static-analysis/Result/result_interface.php b/tests/static-analysis/Result/result_interface.php new file mode 100644 index 00000000..e5f7d0d1 --- /dev/null +++ b/tests/static-analysis/Result/result_interface.php @@ -0,0 +1,42 @@ + $result + * + * @throws Exception + * + * @return Failure + */ +function return_failure(ResultInterface $result): Failure +{ + if ($result->isFailed()) { + return $result; + } + + throw new Exception(); +} + +/** + * @param ResultInterface $result + * + * @throws Exception + * + * @return Success + */ +function return_success(ResultInterface $result): Success +{ + if ($result->isSucceeded()) { + return $result; + } + + throw new Exception(); +}