Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve error messages for shape and vec -like types #412

Closed
veewee opened this issue Jun 27, 2023 · 0 comments · Fixed by #453
Closed

Improve error messages for shape and vec -like types #412

veewee opened this issue Jun 27, 2023 · 0 comments · Fixed by #453
Assignees
Labels
Type: Enhancement Most issues will probably ask for additions or changes.

Comments

@veewee
Copy link
Collaborator

veewee commented Jun 27, 2023

Given:

use Psl\Type;
$shape = Type\shape([
    'name' => Type\string(),
    'articles' => Type\vec(Type\shape([
        'title' => Type\string(),
        'content' => Type\string(),
        'likes' => Type\int(),
        'comments' => Type\optional(Type\vec(Type\shape([
            'user' => Type\string(),
            'comment' => Type\string()
        ]))),
    ]))
]);

try {
    $shape->coerce([
        'name' => 'ok',
        'articles' => [
            [
                'title' => 'ok',
                'content' => new stdClass,
            ]
        ]
    ]);
} catch (Type\Exception\CoercionException $e) {
    echo $e->getMessage().PHP_EOL;
    var_dump($e->getTypeTrace()->getFrames());
}

This results in:

Could not coerce "stdClass" to type "string".

array(3) {
  [0] =>
  string(20) "array{'articles': _}"
  [1] =>
  string(120) "vec<array{'title': string, 'content': string, 'likes': int, 'comments'?: vec<array{'user': string, 'comment': string}>}>"
  [2] =>
  string(19) "array{'content': _}"
}

Both the path and frames are rather confusing and it is unclear what failed exactly without processing this information.

Suggestion:

Keep track of an additional path on the TypeTraceso that we can build errors like:

Could not coerce "stdClass" to type "string" at path articles.0.content

The path can contain a list of strings to identify the path - which will be set for shape and vec-like types:

  • Shapes will mark the property: prop
  • Vecs will mark the index: 0
  • Dicts will mark the named index: key

The list of paths will be .-separated

❗Consider the performance/memory impact, because PSL assertions are already quite runtime-heavy

@veewee veewee added the Type: Enhancement Most issues will probably ask for additions or changes. label Jun 27, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Type: Enhancement Most issues will probably ask for additions or changes.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants