PHP code example of abdulsalamalkhatib / laravel-guardian

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

    

abdulsalamalkhatib / laravel-guardian example snippets


DB::transaction(function () use ($payment) {
    $payment->update(['status' => 'paid']);

    Http::post($gatewayUrl, [
        'payment_id' => $payment->id,
    ]);
});

DB::transaction(function () {
    $this->paymentService->charge();
});

// ...

public function charge(): void
{
    $this->gateway->capture();
}

public function capture(): void
{
    Http::post(...);
}

DB::transaction(function () use ($payment) {
    $payment->update(['status' => 'paid']);

    SendPaymentWebhook::dispatch($payment->id)->afterCommit();
});

$wallet = Wallet::findOrFail($walletId);
$wallet->balance += $amount;
$wallet->save();

DB::transaction(function () use ($walletId, $amount) {
    $wallet = Wallet::query()
        ->whereKey($walletId)
        ->lockForUpdate()
        ->firstOrFail();

    $wallet->balance += $amount;
    $wallet->save();
});

Wallet::whereKey($walletId)->increment('balance', $amount);

$wallet = Wallet::findOrFail($walletId);
$delta = $targetBalance - $wallet->balance;
$wallet->increment('balance', $delta);

if ($withdrawal->status === 'pending') {
    $withdrawal->status = 'approved';
    $withdrawal->save();
}

final class PlayerResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->id,
            'phone' => $this->phone,
        ];
    }
}

return [
    'phone' => Str::mask($this->phone, '*', 3),
];

return [
    // Relative to the scanned project root so standalone CLI works without booting Laravel.
    'paths' => ['app'],

    'fail_on' => 'high',
    'minimum_confidence' => 'medium',

    'rules' => [
        'GUA-001' => [
            'enabled' => true,
            'queue_after_commit' => null,
            'custom_effects' => [
                App\Payments\AcmeGateway::class.'::capture',
            ],
        ],

        'GUA-002' => [
            'enabled' => true,
            'critical_fields' => [
                App\Models\Wallet::class => ['balance', 'bonus_balance'],
                App\Models\Withdrawal::class => ['status'],
            ],
            'trusted_distributed_locks' => false,
        ],

        'GUA-003' => [
            'enabled' => true,
            'sensitive_fields' => [
                App\Models\Player::class => [
                    'phone',
                    'email',
                    'date_of_birth',
                ],
            ],
            'resource_models' => [
                App\Http\Resources\PlayerResource::class => App\Models\Player::class,
            ],
            'sanitizers' => [
                Illuminate\Support\Str::class.'::mask',
            ],
        ],
    ],
];

// guardian-ignore GUA-003: account owner explicitly requested this field
return response()->json([
    'phone' => $player->phone,
]);

use Guardian\Attributes\GuardianIgnore;

#[GuardianIgnore(
    rule: 'GUA-003',
    reason: 'Internal authenticated endpoint restricted to fraud operations',
)]
final class FraudResource extends JsonResource
{
    // ...
}

use Guardian\Attributes\GuardianAllowsSensitive;

#[GuardianAllowsSensitive(
    fields: ['phone'],
    reason: 'The authenticated account owner explicitly requested their own profile phone number.',
)]
public function toArray($request): array
{
    return ['phone' => $this->phone];
}

use Guardian\Application\GuardianRegistry;
use Guardian\Contracts\Plugin;

final class PaymentsGuardianPlugin implements Plugin
{
    public function register(GuardianRegistry $registry): void
    {
        $registry
            ->rule(new ProviderIdempotencyRule())
            ->effectProvider(new AcmePaymentEffectProvider())
            ->sanitizer(new InternalTokenRedactor())
            ->concurrencyGuard(new WalletMutexGuard());
    }
}
bash
php artisan guardian:scan
bash
php artisan guardian:scan
php artisan guardian:baseline
php artisan guardian:list
php artisan guardian:explain GUA-001
php artisan guardian:doctor