|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +use Psr\Container\ContainerInterface; |
| 6 | +use TypeLang\Mapper\Exception\Mapping\InvalidValueException; |
| 7 | +use TypeLang\Mapper\Mapper; |
| 8 | +use TypeLang\Mapper\Platform\DelegatePlatform; |
| 9 | +use TypeLang\Mapper\Platform\StandardPlatform; |
| 10 | +use TypeLang\Mapper\Runtime\Context; |
| 11 | +use TypeLang\Mapper\Type\Builder\CallableTypeBuilder; |
| 12 | +use TypeLang\Mapper\Type\TypeInterface; |
| 13 | + |
| 14 | +require __DIR__ . '/../../vendor/autoload.php'; |
| 15 | + |
| 16 | + |
| 17 | +class Container implements ContainerInterface |
| 18 | +{ |
| 19 | + /** |
| 20 | + * @var array<non-empty-string, object> |
| 21 | + */ |
| 22 | + private array $services; |
| 23 | + |
| 24 | + public function __construct() |
| 25 | + { |
| 26 | + $this->services = [ |
| 27 | + 'my-non-empty-type' => new MyNonEmptyStringType() |
| 28 | + ]; |
| 29 | + } |
| 30 | + |
| 31 | + public function get(string $id) |
| 32 | + { |
| 33 | + return $this->services[$id] ?? throw new \RuntimeException("Service $id not found"); |
| 34 | + } |
| 35 | + |
| 36 | + public function has(string $id): bool |
| 37 | + { |
| 38 | + return array_key_exists($id, $this->services); |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | + |
| 43 | + |
| 44 | + |
| 45 | +// Add new type (must implement TypeInterface) |
| 46 | +class MyNonEmptyStringType implements TypeInterface |
| 47 | +{ |
| 48 | + public function match(mixed $value, Context $context): bool |
| 49 | + { |
| 50 | + return \is_string($value) && $value !== ''; |
| 51 | + } |
| 52 | + |
| 53 | + public function cast(mixed $value, Context $context): string |
| 54 | + { |
| 55 | + if (\is_string($value) && $value !== '') { |
| 56 | + return $value; |
| 57 | + } |
| 58 | + |
| 59 | + throw new InvalidValueException( |
| 60 | + value: $value, |
| 61 | + path: $context->getPath(), |
| 62 | + template: 'Passed value cannot be empty, but {{value}} given', |
| 63 | + ); |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +$container = new Container(); |
| 68 | + |
| 69 | +$mapper = new Mapper(new DelegatePlatform( |
| 70 | + // Extend existing platform (StandardPlatform) |
| 71 | + delegate: new StandardPlatform(), |
| 72 | + types: [ |
| 73 | + // Additional type |
| 74 | + new CallableTypeBuilder('custom-string', static fn (): TypeInterface => $container->get('my-non-empty-type')), |
| 75 | + ], |
| 76 | +)); |
| 77 | + |
| 78 | +$result = $mapper->normalize(['example'], 'list<custom-string>'); |
| 79 | + |
| 80 | +var_dump($result); |
| 81 | +// |
| 82 | +// expected exception: |
| 83 | +// TypeLang\Mapper\Exception\Mapping\InvalidIterableValueException: |
| 84 | +// Passed value "" on index 1 in ["example", ""] is invalid at $[1] |
| 85 | +// |
| 86 | +// previous exception: |
| 87 | +// TypeLang\Mapper\Exception\Mapping\InvalidValueException: |
| 88 | +// Passed value cannot be empty, but "" given at $[1] |
| 89 | +// |
0 commit comments