Skip to content

Commit bf5d9d3

Browse files
Elias Van Ootegemwouterj
Elias Van Ootegem
authored andcommitted
Document typed arrays in optionsresolver
1 parent f96625e commit bf5d9d3

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

components/options_resolver.rst

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,43 @@ is thrown::
340340
In sub-classes, you can use :method:`Symfony\\Component\\OptionsResolver\\OptionsResolver::addAllowedTypes`
341341
to add additional allowed types without erasing the ones already set.
342342

343+
You can specify an array of a specific type as an allowed option. The expected type is
344+
validated in the same way as before (``is_<type>()`` or an ``instanceof`` check).
345+
Only for an array, this is done recursively. If you expect an option to be an array of
346+
``DateTime`` instances or a numeric array, you can specify this as follows::
347+
348+
// ...
349+
class Mailer
350+
{
351+
// ...
352+
public function configureOptions(OptionsResolver $resolver)
353+
{
354+
// ...
355+
$resolver->setAllowedTypes('dates', 'DateTime[]');
356+
$resolver->setAllowedTypes('ports', 'int[]');
357+
}
358+
}
359+
360+
Because the OptionsResolver will validate typed arrays recurively, it is possible to
361+
resolve multi-dimensional arrays, too::
362+
363+
// ...
364+
class Mailer
365+
{
366+
// ...
367+
public function configureOptions(OptionsResolver $resolver)
368+
{
369+
// ...
370+
//allowed type is a 2D array of string values
371+
$resolver->setAllowedTypes('hosts', 'string[][]');
372+
}
373+
}
374+
375+
.. versionadded:: 3.1
376+
Before Symfony 3.1, the allowed types had to be scalar values, qualified classes
377+
or interfaces. The only way to ensure the values of an array were of the right type
378+
was to use a normalizer.
379+
343380
Value Validation
344381
~~~~~~~~~~~~~~~~
345382

0 commit comments

Comments
 (0)