The OptionsResolver Component

The OptionsResolver Component

The OptionsResolver component is an improved replacement for the array_replace PHP function. It allows you to create an options system with required options, defaults, validation (type, value), normalization and more.

Installation

  1. $ composer require symfony/options-resolver

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Usage

Imagine you have a Mailer class which has four options: host, username, password and port:

  1. class Mailer
  2. {
  3. protected $options;
  4. public function __construct(array $options = [])
  5. {
  6. $this->options = $options;
  7. }
  8. }

When accessing the $options, you need to add some boilerplate code to check which options are set:

  1. class Mailer
  2. {
  3. // ...
  4. public function sendMail($from, $to)
  5. {
  6. $mail = ...;
  7. $mail->setHost($this->options['host'] ?? 'smtp.example.org');
  8. $mail->setUsername($this->options['username'] ?? 'user');
  9. $mail->setPassword($this->options['password'] ?? 'pa$$word');
  10. $mail->setPort($this->options['port'] ?? 25);
  11. // ...
  12. }
  13. }

Also, the default values of the options are buried in the business logic of your code. Use the array_replace to fix that:

  1. class Mailer
  2. {
  3. // ...
  4. public function __construct(array $options = [])
  5. {
  6. $this->options = array_replace([
  7. 'host' => 'smtp.example.org',
  8. 'username' => 'user',
  9. 'password' => 'pa$$word',
  10. 'port' => 25,
  11. ], $options);
  12. }
  13. }

Now all four options are guaranteed to be set, but you could still make an error like the following when using the Mailer class:

  1. $mailer = new Mailer([
  2. 'usernme' => 'johndoe', // 'username' is wrongly spelled as 'usernme'
  3. ]);

No error will be shown. In the best case, the bug will appear during testing, but the developer will spend time looking for the problem. In the worst case, the bug might not appear until it’s deployed to the live system.

Fortunately, the Symfony\Component\OptionsResolver\OptionsResolver class helps you to fix this problem:

  1. use Symfony\Component\OptionsResolver\OptionsResolver;
  2. class Mailer
  3. {
  4. // ...
  5. public function __construct(array $options = [])
  6. {
  7. $resolver = new OptionsResolver();
  8. $resolver->setDefaults([
  9. 'host' => 'smtp.example.org',
  10. 'username' => 'user',
  11. 'password' => 'pa$$word',
  12. 'port' => 25,
  13. ]);
  14. $this->options = $resolver->resolve($options);
  15. }
  16. }

Like before, all options will be guaranteed to be set. Additionally, an Symfony\Component\OptionsResolver\Exception\UndefinedOptionsException is thrown if an unknown option is passed:

  1. $mailer = new Mailer([
  2. 'usernme' => 'johndoe',
  3. ]);
  4. // UndefinedOptionsException: The option "usernme" does not exist.
  5. // Defined options are: "host", "password", "port", "username"

The rest of your code can access the values of the options without boilerplate code:

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function sendMail($from, $to)
  6. {
  7. $mail = ...;
  8. $mail->setHost($this->options['host']);
  9. $mail->setUsername($this->options['username']);
  10. $mail->setPassword($this->options['password']);
  11. $mail->setPort($this->options['port']);
  12. // ...
  13. }
  14. }

It’s a good practice to split the option configuration into a separate method:

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function __construct(array $options = [])
  6. {
  7. $resolver = new OptionsResolver();
  8. $this->configureOptions($resolver);
  9. $this->options = $resolver->resolve($options);
  10. }
  11. public function configureOptions(OptionsResolver $resolver)
  12. {
  13. $resolver->setDefaults([
  14. 'host' => 'smtp.example.org',
  15. 'username' => 'user',
  16. 'password' => 'pa$$word',
  17. 'port' => 25,
  18. 'encryption' => null,
  19. ]);
  20. }
  21. }

First, your code becomes easier to read, especially if the constructor does more than processing options. Second, sub-classes may now override the `configureOptions() method to adjust the configuration of the options:

  1. // ...
  2. class GoogleMailer extends Mailer
  3. {
  4. public function configureOptions(OptionsResolver $resolver)
  5. {
  6. parent::configureOptions($resolver);
  7. $resolver->setDefaults([
  8. 'host' => 'smtp.google.com',
  9. 'encryption' => 'ssl',
  10. ]);
  11. }
  12. }

Required Options

If an option must be set by the caller, pass that option to setRequired(). For example, to make the host option required, you can do:

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. $resolver->setRequired('host');
  9. }
  10. }

If you omit a required option, a Symfony\Component\OptionsResolver\Exception\MissingOptionsException will be thrown:

  1. $mailer = new Mailer();
  2. // MissingOptionsException: The required option "host" is missing.

The setRequired() method accepts a single name or an array of option names if you have more than one required option:

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. $resolver->setRequired(['host', 'username', 'password']);
  9. }
  10. }

Use isRequired() to find out if an option is required. You can use getRequiredOptions() to retrieve the names of all required options:

  1. // ...
  2. class GoogleMailer extends Mailer
  3. {
  4. public function configureOptions(OptionsResolver $resolver)
  5. {
  6. parent::configureOptions($resolver);
  7. if ($resolver->isRequired('host')) {
  8. // ...
  9. }
  10. $requiredOptions = $resolver->getRequiredOptions();
  11. }
  12. }

If you want to check whether a required option is still missing from the default options, you can use isMissing(). The difference between this and isRequired() is that this method will return false if a required option has already been set:

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. $resolver->setRequired('host');
  9. }
  10. }
  11. // ...
  12. class GoogleMailer extends Mailer
  13. {
  14. public function configureOptions(OptionsResolver $resolver)
  15. {
  16. parent::configureOptions($resolver);
  17. $resolver->isRequired('host');
  18. // => true
  19. $resolver->isMissing('host');
  20. // => true
  21. $resolver->setDefault('host', 'smtp.google.com');
  22. $resolver->isRequired('host');
  23. // => true
  24. $resolver->isMissing('host');
  25. // => false
  26. }
  27. }

The getMissingOptions() method lets you access the names of all missing options.

Type Validation

You can run additional checks on the options to make sure they were passed correctly. To validate the types of the options, call setAllowedTypes():

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. // specify one allowed type
  9. $resolver->setAllowedTypes('host', 'string');
  10. // specify multiple allowed types
  11. $resolver->setAllowedTypes('port', ['null', 'int']);
  12. // check all items in an array recursively for a type
  13. $resolver->setAllowedTypes('dates', 'DateTime[]');
  14. $resolver->setAllowedTypes('ports', 'int[]');
  15. }
  16. }

You can pass any type for which an is_<type>() function is defined in PHP. You may also pass fully qualified class or interface names (which is checked usinginstanceof). Additionally, you can validate all items in an array recursively by suffixing the type with [].

If you pass an invalid option now, an Symfony\Component\OptionsResolver\Exception\InvalidOptionsException is thrown:

  1. $mailer = new Mailer([
  2. 'host' => 25,
  3. ]);
  4. // InvalidOptionsException: The option "host" with value "25" is
  5. // expected to be of type "string", but is of type "int"

In sub-classes, you can use addAllowedTypes() to add additional allowed types without erasing the ones already set.

Value Validation

Some options can only take one of a fixed list of predefined values. For example, suppose the Mailer class has a transport option which can be one of sendmail, mail and smtp. Use the method setAllowedValues() to verify that the passed option contains one of these values:

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. $resolver->setDefault('transport', 'sendmail');
  9. $resolver->setAllowedValues('transport', ['sendmail', 'mail', 'smtp']);
  10. }
  11. }

If you pass an invalid transport, an Symfony\Component\OptionsResolver\Exception\InvalidOptionsException is thrown:

  1. $mailer = new Mailer([
  2. 'transport' => 'send-mail',
  3. ]);
  4. // InvalidOptionsException: The option "transport" with value "send-mail"
  5. // is invalid. Accepted values are: "sendmail", "mail", "smtp"

For options with more complicated validation schemes, pass a closure which returns true for acceptable values and false for invalid values:

  1. // ...
  2. $resolver->setAllowedValues('transport', function ($value) {
  3. // return true or false
  4. });

In sub-classes, you can use addAllowedValues() to add additional allowed values without erasing the ones already set.

Option Normalization

Sometimes, option values need to be normalized before you can use them. For instance, assume that the host should always start with http://. To do that, you can write normalizers. Normalizers are executed after validating an option. You can configure a normalizer by calling setNormalizer():

  1. use Symfony\Component\OptionsResolver\Options;
  2. // ...
  3. class Mailer
  4. {
  5. // ...
  6. public function configureOptions(OptionsResolver $resolver)
  7. {
  8. // ...
  9. $resolver->setNormalizer('host', function (Options $options, $value) {
  10. if ('http://' !== substr($value, 0, 7)) {
  11. $value = 'http://'.$value;
  12. }
  13. return $value;
  14. });
  15. }
  16. }

The normalizer receives the actual $value and returns the normalized form. You see that the closure also takes an $options parameter. This is useful if you need to use other options during normalization:

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. $resolver->setNormalizer('host', function (Options $options, $value) {
  9. if ('http://' !== substr($value, 0, 7) && 'https://' !== substr($value, 0, 8)) {
  10. if ('ssl' === $options['encryption']) {
  11. $value = 'https://'.$value;
  12. } else {
  13. $value = 'http://'.$value;
  14. }
  15. }
  16. return $value;
  17. });
  18. }
  19. }

To normalize a new allowed value in sub-classes that are being normalized in parent classes use addNormalizer(). This way, the $value argument will receive the previously normalized value, otherwise you can prepend the new normalizer by passing true as third argument.

Default Values that Depend on another Option

Suppose you want to set the default value of the port option based on the encryption chosen by the user of the Mailer class. More precisely, you want to set the port to 465 if SSL is used and to 25 otherwise.

You can implement this feature by passing a closure as the default value of the port option. The closure receives the options as argument. Based on these options, you can return the desired default value:

  1. use Symfony\Component\OptionsResolver\Options;
  2. // ...
  3. class Mailer
  4. {
  5. // ...
  6. public function configureOptions(OptionsResolver $resolver)
  7. {
  8. // ...
  9. $resolver->setDefault('encryption', null);
  10. $resolver->setDefault('port', function (Options $options) {
  11. if ('ssl' === $options['encryption']) {
  12. return 465;
  13. }
  14. return 25;
  15. });
  16. }
  17. }

Caution

The argument of the callable must be type hinted as Options. Otherwise, the callable itself is considered as the default value of the option.

Note

The closure is only executed if the port option isn’t set by the user or overwritten in a sub-class.

A previously set default value can be accessed by adding a second argument to the closure:

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. $resolver->setDefaults([
  9. 'encryption' => null,
  10. 'host' => 'example.org',
  11. ]);
  12. }
  13. }
  14. class GoogleMailer extends Mailer
  15. {
  16. public function configureOptions(OptionsResolver $resolver)
  17. {
  18. parent::configureOptions($resolver);
  19. $resolver->setDefault('host', function (Options $options, $previousValue) {
  20. if ('ssl' === $options['encryption']) {
  21. return 'secure.example.org';
  22. }
  23. // Take default value configured in the base class
  24. return $previousValue;
  25. });
  26. }
  27. }

As seen in the example, this feature is mostly useful if you want to reuse the default values set in parent classes in sub-classes.

Options without Default Values

In some cases, it is useful to define an option without setting a default value. This is useful if you need to know whether or not the user actually set an option or not. For example, if you set the default value for an option, it’s not possible to know whether the user passed this value or if it comes from the default:

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. $resolver->setDefault('port', 25);
  9. }
  10. // ...
  11. public function sendMail($from, $to)
  12. {
  13. // Is this the default value or did the caller of the class really
  14. // set the port to 25?
  15. if (25 === $this->options['port']) {
  16. // ...
  17. }
  18. }
  19. }

You can use setDefined() to define an option without setting a default value. Then the option will only be included in the resolved options if it was actually passed to resolve():

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. $resolver->setDefined('port');
  9. }
  10. // ...
  11. public function sendMail($from, $to)
  12. {
  13. if (array_key_exists('port', $this->options)) {
  14. echo 'Set!';
  15. } else {
  16. echo 'Not Set!';
  17. }
  18. }
  19. }
  20. $mailer = new Mailer();
  21. $mailer->sendMail($from, $to);
  22. // => Not Set!
  23. $mailer = new Mailer([
  24. 'port' => 25,
  25. ]);
  26. $mailer->sendMail($from, $to);
  27. // => Set!

You can also pass an array of option names if you want to define multiple options in one go:

  1. // ...
  2. class Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. $resolver->setDefined(['port', 'encryption']);
  9. }
  10. }

The methods isDefined() and getDefinedOptions() let you find out which options are defined:

  1. // ...
  2. class GoogleMailer extends Mailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. parent::configureOptions($resolver);
  8. if ($resolver->isDefined('host')) {
  9. // One of the following was called:
  10. // $resolver->setDefault('host', ...);
  11. // $resolver->setRequired('host');
  12. // $resolver->setDefined('host');
  13. }
  14. $definedOptions = $resolver->getDefinedOptions();
  15. }
  16. }

Nested Options

Suppose you have an option named spool which has two sub-options type and path. Instead of defining it as a simple array of values, you can pass a closure as the default value of the spool option with a Symfony\Component\OptionsResolver\OptionsResolver argument. Based on this instance, you can define the options under spool and its desired default value:

  1. class Mailer
  2. {
  3. // ...
  4. public function configureOptions(OptionsResolver $resolver)
  5. {
  6. $resolver->setDefault('spool', function (OptionsResolver $spoolResolver) {
  7. $spoolResolver->setDefaults([
  8. 'type' => 'file',
  9. 'path' => '/path/to/spool',
  10. ]);
  11. $spoolResolver->setAllowedValues('type', ['file', 'memory']);
  12. $spoolResolver->setAllowedTypes('path', 'string');
  13. });
  14. }
  15. public function sendMail($from, $to)
  16. {
  17. if ('memory' === $this->options['spool']['type']) {
  18. // ...
  19. }
  20. }
  21. }
  22. $mailer = new Mailer([
  23. 'spool' => [
  24. 'type' => 'memory',
  25. ],
  26. ]);

Nested options also support required options, validation (type, value) and normalization of their values. If the default value of a nested option depends on another option defined in the parent level, add a second Options argument to the closure to access to them:

  1. class Mailer
  2. {
  3. // ...
  4. public function configureOptions(OptionsResolver $resolver)
  5. {
  6. $resolver->setDefault('sandbox', false);
  7. $resolver->setDefault('spool', function (OptionsResolver $spoolResolver, Options $parent) {
  8. $spoolResolver->setDefaults([
  9. 'type' => $parent['sandbox'] ? 'memory' : 'file',
  10. // ...
  11. ]);
  12. });
  13. }
  14. }

Caution

The arguments of the closure must be type hinted as OptionsResolver and Options respectively. Otherwise, the closure itself is considered as the default value of the option.

In same way, parent options can access to the nested options as normal arrays:

  1. class Mailer
  2. {
  3. // ...
  4. public function configureOptions(OptionsResolver $resolver)
  5. {
  6. $resolver->setDefault('spool', function (OptionsResolver $spoolResolver) {
  7. $spoolResolver->setDefaults([
  8. 'type' => 'file',
  9. // ...
  10. ]);
  11. });
  12. $resolver->setDefault('profiling', function (Options $options) {
  13. return 'file' === $options['spool']['type'];
  14. });
  15. }
  16. }

Note

The fact that an option is defined as nested means that you must pass an array of values to resolve it at runtime.

Prototype Options

New in version 5.3: Prototype options were introduced in Symfony 5.3.

There are situations where you will have to resolve and validate a set of options that may repeat many times within another option. Let’s imagine a connections option that will accept an array of database connections with host, database, user and password each.

The best way to implement this is to define the connections option as prototype:

  1. $resolver->setDefault('connections', function (OptionsResolver $connResolver) {
  2. $connResolver
  3. ->setPrototype(true)
  4. ->setRequired(['host', 'database'])
  5. ->setDefaults(['user' => 'root', 'password' => null]);
  6. });

According to the prototype definition in the example above, it is possible to have multiple connection arrays like the following:

  1. $resolver->resolve([
  2. 'connections' => [
  3. 'default' => [
  4. 'host' => '127.0.0.1',
  5. 'database' => 'symfony',
  6. ],
  7. 'test' => [
  8. 'host' => '127.0.0.1',
  9. 'database' => 'symfony_test',
  10. 'user' => 'test',
  11. 'password' => 'test',
  12. ],
  13. // ...
  14. ],
  15. ]);

The array keys (default, test, etc.) of this prototype option are validation-free and can be any arbitrary value that helps differentiate the connections.

Note

A prototype option can only be defined inside a nested option and during its resolution it will expect an array of arrays.

Deprecating the Option

New in version 5.1: The signature of the setDeprecated() method changed fromsetDeprecated(string $option, ?string $message) to `setDeprecated(string $option, string $package, string $version, $message) in Symfony 5.1.

Once an option is outdated or you decided not to maintain it anymore, you can deprecate it using the setDeprecated() method:

  1. $resolver
  2. ->setDefined(['hostname', 'host'])
  3. // this outputs the following generic deprecation message:
  4. // Since acme/package 1.2: The option "hostname" is deprecated.
  5. ->setDeprecated('hostname', 'acme/package', '1.2')
  6. // you can also pass a custom deprecation message (%name% placeholder is available)
  7. ->setDeprecated(
  8. 'hostname',
  9. 'acme/package',
  10. '1.2',
  11. 'The option "hostname" is deprecated, use "host" instead.'
  12. )
  13. ;

Note

The deprecation message will be triggered only if the option is being used somewhere, either its value is provided by the user or the option is evaluated within closures of lazy options and normalizers.

Note

When using an option deprecated by you in your own library, you can pass false as the second argument of the offsetGet() method to not trigger the deprecation warning.

Instead of passing the message, you may also pass a closure which returns a string (the deprecation message) or an empty string to ignore the deprecation. This closure is useful to only deprecate some of the allowed types or values of the option:

  1. $resolver
  2. ->setDefault('encryption', null)
  3. ->setDefault('port', null)
  4. ->setAllowedTypes('port', ['null', 'int'])
  5. ->setDeprecated('port', 'acme/package', '1.2', function (Options $options, $value) {
  6. if (null === $value) {
  7. return 'Passing "null" to option "port" is deprecated, pass an integer instead.';
  8. }
  9. // deprecation may also depend on another option
  10. if ('ssl' === $options['encryption'] && 456 !== $value) {
  11. return 'Passing a different port than "456" when the "encryption" option is set to "ssl" is deprecated.';
  12. }
  13. return '';
  14. })
  15. ;

Note

Deprecation based on the value is triggered only when the option is provided by the user.

This closure receives as argument the value of the option after validating it and before normalizing it when the option is being resolved.

Chaining Option Configurations

In many cases you may need to define multiple configurations for each option. For example, suppose the InvoiceMailer class has an host option that is required and a transport option which can be one of sendmail, mail and smtp. You can improve the readability of the code avoiding to duplicate option name for each configuration using the define() method:

  1. // ...
  2. class InvoiceMailer
  3. {
  4. // ...
  5. public function configureOptions(OptionsResolver $resolver)
  6. {
  7. // ...
  8. $resolver->define('host')
  9. ->required()
  10. ->default('smtp.example.org')
  11. ->allowedTypes('string')
  12. ->info('The IP address or hostname');
  13. $resolver->define('transport')
  14. ->required()
  15. ->default('transport')
  16. ->allowedValues(['sendmail', 'mail', 'smtp']);
  17. }
  18. }

New in version 5.1: The define() andinfo() methods were introduced in Symfony 5.1.

Performance Tweaks

With the current implementation, the configureOptions() method will be called for every single instance of theMailer` class. Depending on the amount of option configuration and the number of created instances, this may add noticeable overhead to your application. If that overhead becomes a problem, you can change your code to do the configuration only once per class:

  1. // ...
  2. class Mailer
  3. {
  4. private static $resolversByClass = [];
  5. protected $options;
  6. public function __construct(array $options = [])
  7. {
  8. // What type of Mailer is this, a Mailer, a GoogleMailer, ... ?
  9. $class = get_class($this);
  10. // Was configureOptions() executed before for this class?
  11. if (!isset(self::$resolversByClass[$class])) {
  12. self::$resolversByClass[$class] = new OptionsResolver();
  13. $this->configureOptions(self::$resolversByClass[$class]);
  14. }
  15. $this->options = self::$resolversByClass[$class]->resolve($options);
  16. }
  17. public function configureOptions(OptionsResolver $resolver)
  18. {
  19. // ...
  20. }
  21. }

Now the Symfony\Component\OptionsResolver\OptionsResolver instance will be created once per class and reused from that on. Be aware that this may lead to memory leaks in long-running applications, if the default options contain references to objects or object graphs. If that’s the case for you, implement a method `clearOptionsConfig() and call it periodically:

  1. // ...
  2. class Mailer
  3. {
  4. private static $resolversByClass = [];
  5. public static function clearOptionsConfig()
  6. {
  7. self::$resolversByClass = [];
  8. }
  9. // ...
  10. }

That’s it! You now have all the tools and knowledge needed to process options in your code.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.