fireproofsocks / dto

Data Transfer Object (DTO) in PHP using JSON Schema
77 stars 12 forks source link

Error on property chaining #12

Closed dzhiryakov closed 6 years ago

dzhiryakov commented 6 years ago

On this page https://github.com/fireproofsocks/dto/wiki/Ambiguous this sample don't work:

class BlogPostDto extends \Dto\Dto
{
    protected $schema = [
        'type' => 'object',
        'properties' => [
            'title' => ['type' => 'string'],
            'content' => ['type' => 'string'],
            'custom_fields' => [
                'type' => 'object',
                'additionalProperties' => ['type' => 'string']
            ]
        ] 
    ];
}

$post = new BlogPostDto();
$post->title = 'New Film Released!';
$post->content = 'The story...';
$post->custom_fields->release_date = 'Next Saturday';

When i use this example it throw exception Dto\Exceptions\InvalidKeyException: The key "custom_fields" does not exist in this DTO.

PHP 7.1.13

fireproofsocks commented 6 years ago

Good catch. One solution to this is to define a default value in the default property. That way the instance of the DTO will always have the properties it needs (even if they are empty).

e.g.

class BlogPostDto extends \Dto\Dto
{
    protected $schema = [
        'type' => 'object',
        'properties' => [
            'title' => ['type' => 'string'],
            'content' => ['type' => 'string'],
            'custom_fields' => [
                'type' => 'object',
                'additionalProperties' => ['type' => 'string']
            ]
        ],
        'default' => [
            'custom_fields' => []
        ]
    ];
}
fireproofsocks commented 6 years ago

I have updated the example and added an explanation.

dzhiryakov commented 6 years ago

Thanks! Now is work fine.