coolephp/options-resolver

Elegant verification class initialization options and configuration. - 优雅的校验类初始化选项、配置。

v1.0.0 2021-02-24 03:07 UTC

This package is auto-updated.

Last update: 2024-10-24 11:33:47 UTC


README

Elegant verification class initialization options and configuration. - 优雅的校验类初始化选项、配置。

Tests Check & fix styling codecov Latest Stable Version Total Downloads License

Requirement

  • PHP >= 7.2

Installation

$ composer require coolephp/options-resolver -vvv

Usage

Example class

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');
        });
    }
}

Initialization

All options passed verification

$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,
  ),
))

Option failed verification

$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

Testing

$ composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.