PHP code example of kirschbaum-development / monitor

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

    

kirschbaum-development / monitor example snippets


// A critical operation as a try/catch: no name, no attempt count, no trace, null means declined.
try {
    DB::beginTransaction();
    $charge = $this->stripe->charge($amount);
    DB::commit();
} catch (CardDeclined $e) {
    DB::rollBack();
    Log::warning('card declined: '.$e->getMessage());
    return null;
} catch (\Throwable $e) {
    DB::rollBack();
    Log::error($e);
    throw $e;
}

// The same operation as a control point.
return Monitor::control('payment.charge', $this)
    ->with(['invoice' => $invoice->id, 'amount' => $amount])
    ->profile('external')                                  // retry, breaker and duration limit from config
    ->transaction(retries: 2)
    ->ensure(fn (ChargeResult $r): bool => $r->settled, 'charge must be settled')
    ->recover(CardDeclined::class, fn (CardDeclined $e) => ChargeResult::declined($e->code))
    ->escalate(PagePayments::class)
    ->run(fn () => $this->stripe->charge($amount));

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\Kirschbaum\Monitor\Http\Middleware\StartTrace::class);
})

#[Point('payments.charge_card', profile: 'external')]
final class ChargeCard extends ControlPoint
{
    public function __construct(private readonly Invoice $invoice) {}

    protected function control(Control $control): void
    {
        $control
            ->recover(CardDeclined::class, fn (CardDeclined $e) => ChargeResult::declined($e->code))
            ->ensure(fn (ChargeResult $r): bool => $r->settled, 'charge must be settled')
            ->escalate(PagePayments::class);
    }

    public function context(): array
    {
        return ['invoice' => $this->invoice->id];
    }

    public function handle(StripeClient $stripe): ChargeResult
    {
        return $stripe->charge($this->invoice);
    }
}

ChargeCard::run($invoice);      // the value, or throws what escaped
ChargeCard::attempt($invoice);  // an Outcome: ->status, ->value, ->exception, ->attempts, ->durationMs

Monitor::fake()->failing('payments.charge_card', new CardDeclined('insufficient_funds'));

ChargeCard::run($invoice);

Monitor::assertRecovered('payments.charge_card', from: CardDeclined::class);
Monitor::assertNothingEscalated();
bash
php artisan make:control-point Payments/ChargeCard --profile=external
bash
php artisan monitor:points --check