Elegant verification class initialization options and configuration. - 优雅的校验类初始化选项、配置。
- PHP >= 7.2
$ composer require coolephp/options-resolver -vvv
use Symfony\Component\OptionsResolver\OptionsResolver;
class Email
{
private $options;
/**
* Email constructor.
*
* @param array $options
*/
public function __construct(array $options = [])
{
$this->setOptions($options);
}
/**
* @return mixed
*/
public function getOptions()
{
return $this->options;
}
/**
* @param array $options
*/
public function setOptions(array $options): void
{
$this->options = configure_options($options, function (OptionsResolver $resolver) {
$resolver->setDefaults([
'host' => 'smtp.example.org',
'username' => 'user',
'password' => 'password',
'port' => 25,
]);
$resolver->setRequired(['host', 'username', 'password', 'port']);
$resolver->setAllowedTypes('host', 'string');
$resolver->setAllowedTypes('username', 'string');
$resolver->setAllowedTypes('password', 'string');
$resolver->setAllowedTypes('port', 'int');
});
}
}
$options = [
'host' => 'smtp.example.org',
'username' => 'user',
'password' => 'password',
'port' => 25,
];
$email = new Email($options);
var_export($email);
Email::__set_state(array(
'options' =>
array (
'host' => 'smtp.example.org',
'username' => 'user',
'password' => 'password',
'port' => 25,
),
))
$options = [
'host' => 'smtp.example.org',
'username' => 'user',
'password' => 'password',
'port' => '25',
];
$email = new Email($options);
var_export($email);
PHP Fatal error: Uncaught Symfony\Component\OptionsResolver\Exception\InvalidOptionsException: The option "port" with value "25" is expected to be of type "int", but is of type "string". in /Users/yaozm/Downloads/options-resolver/vendor/symfony/options-resolver/OptionsResolver.php:1030
$ composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.