dashifen/validator

一个接口和抽象类,用于生产验证数据的对象。

安装: 3,983

依赖者: 0

建议者: 0

安全性: 0

星标: 0

关注者: 2

分支: 0

公开问题: 0

类型:项目

3.0.0 2021-08-26 18:05 UTC

README

在这里,我们定义了一个用于验证器的接口,以及一个抽象类,可以从中构建基于字段名验证数据的具体对象。目标:标准化Dash在他们的工作中创建验证器的方式。

安装

composer require dashifen/validator

使用

您可以选择扩展 AbstractValidator 对象,或者简单地在自己的实现中实现 AbstractInterface。该接口定义了两个方法

  1. canValidate - 返回一个布尔值,告诉调用范围是否可以根据 $field 参数进行验证。
  2. isValid - 根据其 $field 标签返回一个关于 $value 是否有效的布尔值。

AbstractValidator 实现了这两个方法,同时要求您定义第三个方法:一个受保护的 getValidationMethod 方法。它返回另一个方法的名字,这个方法假定是同一个对象,可以验证标记为 $field 的数据。

示例

在这个示例中,我们假设应用程序的字段命名规范是使用连字符命名法。

class Validator extends AbstractValidator {
    protected function getValidationMethod(string $field): string {
      
        // to convert a kebab-case $field to a function name, we want to 
        // convert it to StudlyCaps.  so, first, we convert from kebab-case to 
        // camelCase and then we ucfirst() the camelCase string to make it 
        // studly.  finally, we add the word "validate."  Thus, a start-date
        // field becomes startDate, then StartDate, and finally we return 
        // transformStartDate.
  
        $camelCase = preg_replace_callback("/-([a-z])/", function (array $matches): string {
            return strtoupper($matches[1]);
        }, $field);
      
        return "validate" . ucfirst($camelCase);
    }

    private function validateStartDate(string $date): bool {
      
        // what we want to do is make sure that our date appears valid.
        // we're less concerned with format (a transform can standardize 
        // that).  here, we just want to know that what we have might be
        // a date which is a good job for strtotime()!
  
        return strtotime($date) !== false;
    }
}

上面的这个小类代表了一个简单的基于 AbstractValidator 的具体对象,该对象位于本存储库中。抽象对象的 canValidateisValid 方法的实现确保我们使用 getValidationMethod 来识别一个可以转换由 $field 标记的数据的方法的名字,然后在我们需要时调用该方法,返回其结果。