-
Notifications
You must be signed in to change notification settings - Fork 0
/
04.custom-platform.php
57 lines (46 loc) · 1.48 KB
/
04.custom-platform.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\Mapper;
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
{
public function getName(): string
{
return 'simple';
}
public function getTypes(): iterable
{
// The platform will only support objects, that is,
// references to existing classes.
yield new ClassTypeBuilder();
}
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());
var_dump($mapper->normalize(new ExampleDTO()));
//
// TypeRequiredException: Type "int" for property ExampleDTO::$value
// is not defined
//
var_dump($mapper->normalize([new ExampleDTO()], 'array<ExampleDTO>'));
//
// ParseException: Template arguments not allowed in "array<ExampleDTO>" at column 6
//