示例類
use Symfony\Component\OptionsResolver\OptionsResolver;
class Email
{
private $options;
/**
* Email constructor.
*
* @param array $options
*/
public function __construct(array $options = [])
{
$this->setOptions($options);
}
/**
* Configuration options.
*
* @param \Closure $closure
* @param null $object
*
* @return array
*/
protected function configureOptions(array $options, Closure $closure, $object = null)
{
$resolver = new OptionsResolver();
$closure($resolver);
if ($object instanceof Closure) {
return $object()->options = $resolver->resolve($options);
}
if (is_object($object)) {
return $object->options = $resolver->resolve($options);
}
if (is_string($object) && class_exists($object)) {
$object = new $object();
return $object->options = $resolver->resolve($options);
}
return $resolver->resolve($options);
}
/**
* @return mixed
*/
public function getOptions()
{
return $this->options;
}
/**
* @param array $options
*/
public function setOptions(array $options): void
{
$this->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');
});
}
}
選項通過校驗
$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 Symfony\Component\OptionsResolver\Exception\InvalidOptionsException: 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 中的應用。
本作品採用《CC 協議》,轉載必須註明作者和本文連結
No practice, no gain in one's wit.
我的 Gitub