项目作者: coolephp

项目描述 :
Elegant verification class initialization options and configuration. - 优雅的校验类初始化选项、配置。
高级语言: PHP
项目地址: git://github.com/coolephp/options-resolver.git
创建时间: 2021-02-23T09:08:42Z
项目社区:https://github.com/coolephp/options-resolver

开源协议:MIT License

下载


options-resolver

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

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

Requirement

  • PHP >= 7.2

Installation

  1. $ composer require coolephp/options-resolver -vvv

Usage

Example class

  1. use Symfony\Component\OptionsResolver\OptionsResolver;
  2. class Email
  3. {
  4. private $options;
  5. /**
  6. * Email constructor.
  7. *
  8. * @param array $options
  9. */
  10. public function __construct(array $options = [])
  11. {
  12. $this->setOptions($options);
  13. }
  14. /**
  15. * @return mixed
  16. */
  17. public function getOptions()
  18. {
  19. return $this->options;
  20. }
  21. /**
  22. * @param array $options
  23. */
  24. public function setOptions(array $options): void
  25. {
  26. $this->options = configure_options($options, function (OptionsResolver $resolver) {
  27. $resolver->setDefaults([
  28. 'host' => 'smtp.example.org',
  29. 'username' => 'user',
  30. 'password' => 'password',
  31. 'port' => 25,
  32. ]);
  33. $resolver->setRequired(['host', 'username', 'password', 'port']);
  34. $resolver->setAllowedTypes('host', 'string');
  35. $resolver->setAllowedTypes('username', 'string');
  36. $resolver->setAllowedTypes('password', 'string');
  37. $resolver->setAllowedTypes('port', 'int');
  38. });
  39. }
  40. }

Initialization

All options passed verification

  1. $options = [
  2. 'host' => 'smtp.example.org',
  3. 'username' => 'user',
  4. 'password' => 'password',
  5. 'port' => 25,
  6. ];
  7. $email = new Email($options);
  8. var_export($email);
  1. Email::__set_state(array(
  2. 'options' =>
  3. array (
  4. 'host' => 'smtp.example.org',
  5. 'username' => 'user',
  6. 'password' => 'password',
  7. 'port' => 25,
  8. ),
  9. ))

Option failed verification

  1. $options = [
  2. 'host' => 'smtp.example.org',
  3. 'username' => 'user',
  4. 'password' => 'password',
  5. 'port' => '25',
  6. ];
  7. $email = new Email($options);
  8. var_export($email);
  1. 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

  1. $ 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.