psl icon indicating copy to clipboard operation
psl copied to clipboard

ShapeType and CoercionException

Open vaclavvanik opened this issue 3 years ago • 2 comments

I love coercing ShapeType. I can easily check if given payload is in expected format. However debugging complex ShapeType CoercionException is pain in the ass.

Let's see simple (complex) example:

<?php

use Psl\Type;

require_once __DIR__ . '/vendor/autoload.php';

$type = Type\shape([
    'response' => Type\shape([
        'object1' => Type\shape([
            'code' => Type\non_empty_string(),
        ]),
        'object2' => Type\shape([
            'code' => Type\non_empty_string(),
        ]),
    ]),
]);

$payload = [
    'response' => [
        'object1' => [
            'code' => '',
        ],
        'object2' => [
            'code' => 5,
        ],
    ]
];

$coerce = $type->coerce($payload);

This will throw CoercionException with message: Could not coerce "string" to type "non-empty-string".

It is really confusing I do not know which node is invalid.

I would suggest message like: Could not coerce (response->object1->code) "string" to type "non-empty-string".

vaclavvanik avatar Jun 11 '21 12:06 vaclavvanik

type exceptions contain a type trace, however, the type trace for shapes needs a bit of improvement.

example: https://phpsandbox.io/n/broad-sunset-wkem-c9oad

azjezz avatar Jun 11 '21 13:06 azjezz

another example: https://phpsandbox.io/n/broad-sunset-wkem-c9oad

one this that i think would be useful is to flip the frames by default.

azjezz avatar Jun 11 '21 13:06 azjezz

Fixed in https://github.com/azjezz/psl/pull/453

veewee avatar Apr 04 '24 10:04 veewee