-
Notifications
You must be signed in to change notification settings - Fork 432
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add support and tests for
$this
type assertions
- Loading branch information
1 parent
d67f5eb
commit a44f10c
Showing
2 changed files
with
85 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
<?php | ||
|
||
namespace AssertThis; | ||
|
||
use RuntimeException; | ||
|
||
use function PHPStan\Testing\assertType; | ||
|
||
/** | ||
* @template TOk | ||
* @template TErr | ||
*/ | ||
interface Result { | ||
/** | ||
* @phpstan-assert-if-true Ok<TOk> $this | ||
* @phpstan-assert-if-false Err<TErr> $this | ||
*/ | ||
public function isOk(): bool; | ||
|
||
/** | ||
* @return TOk|never | ||
*/ | ||
public function unwrap(); | ||
} | ||
|
||
/** | ||
* @template TOk | ||
* @template-implements Result<TOk, never> | ||
*/ | ||
class Ok implements Result { | ||
public function __construct(private $value) { | ||
} | ||
|
||
/** | ||
* @return true | ||
*/ | ||
public function isOk(): bool { | ||
return true; | ||
} | ||
|
||
/** | ||
* @return TOk | ||
*/ | ||
public function unwrap() { | ||
return $this->value; | ||
} | ||
} | ||
|
||
/** | ||
* @template TErr | ||
* @template-implements Result<never, TErr> | ||
*/ | ||
class Err implements Result { | ||
public function __construct(private $value) { | ||
} | ||
|
||
/** | ||
* @return false | ||
*/ | ||
public function isOk(): bool { | ||
return false; | ||
} | ||
|
||
/** | ||
* @return never | ||
*/ | ||
public function unwrap() { | ||
throw new RuntimeException('Tried to unwrap() an Err value'); | ||
} | ||
} | ||
|
||
function () { | ||
/** @var Result<int, string> $result */ | ||
$result = new Ok(123); | ||
assertType('AssertThis\\Result<int, string>', $result); | ||
|
||
if ($result->isOk()) { | ||
assertType('AssertThis\\Ok<int>', $result); | ||
assertType('int', $result->unwrap()); | ||
} else { | ||
assertType('AssertThis\\Err<string>', $result); | ||
assertType('never', $result->unwrap()); | ||
} | ||
}; |