Skip to content

Docs ‐ Configurator

Isaac Sai edited this page Jan 21, 2024 · 2 revisions

Introduction to Configurator

When building USSD application, you may want to group related configuration to make them simple and easy to reuse. Configurators help us do that. For instance, you an have your configurator define the response class to use, the exception handler to use, the initial state to use and many more.

Creating a configurator.

php artisan ussd:configurator AfricasTalkingConfigurator

Implement want configuration it should load.

<?php

namespace App\Ussd\Configurators;

use App\Ussd\BriefExceptionHandler;
use App\Ussd\VerboseExceptionHandler;
use App\Ussd\Responses\AfricasTalkingResponse;
use Sparors\Ussd\Context;
use Sparors\Ussd\Contracts\Configurator;
use Sparors\Ussd\Ussd;

class AfricasTalkingConfigurator implements Configurator
{
    public function configure(Ussd $ussd): void
    {
        $lastText = request('text') ?? '';

        if (strlen($lastText) > 0) {
            $lastText = explode('*', $lastText);
            $lastText = end($lastText);
        }

        $ussd->useResponse(AfricasTalkingResponse::class)
            ->useContext(
                Context::create(
                    request('sessionId'),
                    request('phoneNumber'),
                    $lastText
                )->with([
                    'phone_number' => request('phoneNumber')
                ])
            )->unless(
                config('app.env') === 'production',
                callback: function (Ussd $ussd) {
                    $ussd->useExceptionHandler(VerboseExceptionHandler::class);
                },
                fallback: function (Ussd $ussd) {
                    $ussd->useExceptionHandler(BriefExceptionHandler::class);
                }
            );
    }
}
Clone this wiki locally