ILIAS  release_8 Revision v8.19
All Data Structures Namespaces Files Functions Variables Modules Pages
Error.php
Go to the documentation of this file.
1 <?php
2 
3 declare(strict_types=1);
4 
5 /* Copyright (c) 2017 Stefan Hecken <stefan.hecken@concepts-and-training.de> Extended GPL, see docs/LICENSE */
6 
7 namespace ILIAS\Data\Result;
8 
9 use ILIAS\Data;
11 
17 class Error implements Data\Result
18 {
22  protected $error;
23 
24  public function __construct($error)
25  {
26  if (!is_string($error) && !($error instanceof \Exception)) {
27  throw new \InvalidArgumentException("Expected error to be a string or an Exception.");
28  }
29  $this->error = $error;
30  }
31 
35  public function isOK(): bool
36  {
37  return false;
38  }
39 
43  public function value()
44  {
45  if ($this->error instanceof \Exception) {
46  throw $this->error;
47  }
48 
49  throw new Data\NotOKException($this->error);
50  }
51 
55  public function isError(): bool
56  {
57  return true;
58  }
59 
63  public function error()
64  {
65  return $this->error;
66  }
67 
71  public function valueOr($default)
72  {
73  return $default;
74  }
75 
79  public function map(callable $f): Result
80  {
81  return $this;
82  }
83 
87  public function then(callable $f): Result
88  {
89  return $this;
90  }
91 
95  public function except(callable $f): Result
96  {
97  $result = $f($this->error);
98 
99  if ($result === null) {
100  return $this;
101  }
102 
103  if (!$result instanceof Data\Result) {
104  throw new \UnexpectedValueException("The returned type of callable is not an instance of interface Result");
105  }
106 
107  return $result;
108  }
109 }
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Result.php:14
then(callable $f)
Get a new result from the callable or do nothing if this is an error.If null is returned from $f...
Definition: Error.php:87
valueOr($default)
Get the encapsulated value or the supplied default if result is an error.mixed
Definition: Error.php:71
map(callable $f)
Create a new result where the contained value is modified with $f.Does nothing if !isOK...
Definition: Error.php:79
isError()
Get to know if the result is an error.
Definition: Error.php:55
value()
Get the encapsulated value.mixed
Definition: Error.php:43
isOK()
Get to know if the result is ok.
Definition: Error.php:35
except(callable $f)
Feed the error into a callable and replace this with the result or do nothing if this is a value...
Definition: Error.php:95
error()
Get the encapsulated error.|string
Definition: Error.php:63
Signals that a result contains no value.