PHP code example of thepublicgood / yerp

1. Go to this page and download the library: Download thepublicgood/yerp 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/ */

    

thepublicgood / yerp example snippets


use TPG\Yerp\Rules;

class User
{
    #[Rules\Required]
    public string $firstName;
    #[Rules\Nullable]
    public ?string $lastName = null;
    #[Rules\Required, Rules\Email]
    public string $emailAddress;
    #[Rules\Boolean(true)]
    public boolean $active;
}

class UserController
{
    public function create()
    {
        // Create a new object instance
        $user = new User();
        $user->firstName = 'John';
        $user->lastName = 'Doe';
        $user->emailAddress = '[email protected]';
        $user->active = false;

        // Pass to the validator
        $validated = (new Validator($user))->validate();
    }
}

$validated = (new Validator($user))->validate();

$validated->property('firstName')->passed();

$validated->property('firstName')->failed();

$validated->property('firstName', Rule\Required::class)->passed();

#[Rule\Nullable, Rules\Email(last: true), Rule\Equal('[email protected]')]
public string $emailAddress;

#[Rules\Email(failure: 'Must be a valid email address')]
public string $email;

$validated->property('email', Rules\Email::class)->message();

#[Rules\Email(
    success: 'The email address is valid!',    // Success
    failure: 'Must be a valid email address',  // Failed
)]
public string $email;

#[Rules\Required]
property ?string $someString;

#[Rules\Alpha]
property string $someString;

#[Rules\ArrayKey('test')]
property array $someArray;

#[Rules\Boolean(true)]
property bool $mustBeTrue;

#[Rules\Equal('expected')]
propert ?string $someString;

#[Rules\Email]
property string $emailAddress;

#[Rules\In(['a', 'b', 'c'])]
property string $someString;

#[Rules\Length(min: 5, max: 20)]
property string $someString;

#[Rules\Numeric]
property string $someString;

#[Rules\Regex('/^test$/')]
property string $regexString;

namespace CustomRules;

use Attribute;
use TPG\Yerp\Rules\AbstractRule;
use TPG\Yerp\Result;

#[Attribute]
class HyphenatedRule extends AbstractRule
{
    public function validate(mixed $value): Result
    {
        return $this->getResult(str_contains((string)$value, '-'));
    }
}


use CustomRules\Hyphenated;

class Article
{
    public string $title;
    #[HyphenatedRule]
    public string $slug;
}

namespace CustomRules;

use Attribute;
use TPG\Yerp\Rules\AbstractRule;
use TPG\Yerp\Result;

use DelimitedRule extends AbstractRule
{
    public function __construct(protected string $delimiter = ',')
    {
    }

    public function validate(string $value): Result
    {
        return $this->getResult(str_contains($value, $this->delimited));
    }
}