-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path05.custom-type-callable.php
90 lines (71 loc) · 2.26 KB
/
05.custom-type-callable.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
<?php
declare(strict_types=1);
use Psr\Container\ContainerInterface;
use TypeLang\Mapper\Exception\Mapping\InvalidValueException;
use TypeLang\Mapper\Mapper;
use TypeLang\Mapper\Platform\DelegatePlatform;
use TypeLang\Mapper\Platform\StandardPlatform;
use TypeLang\Mapper\Runtime\Context;
use TypeLang\Mapper\Type\Builder\CallableTypeBuilder;
use TypeLang\Mapper\Type\TypeInterface;
require __DIR__ . '/../../vendor/autoload.php';
class Container implements ContainerInterface
{
/**
* @var array<non-empty-string, object>
*/
private array $services;
public function __construct()
{
$this->services = [
'my-non-empty-type' => new MyNonEmptyStringType()
];
}
public function get(string $id)
{
return $this->services[$id] ?? throw new \RuntimeException("Service $id not found");
}
public function has(string $id): bool
{
return array_key_exists($id, $this->services);
}
}
// Add new type (must implement TypeInterface)
class MyNonEmptyStringType implements TypeInterface
{
public function match(mixed $value, Context $context): bool
{
return \is_string($value) && $value !== '';
}
public function cast(mixed $value, Context $context): string
{
if (\is_string($value) && $value !== '') {
return $value;
}
throw new InvalidValueException(
value: $value,
path: $context->getPath(),
template: 'Passed value cannot be empty, but {{value}} given',
);
}
}
$container = new Container();
$mapper = new Mapper(new DelegatePlatform(
// Extend existing platform (StandardPlatform)
delegate: new StandardPlatform(),
types: [
// Additional type
new CallableTypeBuilder('custom-string', static fn (): TypeInterface => $container->get('my-non-empty-type')),
],
));
$result = $mapper->normalize(['example', ''], 'list<custom-string>');
var_dump($result);
//
// expected exception:
// TypeLang\Mapper\Exception\Mapping\InvalidIterableValueException:
// Passed value "" on index 1 in ["example", ""] is invalid at $[1]
//
// previous exception:
// TypeLang\Mapper\Exception\Mapping\InvalidValueException:
// Passed value cannot be empty, but "" given at $[1]
//