Last active
February 10, 2021 20:24
-
-
Save stefanofago73/ea4ea505e5565ead744554c1c558501a to your computer and use it in GitHub Desktop.
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 declare(strict_types = 1); | |
/** | |
* NOTE: | |
* | |
* This example is for that legacy code where more error conditions | |
* are in sequence... Using exceptions, we are creating a control flow | |
* policy where every exception is an exit from actual flow. | |
* When not possible to refactor to FP or before using Try-Monad we can | |
* simulate monoid-al behaviour with an accumulator... | |
* | |
*/ | |
class ExceptionsStack | |
{ | |
/** @var array<string> $slots */ | |
private array $slots = []; | |
private function __construct() | |
{ | |
} | |
public final function addError(string $errorString):ExceptionsStack { | |
$this->slots[] = $errorString; | |
return $this; | |
} | |
/** @param Closure(\Exception):string $mapper */ | |
public final function addErrorFrom(\Exception $exc, \Closure $mapper):ExceptionsStack { | |
$this->slots[] = $mapper($exc); | |
return $this; | |
} | |
/** @param Closure(array<string>):\Exception $mapper */ | |
public final function toException(\Closure $mapper):\Exception { | |
return $mapper($this->slots); | |
} | |
/** | |
* @param Closure(array<string>):\Exception $mapper | |
* @return Closure():\Exception | |
*/ | |
public final function toExceptionLazy(\Closure $mapper):\Closure { | |
return fn()=>$mapper($this->slots); | |
} | |
public static final function createWith(string $start):ExceptionsStack | |
{ | |
$instance = new ExceptionsStack(); | |
$instance->slots[]=$start; | |
return $instance; | |
} | |
public static final function create():ExceptionsStack | |
{ | |
return new ExceptionsStack(); | |
} | |
}//END | |
/** | |
* | |
* USAGE SIMULATION | |
* | |
*/ | |
$stack = ExceptionsStack::create(); | |
$x = time(); | |
try{ | |
throw new \Exception("Something goes wrong!..."); | |
}catch(Exception $exc){ | |
$stack->addErrorFrom($exc,fn(\Exception $exc)=>sprintf("<[%s]>",$exc->__toString()) ); | |
} | |
if(($x%10)>=5) | |
{ | |
$stack->addError("No valid X value passed"); | |
} | |
/** | |
* Maybe I want to throw a "summary" Exception or convert to a specifi type | |
* Lazy variant can be useful to generate the Exception after more code | |
* in a precise point choosen by dev... | |
* | |
*/ | |
$ex1 = $stack->toException(fn(array $strings)=>new \Exception(implode($strings))); | |
echo $ex1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment