ziadoz / awesome-php

A curated list of amazingly awesome PHP libraries, resources and shiny things.
Do What The F*ck You Want To Public License
30.95k stars 5.08k forks source link

added Dsheiko\Validate library #890

Closed dsheiko closed 4 years ago

dsheiko commented 6 years ago

Added a link to a validation library for testing primitive and complex types against a contract

VarCI-bot commented 6 years ago

This pull request adds the following suggestion:

-- Automated response by Var.CI :robot:

josegonzalez commented 6 years ago

How is this better/different than any of the existing solutions?

dsheiko commented 6 years ago

@josegonzalez I don't claim it's better, but different:

1) Dead-simple to write custom validators

class IsBool extends ValidateAbstract
{
    public static function test($value)
    {
        return is_bool($value);
    }
}

and corresponding exceptions:

class Exception extends \Dsheiko\Validate\Exception
{
    public static $tpl = '{value} is not a boolean';
}

2) Even easier to extend a validator

class Nickname extends \Dsheiko\Validate\IsString
{
    protected static $options = [ "minLength" => 4, "maxLength" => 16, "notEmpty" => true ];
}

3) One can test complex types like key-value arrays:

use \Dsheiko\Validate;

$params = [
  "email" => "john@snow.io",
  "password" => "******",
];

Validate::map($params, [
    "email" => ["mandatory", "IsEmail"],
    "password" => ["mandatory", "IsString" => ["minLength" => 6, "maxLength" => 128]],
    "rememberMe" => ["optional", "IsBool" ],
]);

4) One can do with it Design by Contract

use \Dsheiko\Validate;

function login($email, $password)
{
    Validate::contract([
            $email,
            $password
        ], [
        [
            "IsEmail",
            "IsString"=> [ "minLength" => 6, "maxLength" => 32, "notEmpty" => true ],
        ],
    ]);
    // do login
}

// may throw
// Dsheiko\Validate\IsString\Exception
// Dsheiko\Validate\IsString\minLength\Exception
// Dsheiko\Validate\IsString\maxLength\Exception
// Dsheiko\Validate\IsEmail\Exception