Wednesday, March 9, 2022

[FIXED] Symfony OptionResolver: how to check that of two options only one is set

Issue

I have to validate the configuration of the Amazon MWS ListOrders call.

This call accepts both CreatedAfter and LastUpdatedAfter, but only one of the two, not both at the same time.

So, how can I check this condition with OptionResolver?

I think I can do something like this:

$resolver = new OptionsResolver();
$resolver->setDefined(['CreatedAfter', 'LastUpdatedAfter']);
$resolver->setAllowedTypes([...]);

But at this point how can I check the condition that only one is set?

I would like to do this during the $resolver->resolve() call.

Or should have I first resolve the options and then check that only one of them is set using the is*() methods?


Solution

... only one of the two, not both at the same time.

For validate that before you can use them, use setNormalizer():

$resolver->setDefined(['CreatedAfter', 'LastUpdatedAfter']);

$resolver->setNormalizer('CreatedAfter', function (Options $options, $value) {
    if (null === $value xor null === $options['LastUpdatedAfter']) {
        return value;
    }

    throw new \InvalidArgumentException('Both are null or both are provided');
});


Answered By - yceruto

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.