PHP code example of moe-mizrak / validator-guard

1. Go to this page and download the library: Download moe-mizrak/validator-guard 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/ */

    

moe-mizrak / validator-guard example snippets


// class UserService
#[IntervalGuard(lowerBound: 100, operator: '<=', upperBound: 10000)] // Transaction amount (method result) must be between 100 and 10,000
public function getTransactionAmount(int $transactionId): float
{
    // Logic of transaction amount calculation
}

$userService = app(UserService::class);

$transactionId = 1344;
$amount = $userService->getTransactionAmount($transactionId); 

return [
    /**
     * Here add the attributes that are used for Validation Guard
     */
    'attributes' => [
        // Attributes that will be handled before method execution
        'before' => [
            AllowedValuesGuard::class,
            DateGuard::class,
            CallbackGuard::class,
        ],
        // Attributes that will be handled after method execution
        'after' => [
            IntervalGuard::class,
            ArrayKeysExistGuard::class,
        ]
    ],

    /**
     * Here add all classes that you use attribute validation in order to bind them to ValidatorGuardCore in Service Provider.
     * Basically whenever these classes are resolved by container, we initiate ValidatorGuardCore to mimic them as a wrapper and handle validation.
     * ! Note: You do NOT need to add classes that you use valguard helper method (Check the Usage section for more details).
     */
    'class_list' => [
    ],

    /**
     * Enable throwing exceptions in case of validation failure
     */
    'throw_exceptions' => env('VALIDATOR_GUARD_THROW_EXCEPTIONS', true),

    /**
     * Enable logging exceptions in case of validation failure
     */
    'log_exceptions' => env('VALIDATOR_GUARD_LOG_EXCEPTIONS', false),

    /**
     * Set an option for default channel for logging so that it can be configured when needed.
     */
    'log_channel' => env('VALIDATOR_GUARD_LOG_CHANNEL', 'stack'),
]

// class UserService
#[IntervalGuard(lowerBound: 100, operator: '<=', upperBound: 10000)] // Transaction amount (method result) must be between 100 and 10,000
public function getTransactionAmount(int $transactionId): float
{
    // Logic of transaction amount calculation
}

$userService = new UserService(); // It does NOT have to be resolved by the container

$transactionId = 1344;
// Call the method by wrapping user service with valguard helper
$amount = valguard($userService)->getTransactionAmount($transactionId); 
/*
 * If the transaction amount is not between 100 and 10,000, the exception will be thrown/logged (based on throwing or logging enabled in config).
 * If the transaction amount is between 100 and 10,000, the method will be executed and give the result.
 */

"class_list" => [
    UserService::class,
]

// class UserService
#[IntervalGuard(lowerBound: 100, operator: '<=', upperBound: 10000)] // Transaction amount (method result) must be between 100 and 10,000
public function getTransactionAmount(int $transactionId): float
{
    // Logic of transaction amount calculation
}

// Resolve UserService from the container
$userService = app(UserService::class);

// Call the method
$transactionId = 1344;
$amount = $userService->getTransactionAmount($transactionId); 
/*
 * If the transaction amount is not between 100 and 10,000, the exception will be thrown/logged (based on throwing or logging enabled in config).
 * If the transaction amount is between 100 and 10,000, the method will be executed and give the result.
 */

// class UserService
#[IntervalGuard(lowerBound: 100, operator: '<=', upperBound: 10000)] // Transaction amount (method result) must be between 100 and 10,000
public function getTransactionAmount(int $transactionId): float
{
    // Logic of transaction amount calculation
}

// Initiate UserService class
$userService = new UserService();

$transactionId = 1344;
// Call the method
$amount = valguard($userService)->getTransactionAmount($transactionId); 

#[IntervalGuard(lowerBound: 10, operator: '<')]
#[IntervalGuard(lowerBound: 30, operator: '>=')]
public function getTransactionAmount(int $transactionId): float
{
    // Logic of transaction amount calculation
}

    #[IntervalGuard(lowerBound: 18, operator: '<=')] // Age must be bigger than 18 (inclusive)
    public function calculateUserAge(): int
    {
        // Logic of user age calculation
    }
    

    #[IntervalGuard(lowerBound: 0, operator: '<=', upperBound: 5)] // Maximum 5 login attempts allowed
    public function loginAttempts(string $username): int
    {
        // Logic of login attempts calculation
    }
    

    #[IntervalGuard(lowerBound: 100, operator: '<')] // Credit score must be bigger than 800
    public function getCreditScore(int $userId): int
    {
        // Logic of credit score calculation
    }
    

// class UserService
public function createEvent(
    #[DateGuard(paramPosition: 0, boundary: DateGuard::FUTURE)] string $eventDate
): void {
    // Logic to create an event
}

// Initiate UserService class
$userService = new UserService();

$eventDate = '2023-12-31';
// Call the method
valguard($userService)->createEvent($eventDate); 

    public function subscribeUser(
        int $userId,
        #[DateGuard(paramPosition: 1, boundary: DateGuard::FUTURE)] string $subscriptionEndDate
    ): void {
        // Logic to subscribe user
    }
    

    public function fetchHistoricalData(
    #[DateGuard(paramPosition: 0, boundary: DateGuard::PAST)] string $queryDate
    ): array {
        // Fetch data for the given date
    }
    

    public function scheduleEvent(
        #[DateGuard(paramPosition: 0, boundary: DateGuard::WEEKDAYS)] string $eventDate
    ): void {
        // Logic to schedule an event
    }
    

    public function makeReservation(
        bool $isRoomAvailable,
        #[DateGuard(
            paramPosition: 1,
            boundary: DateGuard::BETWEEN,
            range: ['lower_bound' => '2023-01-01', 'upper_bound' => '2023-12-31'])
        ] string $reservationDate
    ): void {
        // Logic to make a reservation
    }
    

// class UserService
public function createEvent(
    #[AllowedValuesGuard(paramPosition: 0, values: ['meeting', 'party', 'wedding'])] string $eventType
): void {
    // Logic to create an event
}

// Initiate UserService class
$userService = new UserService();

$eventType = 'meeting';
// Call the method
valguard($userService)->createEvent($eventType); 

    public function selectLanguage(
        #[AllowedValuesGuard(paramPosition: 0, values: ['en', 'tr', 'de', 'fr'])] string $language
    ): void {
        // Logic to select a language
    }
    

    public function assignRole(
        int $userId,
        #[AllowedValuesGuard(paramPosition: 1, values: ['admin', 'user', 'guest'])] string $role
    ): void {
        // Logic to assign a role
    }
    

    public function makePayment(
        #[AllowedValuesGuard(paramPosition: 0, values: ['credit_card', 'paypal', 'bank_transfer'])] string $paymentMethod
    ): void {
        // Logic to make a payment
    }
    

    public function updateOrderStatus(
        int $orderId,
        #[AllowedValuesGuard(paramPosition: 1, values: ['pending', 'shipped', 'delivered', 'cancelled'])] string $status,
        #[AllowedValuesGuard(paramPosition: 2, values: ['false', 'true'])] bool $isPaid
    ): bool {
        // Logic to update order status
    }
    

// class UserService
#[CallbackGuard(
    className: PaymentGateway::class,
    methodName: 'isPaymentMethodSupported',
    params: ['credit_card', 'US'],
    expectedResult: true
)]
public function processPayment(int $paymentId): void 
{
    // Logic of payment processing
}

// Initiate UserService class
$userService = new UserService();

$paymentId = 134;
// Call the method
valguard($userService)->processPayment($paymentId); 

    #[CallbackGuard(
        className: PaymentService::class,
        methodName: 'getPaymentMethods',
        expectedResult: new PaymentMethodsDTO([
            'credit_card',
            'paypal',
            'bank_transfer',
        ])
    )]
    public function processPayment(int $paymentId): void 
    {
        // Logic of payment processing
    }
    

    #[CallbackGuard(
        className: PermissionService::class,
        methodName: 'allowedPermissions',
        params: ['admin'],
        expectedResult: ['read', 'write', 'delete']
    )]
    public function getUserData(int $userId): array
    {
        // Logic to get user data
    }
    

    #[CallbackGuard(
        className: BalanceService::class,
        methodName: 'balanceStatus',
        expectedResult: "active"
    )]
    public function withdraw(): bool 
    {
        // Logic to withdraw
    }
    

    #[CallbackGuard(
        className: SubscriptionService::class,
        methodName: 'isSubscriptionActive',
        params: ["monthly"],
        expectedResult: true
    )]
    public function fetchSubscriptionData(): array
    {
        // Fetch subscription data
    }
    

// class UserService
#[ArrayKeysExistGuard(
    keys: ['name', 'email'],
    inMethodResult: true
)] // name and email keys must exist in the method result array
public function getUserData(int $userId): array
{
    // Logic to get user data
}

// Initiate UserService class
$userService = new UserService();

$userId = 134;
// Call the method
$userData = valguard($userService)->getUserData($userId); 

    #[ArrayKeysExistGuard(
        keys: ['status', 'data'],
        inMethodResult: true
    )]
    public function fetchApiResponse(): array 
    {
        // API call logic
    }
    

    #[ArrayKeysExistGuard(
        keys: ['product_id', 'quantity'],
        inMethodResult: true
    )]
    public function getOrderData(int $orderId): array
    {
        // Logic to get order data
    }
    

    #[ArrayKeysExistGuard(
        keys: ['user_id', 'email'],
        inParam: true,
        paramPosition: 0
    )]
    public function handleRequest(array $request): void 
    {
        // Handle request logic
    }
    

    #[ArrayKeysExistGuard(
        keys: ['amount', 'currency', 'payment_method'],
        inParam: true,
        paramPosition: 1
    )]
    public function initiatePayment(int $paymentId, array $payload): void {
        // Payment processing logic
    }
    

use Illuminate\Support\Arr;
use MoeMizrak\ValidatorGuardCore\Data\MethodContextData;
use MoeMizrak\ValidatorGuardCore\Contracts\ValidationAttributeInterface;

#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
final readonly class NewAttribute implements ValidationAttributeInterface
{
    public function __construct(
        private int $paramPosition, // We get the param position to retrieve the parameter value from method params, this is the way we know which parameter to validate since name of the method parameter is not accessible
        private string $stringValue
    ) {}

    public function handle(MethodContextData $methodContextData): bool
    {
        // Validation logic
        $result = $methodContextData->methodResult; // Method result
        $methodParams = $methodContextData->methodParams; // Method parameters
        
        $paramData = Arr::get($methodParams, $this->paramPosition); // Get the parameter value from method params
        
        return ! is_null($paramData) && $result === $this->stringValue;
    }
}

'attributes' => [
    
    'before' => [
        AllowedValuesGuard::class,
        DateGuard::class,
        CallbackGuard::class,
    ],
    
    'after' => [
        IntervalGuard::class,
        ArrayKeysExistGuard::class,
        NewAttribute::class, // Add the new attribute to the after array (or before array based on the 

// class UserService
#[NewAttribute(paramPosition: 0, stringValue: 'test')]
public function testMethod(string $param): string
{
    return 'test';
}

// Initiate UserService class
$userService = new UserService();

$param = 'validParam';
// Call the method
$result = valguard($userService)->testMethod($param);
bash
php artisan vendor:publish --tag=validator-guard