ILIAS  release_5-3 Revision v5.3.23-19-g915713cf615
Custom.php
Go to the documentation of this file.
1<?php
2/* Copyright (c) 2017 Stefan Hecken <stefan.hecken@concepts-and-training.de> Extended GPL, see docs/LICENSE */
3
5
7use ILIAS\Data;
9
10class Custom implements Constraint
11{
15 protected $data_factory;
16
20 protected $is_ok;
21
25 protected $error;
26
30 public function __construct(callable $is_ok, $error, Data\Factory $data_factory)
31 {
32 $this->is_ok = $is_ok;
33
34 if (!is_callable($error)) {
35 $this->error = function () use ($error) {
36 return $error;
37 };
38 } else {
39 $this->error = $error;
40 }
41
42 $this->data_factory = $data_factory;
43 }
44
48 final public function check($value)
49 {
50 if (!$this->accepts($value)) {
51 throw new \UnexpectedValueException($this->getErrorMessage($value));
52 }
53
54 return null;
55 }
56
60 final public function accepts($value)
61 {
62 return call_user_func($this->is_ok, $value);
63 }
64
68 final public function problemWith($value)
69 {
70 if (!$this->accepts($value)) {
71 return $this->getErrorMessage($value);
72 }
73
74 return null;
75 }
76
80 final public function restrict(Result $result)
81 {
82 if ($result->isError()) {
83 return $result;
84 }
85
86 $problem = $this->problemWith($result->value());
87 if ($problem !== null) {
88 $error = $this->data_factory->error($problem);
89 return $error;
90 }
91
92 return $result;
93 }
94
98 final public function withProblemBuilder(callable $builder)
99 {
100 $clone = clone $this;
101 $clone->error = $builder;
102 return $clone;
103 }
104
110 final public function getErrorMessage($value)
111 {
112 return call_user_func($this->error, $value);
113 }
114}
$result
An exception for terminatinating execution or to throw for unit testing.
Builds data types.
Definition: Factory.php:15
__construct(callable $is_ok, $error, Data\Factory $data_factory)
Definition: Custom.php:30
accepts($value)
Tells if the provided value complies.bool
Definition: Custom.php:60
problemWith($value)
Tells what the problem with the provided value is.Should return null if accepts($value)....
Definition: Custom.php:68
check($value)
Checks the provided value.Should not throw if accepts($value).UnexpectedValueException if value does ...
Definition: Custom.php:48
restrict(Result $result)
Restricts a Result.Must do nothing with the result if $result->isError(). Must replace the result wit...
Definition: Custom.php:80
withProblemBuilder(callable $builder)
Get a constraint like this one with a builder for a custom error message.problemWith() must return an...
Definition: Custom.php:98
getErrorMessage($value)
Get the problem message.
Definition: Custom.php:110
error($a_errmsg)
set error message @access public
A result encapsulates a value or an error and simplifies the handling of those.
Definition: Result.php:12
value()
Get the encapsulated value.
A constraint encodes some resrtictions on values.
Definition: Constraint.php:15