• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

用 symfony/options-resolver 优雅的校验类初始化选项

互联网 diligentman 2天前 4次浏览

示例类

use SymfonyComponentOptionsResolverOptionsResolver;

/**
 * Class Email
 * composer require symfony/options-resolver
 */
class Email
{
    /**
     * Email constructor.
     *
     * @param  array  $options
     */
    public function __construct(array $options = [])
    {
        $this->configureOptions($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');
        });
    }

    /**
     * @param  array  $options
     * @param  Closure  $closure
     */
    public function configureOptions(array $options, Closure $closure)
    {
        $resolver = new OptionsResolver;
        $closure($resolver);
        $this->options = $resolver->resolve($options);
    }
}

正确的选贤

$email = new Email([
    'host'     => 'smtp.example.org',
    'username' => 'user',
    'password' => 'password',
    'port'     => 25,
]);

var_export($email);
Email::__set_state(array(
    'options' =>
        array (
            'host' => 'smtp.example.org',
            'username' => 'user',
            'password' => 'password',
            'port' => 25,
        ),
))

未通过校验的选项

$email = new Email([
    'host'     => 'smtp.example.org',
    'username' => 'user',
    'password' => 'password',
    'port'     => '25', // 注意这里
]);

var_export($email);
PHP Fatal error:  Uncaught SymfonyComponentOptionsResolverExceptionInvalidOptionsException: The option "port" with value "25" is expected to be of type "int", but is of type "string".

总结

个人觉得可使用该 symfony/options-resolver 组件较好的对开发第三方 sdk 的客户端类初始化参数进行校验,例如个人适配的 Yii 极光推送扩展包 – yii-jpush 中的应用。


程序员灯塔
转载请注明原文链接:用 symfony/options-resolver 优雅的校验类初始化选项
喜欢 (0)