-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path04.custom-platform.php
More file actions
86 lines (72 loc) · 2.31 KB
/
04.custom-platform.php
File metadata and controls
86 lines (72 loc) · 2.31 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
declare(strict_types=1);
use TypeLang\Mapper\Mapper;
use TypeLang\Mapper\Mapping\Provider\MetadataBuilder;
use TypeLang\Mapper\Mapping\Reader\AttributeReader;
use TypeLang\Mapper\Platform\Common\SupportsClassInstantiator;
use TypeLang\Mapper\Platform\Common\SupportsMetadata;
use TypeLang\Mapper\Platform\Common\SupportsPropertyAccessor;
use TypeLang\Mapper\Platform\GrammarFeature;
use TypeLang\Mapper\Platform\PlatformInterface;
use TypeLang\Mapper\Type\Builder\ClassTypeBuilder;
require __DIR__ . '/../../vendor/autoload.php';
// The set of types and grammar is defined using a "platform". You can create
// your own platform, for example, for a specific DB, or use built-in ones.
//
// For example, let's create a platform that supports only simple types,
// without generics, union types, shapes, and other things.
class SimplePlatform implements PlatformInterface
{
use SupportsMetadata;
use SupportsPropertyAccessor;
use SupportsClassInstantiator;
public function getName(): string
{
return 'simple';
}
public function getTypes(): iterable
{
$driver = new MetadataBuilder(new AttributeReader());
// The platform will only support objects, that is,
// references to existing classes.
yield new ClassTypeBuilder(
meta: $this->getMetadataProvider(),
accessor: $this->getPropertyAccessor(),
instantiator: $this->getClassInstantiator(),
);
}
public function getTypeCoercers(): iterable
{
return [];
}
public function isFeatureSupported(GrammarFeature $feature): bool
{
// Disable all grammar features except the main one.
return false;
}
}
class ExampleDTO
{
public function __construct(
public readonly int $value = 42,
) {}
}
$mapper = new Mapper(new SimplePlatform());
try {
var_dump($mapper->normalize(new ExampleDTO()));
} catch (\Throwable $e) {
echo $e->getMessage() . "\n";
}
//
// TypeRequiredException: Type "int" for property ExampleDTO::$value
// is not defined
//
try {
var_dump($mapper->normalize([new ExampleDTO()], 'array<ExampleDTO>'));
} catch (\Throwable $e) {
echo $e->getMessage() . "\n";
}
//
// ParseException: Template arguments not allowed in "array<ExampleDTO>"
// at column 6
//