Skip to content

Instantly share code, notes, and snippets.

@nyamsprod
Last active June 15, 2023 09:57
Show Gist options
  • Save nyamsprod/298dd0f8969b052c8104c1e612753eb1 to your computer and use it in GitHub Desktop.
Save nyamsprod/298dd0f8969b052c8104c1e612753eb1 to your computer and use it in GitHub Desktop.
<?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