Symfony OptionsResolver with multi dimensional array support
PHP >= 7.2
$ composer require sauls/options-resolver
{
"require": {
"sauls/options-resolver": "^1.0"
}
}
Standard usage can be found at Symfony OptionsResolver official documentation.
The associative array support is added by using a dot notation
array indexes.
To define the associative options, use dot notated
array indexes.
$resolver->setDefined['nested.name', 'nested.value', 'nested.deep.type'];
Allowed types are added using dot notation
index.
$resolver->addAllowedType('nested.name', ['string']);
$resolver->addAllowedType('nested.value', ['int']);
Allowed values are added using dot notation
index.
$resolver->addAllowedValues('nested.deep.type', ['one', 'two', 'three']);
Default options can be added as dot notation
index or associative array
.
$resolver->setDefaults(
[
'nested.name' => 'Hello world!',
'nested.value' => 100,
'nested.deep.type' => 'one',
]
);
// Or
$resolver->setDefaults(
[
'nested' => [
'name' => 'Hello world!',
'value' => 100,
'deep' => [
'type' => 'one',
],
],
]
);
Passing array to resolve options can contain either the dot notation
indexes or associative
array.
$resolver->resolve(
[
'nested.name' => 'Resolve me!',
'nested.value' => 500,
'nested.deep.type' => 'two',
]
);
// Or
$resolver->resolve(
[
'nested' => [
'name' => 'Resolve me!',
'value' => 500,
'deep' => [
'type' => 'two',
],
]
]
);
All exceptions will return what is wrong with your associative option using dot notation
. For example:
The option "nested.deep.type" with value "four" is invalid. Accepted values are: "one", "two", "three".
The option "nested.value" with value "wrong" is expected to be of type "int", but is of type "string".
The required option "nested.value" is missing.
The option "nested.deep.nmae" does not exist. Defined options are: "nested.deep.name", "nested.name", "nested.type", "nested.value", "text", "type".