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

String to DateTime returns \Nette\Utils\Arrays error #44

Closed
vitek-dev opened this issue Aug 13, 2021 · 1 comment
Closed

String to DateTime returns \Nette\Utils\Arrays error #44

vitek-dev opened this issue Aug 13, 2021 · 1 comment

Comments

@vitek-dev
Copy link

Bug Description

I am not sure, if I am using this right, but I am trying to convert input string to result DateTime object

Steps To Reproduce

https://fiddle.nette.org/nette/#4f2cd78abf

class Foo {
    public \DateTime $bar;
}

$processor = new \Nette\Schema\Processor;
$processor->process(
    \Nette\Schema\Expect::structure([
        'bar' => \Nette\Schema\Expect::string()->castTo('DateTime')
    ])->castTo(Foo::class),
    [
        'bar' => '2021-01-01',
    ]
);

Will result in the error:

Nette\Utils\Arrays::toObject(): Argument #1 ($array) must be of type iterable, string given, called in ...../vendor/nette/schema/src/Schema/Elements/Base.php on line 174

Expected Behavior

Input string will be successfully mapped to target class DateTime property.

@SeriousKen
Copy link

SeriousKen commented Feb 3, 2022

I just came across this and I think the way cast works isn't properly explained in the documentation. All it does is instantiate an object and then map an array to public properties. It also won't work with any type that has constructor arguments.

I think you should use normalization - the following works:

$schema = Expect::structure([
    'created_at' => Expect::type(DateTime::class)->before(function ($date) {
        return new DateTime($data);
    }),
]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants