定制 simple-as-fuck/php-validator 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

simple-as-fuck/php-validator

Composer 安装命令:

composer require simple-as-fuck/php-validator

包简介

README 文档

README

Validator for php variables with intuitive rule chain, put inside mixed and you in the end get requested type.

Installation

composer require simple-as-fuck/php-validator

Support

If any PHP platform requirements in composer.json ends with security support, consider package version as unsupported except last version.

PHP supported versions.

Usage

/** @var mixed $value */
$value = $config->get('some_value_name');

$rules = \SimpleAsFuck\Validator\Factory\Validator::make($value, 'Config "some_value_name" value');
$validValue = $rules->string()->notEmpty()->notNull();
// string value is not dump into validation message similarly to:
// https://www.php.net/manual/en/class.sensitiveparameter.php
$validSensitiveValue = $rules->string(sensitiveValue: true)->notEmpty()->notNull();
/*
 * now you have in $validValue really not empty string and even phpstan know the type without any annoying annotation
 * if validation failed \UnexpectedValueException('Config "some_value_name" value must ...') is thrown from rule chain
 */
$stringValues = $rules->array()->ofString()->notNull();

/*
 * shorter notation, value name in validator factory is optional and here is unnecessary,
 * validation exception is thrown in same line as config key name
 * so you should this find in your stacktrace and know than something is wrong in your config file
 */
\SimpleAsFuck\Validator\Factory\Validator::make($config->get('some_value_name'))->string()->notEmpty()->notNull();

This validation can be applied into any php variable and is appropriately usable for json decoded data. All rules have declared types for next rule in chain so not look for any rules list, your IDE should hint you available rules and rule chain is designed for preventing redundant rules or rule combination which do not make sense.

Validation exception type changing

You can change exception type throw from rule chain while validation failed by inject yours exception factory.

If you want throw some HTTP exception for validation http request beware of this validator is not suitable for validation user inputs.

First: validator fail in first unsuccessful rule in nested structure and throw only one exception even if there can be more validation fails.

Second: validator throw highly generated messages which can be for user unreadable and translation support is not in plan, for us developers messages should be fine.

Third: realise than we write in PHP server side application so the app should return data in some API format and view data should some weird javascript, native or mobile client app. Yes I know than even pc games are rendered in cloud but client pc has also some computing power and if client logic and html is rendered on server is only wasting of its power.

final class ExceptionFactory extends \SimpleAsFuck\Validator\Factory\Exception
{
    /**
     * @param non-empty-string $message
     */
    public function create(string $message): \Exception
    {
        return new \RuntimeException($message);
    }
}

$exceptionFactory = new \ExceptionFactory();

$value = new \SimpleAsFuck\Validator\Model\Validated(1);

$rules = new \SimpleAsFuck\Validator\Rule\General\Rules($exceptionFactory, 'variable', $value);

$validValue = $rules->int()->notNull();

Validation rule caching

You can cache result of validation rules by cache method.

It can fix performance if validator work with complex data structure or call some parsing functions.

$result = \SimpleAsFuck\Validator\Factory\Validator::make('some parsed string')
    ->string()
    ->parseRegex('/^(?P<some>.+) (?P<parsed>.+) .*/$')
    // with cache regex parsing and previous rules are called only once
    // even if validation continue in multiple new rule branches
    ->cache()
;

// every match load data from parsed cache inside ParseRegex rule
$result->match('some')->notNull();
$result->match('parsed')->notNull();

Cache is turned off by default to reduce memory consumption.

Customization

User defined rule

You can create your rule and put it in the end of rule chain and this allow you to run some yours validation.

If you are validating something what is widely standardized, consider contribute into rule chain, for more nicely writing it or share some rule with others.

/**
 * @implements \SimpleAsFuck\Validator\Rule\Custom\UserDefinedRule<string, string>
 */
final class GandalfRule implements \SimpleAsFuck\Validator\Rule\Custom\UserDefinedRule
{
    /**
     * @param string $value
     */
    public function validate($value): ?string
    {
        throw new \SimpleAsFuck\Validator\Model\ValueMust('not pass');
    }
}

$rules = \SimpleAsFuck\Validator\Factory\Validator::make('');

$rules->string()->custom(new \GandalfRule())->notNull();

User class rule

Validator rule chain always return some specific type so generic object is not in option. You are able to convert object into some class with validated structure.

/**
 * @implements \SimpleAsFuck\Validator\Rule\Custom\UserClassRule<YourClass>
 */
final class YourClassRule implements \SimpleAsFuck\Validator\Rule\Custom\UserClassRule
{
    public function validate(\SimpleAsFuck\Validator\Rule\Object\ObjectRule $object): YourClass
    {
        return new YourCass(
            $object->property('propertyName')->string()->max(30)->notNull()
            // some next property ...
        );
    }
}

/** @var mixed $data */

$rules = \SimpleAsFuck\Validator\Factory\Validator::make($data);

$yourObject = $rules->object()->class(new YourClassRule())->notNull();
$yourObjects = $rules->array()->ofClass(new YourClassRule())->notNull();

simple-as-fuck/php-validator 适用场景与选型建议

simple-as-fuck/php-validator 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 187.99k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 11 月 20 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 simple-as-fuck/php-validator 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 simple-as-fuck/php-validator 我们能提供哪些服务?
定制开发 / 二次开发

基于 simple-as-fuck/php-validator 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 187.99k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 9
  • 依赖项目数: 5
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 2
  • 开发语言: PHP

其他信息

  • 授权协议: Unlicense
  • 更新时间: 2021-11-20