PHP code example of simple-as-fuck / php-validator
1. Go to this page and download the library: Download simple-as-fuck/php-validator library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
simple-as-fuck / php-validator example snippets
/** @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();
/*
* 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();
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();
/**
* @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();
/**
* @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();
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.