-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path02.custom-type.php
57 lines (48 loc) · 1.65 KB
/
02.custom-type.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
<?php
declare(strict_types=1);
use TypeLang\Mapper\Exception\Mapping\InvalidValueException;
use TypeLang\Mapper\Mapper;
use TypeLang\Mapper\Platform\DelegatePlatform;
use TypeLang\Mapper\Platform\Standard\Builder\SimpleTypeBuilder;
use TypeLang\Mapper\Platform\Standard\Type\TypeInterface;
use TypeLang\Mapper\Platform\StandardPlatform;
use TypeLang\Mapper\Runtime\Context;
require __DIR__ . '/../../vendor/autoload.php';
// 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',
);
}
}
$mapper = new Mapper(new DelegatePlatform(
// Extend existing platform (StandardPlatform)
delegate: new StandardPlatform(),
types: [
// Additional type
new SimpleTypeBuilder('custom-string', MyNonEmptyStringType::class)
],
));
$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]
//