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

[OptionsResolver] Allow giving a callback as an allowedValue to OptionsResolver #8375

Merged
merged 1 commit into from Jan 7, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/Symfony/Component/OptionsResolver/OptionsResolver.php
Expand Up @@ -294,8 +294,14 @@ private function validateOptionsCompleteness(array $options)
private function validateOptionValues(array $options)
{
foreach ($this->allowedValues as $option => $allowedValues) {
if (isset($options[$option]) && !in_array($options[$option], $allowedValues, true)) {
throw new InvalidOptionsException(sprintf('The option "%s" has the value "%s", but is expected to be one of "%s"', $option, $options[$option], implode('", "', $allowedValues)));
if (isset($options[$option])) {
if (is_array($allowedValues) && !in_array($options[$option], $allowedValues, true)) {
throw new InvalidOptionsException(sprintf('The option "%s" has the value "%s", but is expected to be one of "%s"', $option, $options[$option], implode('", "', $allowedValues)));
}

if (is_callable($allowedValues) && !call_user_func($allowedValues, $options[$option])) {
throw new InvalidOptionsException(sprintf('The option "%s" has the value "%s", which it is not valid', $option, $options[$option]));
}
}
}
}
Expand Down
Expand Up @@ -658,6 +658,45 @@ public function testResolveSucceedsIfOptionRequiredAndValueAllowed()
$this->assertEquals($options, $this->resolver->resolve($options));
}

public function testResolveSucceedsIfValueAllowedCallbackReturnsTrue()
{
$this->resolver->setRequired(array(
'test',
));
$this->resolver->setAllowedValues(array(
'test' => function ($value) {
return true;
},
));

$options = array(
'test' => true,
);

$this->assertEquals($options, $this->resolver->resolve($options));
}

/**
* @expectedException \Symfony\Component\OptionsResolver\Exception\InvalidOptionsException
*/
public function testResolveFailsIfValueAllowedCallbackReturnsFalse()
{
$this->resolver->setRequired(array(
'test',
));
$this->resolver->setAllowedValues(array(
'test' => function ($value) {
return false;
},
));

$options = array(
'test' => true,
);

$this->assertEquals($options, $this->resolver->resolve($options));
}

public function testClone()
{
$this->resolver->setDefaults(array('one' => '1'));
Expand Down