forked from ILIAS-eLearning/ILIAS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblemBuilder.php
93 lines (83 loc) · 2.51 KB
/
ProblemBuilder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
<?php
/**
* This file is part of ILIAS, a powerful learning management system
* published by ILIAS open source e-Learning e.V.
*
* ILIAS is licensed with the GPL-3.0,
* see https://www.gnu.org/licenses/gpl-3.0.en.html
* You should have received a copy of said license along with the
* source code, too.
*
* If this is not the case or you just want to try ILIAS, you'll find
* us at:
* https://www.ilias.de
* https://github.com/ILIAS-eLearning
*
*********************************************************************/
declare(strict_types=1);
namespace ILIAS\Refinery;
use Closure;
use InvalidArgumentException;
trait ProblemBuilder
{
/**
* @return string|callable
*/
abstract protected function getError();
/**
* @inheritDoc
*/
final public function withProblemBuilder(callable $builder): self
{
$clone = clone $this;
$clone->error = $builder;
return $clone;
}
/**
* Get the problem message
* @param mixed $value
* @return string
*/
final public function getErrorMessage($value): string
{
$error = $this->getError();
if (!is_callable($error)) {
return $error;
}
$lng_closure = $this->getLngClosure();
return call_user_func($this->error, $lng_closure, $value);
}
/**
* Get the closure to be passed to the error-function that does i18n and sprintf.
* @return Closure
*/
final protected function getLngClosure(): Closure
{
return function () {
$args = func_get_args();
if (count($args) < 1) {
throw new InvalidArgumentException(
"Expected an id of a lang var as first parameter"
);
}
$error = $this->lng->txt($args[0]);
if (count($args) > 1) {
$args[0] = $error;
for ($i = 0, $numArgs = count($args); $i < $numArgs; $i++) {
$v = $args[$i];
if (is_array($v) || is_null($v) || (is_object($v) && !method_exists($v, "__toString"))) {
if (is_array($v)) {
$args[$i] = "array";
} elseif (is_null($v)) {
$args[$i] = "null";
} else {
$args[$i] = get_class($v);
}
}
}
$error = sprintf(...$args);
}
return $error;
};
}
}