<?php
use Symfony\Component\OptionsResolver\OptionsResolver;
/*
* set possible options
*/
$resolver = new OptionsResolver();
$resolver->setDefaults([
'enabled' => true,
]);
// array in first param is deprecated since 2.6
$resolver->setAllowedValues('enabled', [true, false]);
// setOptional is deprecated since 2.6. Use setDefined instead
$resolver->setDefined(['id']);
$resolver->setRequired(['class']);
// array in first param is deprecated since 2.6
$resolver->setAllowedTypes('class', 'ArrayAccess');
/*
* options to resolve
*/
$validOpt1 = [
'class' => new ArrayObject(),
'id' => 3,
];
$validOpt2 = [
'class' => new ArrayObject(),
'enabled' => false,
];
$invalidOpt1 = [
'class' => new EmptyIterator(),
];
$invalidOpt2 = [
'class' => new ArrayObject(),
'foo' => true,
];
/*
* resolve options
*/
// valid options
dump($resolver->resolve($validOpt1));
dump($resolver->resolve($validOpt2));
// invalid options
try {
$resolver->resolve($invalidOpt1);
} catch (Exception $e) {
dump($e->getMessage());
}
try {
$resolver->resolve($invalidOpt2);
} catch (Exception $e) {
dump($e->getMessage());
}
^ array:3 [
"enabled" => true
"class" => ArrayObject {#1391
-storage: []
: false
: false
: "ArrayIterator"
}
"id" => 3
]
^ array:2 [
"enabled" => false
"class" => ArrayObject {#1392
-storage: []
: false
: false
: "ArrayIterator"
}
]
^ "The option "class" with value EmptyIterator is expected to be of type "ArrayAccess", but is of type "EmptyIterator"."
^ "The option "foo" does not exist. Defined options are: "class", "enabled", "id"."