Last active
June 15, 2023 09:57
-
-
Save nyamsprod/298dd0f8969b052c8104c1e612753eb1 to your computer and use it in GitHub Desktop.
The Maybe nomad revisited from https://hackernoon.com/say-goodbye-to-null-checking-and-exceptions-using-the-maybe-monad-in-symfony/
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
<?php | |
/** | |
* @template T | |
*/ | |
class Maybe | |
{ | |
/** | |
* @param T|null $value | |
*/ | |
private function __construct( | |
private readonly mixed $value | |
) { | |
} | |
/** | |
* @param T|null $value | |
* @return Maybe<T> | |
*/ | |
public static function just($value): Maybe | |
{ | |
return new self($value); | |
} | |
/** | |
* @return Maybe<T> | |
*/ | |
public static function nothing(): Maybe | |
{ | |
return new self(null); | |
} | |
/** | |
* @template U | |
* @param callable(T):U $fn | |
* @return Maybe<U> | |
*/ | |
public function pipe(callable $fn): Maybe | |
{ | |
return match (true) { | |
null === $this->value => $this, | |
default => self::just($fn($this->value)), | |
}; | |
} | |
/** | |
* @param T $defaultValue | |
* @return T | |
*/ | |
public function value($defaultValue = null) | |
{ | |
return $this->value ?? $defaultValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment