Repository navigation
Expand file tree
/
Copy pathExceptionMappingRule.php
More file actions
68 lines (62 loc) · 2.55 KB
/
Copy pathExceptionMappingRule.php
File metadata and controls
68 lines (62 loc) · 2.55 KB
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
<?php
declare(strict_types=1);
namespace TinyBlocks\Http\ErrorHandler;
use Closure;
use Throwable;
use TinyBlocks\Http\ErrorHandler\Internal\Mapping\DefaultMappingEntry;
use TinyBlocks\Http\ErrorHandler\Internal\Mapping\DynamicMappedErrorResolver;
use TinyBlocks\Http\ErrorHandler\Internal\Mapping\FixedMappedErrorResolver;
/**
* Intermediate builder closing a rule registered on an {@see ExceptionMappingTable}. A rule
* resolves either to a fixed {@see MappedError} (<code>mapsTo</code>) or to one produced by a
* closure that receives the matched throwable (<code>resolvesWith</code>).
*/
final readonly class ExceptionMappingRule
{
public function __construct(private ExceptionMappingTable $table, private ExceptionMatcher $matcher)
{
}
/**
* Closes the rule with a fixed MappedError produced from the given fields.
*
* @param string $code Machine-readable error code.
* @param int $status HTTP response status code, one of the known HTTP error statuses.
* @param string $message Human-readable error description.
* @param array<string, string|string[]> $headers Optional HTTP response headers.
* @return ExceptionMappingTable The table with the new rule appended.
*/
public function mapsTo(string $code, int $status, string $message, array $headers = []): ExceptionMappingTable
{
return $this->table->withEntry(
entry: new DefaultMappingEntry(
matcher: $this->matcher,
resolver: new FixedMappedErrorResolver(
error: new MappedError(
code: $code,
status: $status,
message: $message,
headers: $headers
)
)
)
);
}
/**
* Closes the rule with a closure that produces a MappedError from the matched exception.
*
* <p>The closure parameter may be typed more specifically than {@see Throwable} when the
* matcher guarantees the runtime type before the closure is invoked.</p>
*
* @param Closure(Throwable): MappedError $resolver The closure to invoke with the matched exception.
* @return ExceptionMappingTable The table with the new rule appended.
*/
public function resolvesWith(Closure $resolver): ExceptionMappingTable
{
return $this->table->withEntry(
entry: new DefaultMappingEntry(
matcher: $this->matcher,
resolver: new DynamicMappedErrorResolver(factory: $resolver)
)
);
}
}