PHP code example of aegisora / guardian

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

    

aegisora / guardian example snippets


$guardian
    ->that($value)
    ->must(FirstRule::create())
    ->must(SecondRule::create())
    ->validate();

Aegisora\RuleContract\RuleInterface

->must(
    EmailRule::create(),
    new InvalidEmailException()
)

GuardianExecutingRuleException

use Aegisora\Guardian\Guardian;

$guardian = new Guardian();

$guardian->check(
    $value,
    FooRule::create()
);

GuardianValidationException

use Aegisora\Guardian\Guardian;
use App\Exceptions\InvalidValueException;

$guardian = new Guardian();

$guardian->check(
    $value,
    FooRule::create(),
    new InvalidValueException()
);

use Aegisora\Guardian\Guardian;

$guardian = new Guardian();

$guardian
    ->that($value)
    ->must(FirstRule::create())
    ->must(SecondRule::create())
    ->validate();

$guardian
    ->that($value)
    ->must(
        EmailRule::create(),
        new InvalidEmailException()
    )
    ->must(
        PasswordRule::create(),
        new WeakPasswordException()
    )
    ->validate();



namespace App\Registration;

final class RegisterUserCommand
{
    private string $email;
    private string $password;
    private int $age;

    public function __construct(
        string $email,
        string $password,
        int $age
    ) {
        $this->email = $email;
        $this->password = $password;
        $this->age = $age;
    }

    public function getEmail(): string
    {
        return $this->email;
    }

    public function getPassword(): string
    {
        return $this->password;
    }

    public function getAge(): int
    {
        return $this->age;
    }
}



namespace App\Registration\Rules;

use Aegisora\RuleContract\Models\Context;
use Aegisora\RuleContract\Models\Result;
use Aegisora\RuleContract\Rule;
use App\Registration\RegisterUserCommand;

final class ValidEmailRule extends Rule
{
    protected function executeValidate(Context $context): Result
    {
        $command = $context->getValue();

        if (!$command instanceof RegisterUserCommand) {
            return Result::invalid('invalid_registration_command');
        }

        if (filter_var($command->getEmail(), FILTER_VALIDATE_EMAIL) === false) {
            return Result::invalid('invalid_email');
        }

        return Result::valid();
    }
}



namespace App\Registration\Rules;

use Aegisora\RuleContract\Models\Context;
use Aegisora\RuleContract\Models\Result;
use Aegisora\RuleContract\Rule;
use App\Registration\RegisterUserCommand;

final class StrongPasswordRule extends Rule
{
    protected function executeValidate(Context $context): Result
    {
        $command = $context->getValue();

        if (!$command instanceof RegisterUserCommand) {
            return Result::invalid('invalid_registration_command');
        }

        $password = $command->getPassword();

        if (strlen($password) < 12) {
            return Result::invalid('weak_password');
        }

        if (preg_match('/[A-Z]/', $password) !== 1) {
            return Result::invalid('weak_password');
        }

        if (preg_match('/[0-9]/', $password) !== 1) {
            return Result::invalid('weak_password');
        }

        return Result::valid();
    }
}



namespace App\Registration\Rules;

use Aegisora\RuleContract\Models\Context;
use Aegisora\RuleContract\Models\Result;
use Aegisora\RuleContract\Rule;
use App\Registration\RegisterUserCommand;

final class AdultUserRule extends Rule
{
    private const MINIMUM_AGE = 18;

    protected function executeValidate(Context $context): Result
    {
        $command = $context->getValue();

        if (!$command instanceof RegisterUserCommand) {
            return Result::invalid('invalid_registration_command');
        }

        if ($command->getAge() < self::MINIMUM_AGE) {
            return Result::invalid('user_is_too_young');
        }

        return Result::valid();
    }
}



namespace App\Registration;

use Aegisora\Guardian\Guardian;
use App\Registration\Exceptions\InvalidEmailException;
use App\Registration\Exceptions\UserIsTooYoungException;
use App\Registration\Exceptions\WeakPasswordException;
use App\Registration\Rules\AdultUserRule;
use App\Registration\Rules\StrongPasswordRule;
use App\Registration\Rules\ValidEmailRule;

final class RegisterUserService
{
    private Guardian $guardian;
    private UserRepository $users;

    public function __construct(
        Guardian $guardian,
        UserRepository $users
    ) {
        $this->guardian = $guardian;
        $this->users = $users;
    }

    public function register(RegisterUserCommand $command): User
    {
        $this->guardian
            ->that($command)
            ->must(
                new ValidEmailRule(),
                new InvalidEmailException()
            )
            ->must(
                new StrongPasswordRule(),
                new WeakPasswordException()
            )
            ->must(
                new AdultUserRule(),
                new UserIsTooYoungException()
            )
            ->validate();

        return $this->users->create(
            $command->getEmail(),
            password_hash($command->getPassword(), PASSWORD_DEFAULT),
            $command->getAge()
        );
    }
}



use Aegisora\Guardian\Exceptions\GuardianExecutingRuleException;
use App\Registration\Exceptions\InvalidEmailException;
use App\Registration\Exceptions\UserIsTooYoungException;
use App\Registration\Exceptions\WeakPasswordException;
use App\Registration\RegisterUserCommand;

try {
    $user = $registerUserService->register(
        new RegisterUserCommand(
            '[email protected]',
            'SecurePassword123',
            25
        )
    );

    return [
        'status' => 201,
        'user_id' => $user->getId(),
    ];
} catch (InvalidEmailException $exception) {
    return [
        'status' => 422,
        'error' => 'Invalid email address.',
    ];
} catch (WeakPasswordException $exception) {
    return [
        'status' => 422,
        'error' => 'Password is too weak.',
    ];
} catch (UserIsTooYoungException $exception) {
    return [
        'status' => 422,
        'error' => 'User must be at least 18 years old.',
    ];
} catch (GuardianExecutingRuleException $exception) {
    return [
        'status' => 500,
        'error' => 'Validation rule execution failed.',
    ];
}

check($value, RuleInterface $rule, Throwable $exception = null): void

that($value): GuardianExecutor

must(RuleInterface $rule, Throwable $exception = null): self

validate(): void

throw new GuardianValidationException(
    $failedRuleCode
);

RuleException → GuardianExecutingRuleException

if (!$value) {
}

$guardian->check($value, SomeRule::create());

new InvalidUserEmailException()