112 lines
1.9 KiB
PHP
112 lines
1.9 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Lucent\ResultType;
|
|
|
|
use Lucent\Option\None;
|
|
use Lucent\Option\Some;
|
|
|
|
/**
|
|
* @template T
|
|
* @template E
|
|
*
|
|
* @extends \Lucent\ResultType\Result<T,E>
|
|
*/
|
|
final class Success extends Result
|
|
{
|
|
/**
|
|
* @var T
|
|
*/
|
|
private $value;
|
|
|
|
/**
|
|
* Internal constructor for a success value.
|
|
*
|
|
* @param T $value
|
|
*
|
|
* @return void
|
|
*/
|
|
private function __construct($value)
|
|
{
|
|
$this->value = $value;
|
|
}
|
|
|
|
/**
|
|
* Create a new error value.
|
|
*
|
|
* @template S
|
|
*
|
|
* @param S $value
|
|
*
|
|
* @return \Lucent\ResultType\Result<S,E>
|
|
*/
|
|
public static function create($value): Success
|
|
{
|
|
return new self($value);
|
|
}
|
|
|
|
/**
|
|
* Get the success option value.
|
|
*
|
|
* @return \Lucent\Option\Option<T>
|
|
*/
|
|
public function success(): Some
|
|
{
|
|
return Some::create($this->value);
|
|
}
|
|
|
|
/**
|
|
* Map over the success value.
|
|
*
|
|
* @template S
|
|
*
|
|
* @param callable(T):S $f
|
|
*
|
|
* @return \Lucent\ResultType\Result<S,E>
|
|
*/
|
|
public function map(callable $f): Result
|
|
{
|
|
return self::create($f($this->value));
|
|
}
|
|
|
|
/**
|
|
* Flat map over the success value.
|
|
*
|
|
* @template S
|
|
* @template F
|
|
*
|
|
* @param callable(T):\Lucent\ResultType\Result<S,F> $f
|
|
*
|
|
* @return \Lucent\ResultType\Result<S,F>
|
|
*/
|
|
public function flatMap(callable $f)
|
|
{
|
|
return $f($this->value);
|
|
}
|
|
|
|
/**
|
|
* Get the error option value.
|
|
*
|
|
* @return \Lucent\Option\Option<E>
|
|
*/
|
|
public function error()
|
|
{
|
|
return None::create();
|
|
}
|
|
|
|
/**
|
|
* Map over the error value.
|
|
*
|
|
* @template F
|
|
*
|
|
* @param callable(E):F $f
|
|
*
|
|
* @return \Lucent\ResultType\Result<T,F>
|
|
*/
|
|
public function mapError(callable $f): Result
|
|
{
|
|
return self::create($this->value);
|
|
}
|
|
}
|