Dispatcher.php 1.2 KB
<?php

namespace Lackoxygen\ExceptionPush;

use Lackoxygen\ExceptionPush\Contracts\AgentInterface;
use Lackoxygen\ExceptionPush\Contracts\CallbackInterface;

class Dispatcher implements CallbackInterface
{
    /**
     * @return \Closure|null
     */
    public function config(): ?\Closure
    {
        $dispatcher = ExceptionPush::config('callbacks.dispatcher');

        if ($dispatcher instanceof \Closure) {
            return $dispatcher;
        }

        return null;
    }

    /**
     * @return \Closure
     */
    public function default(): \Closure
    {
        return function ($agents, $body) {
            foreach ($agents as $agent) {
                if ($agent instanceof AgentInterface) {
                    try {
                        $agent->report($body);
                    } catch (\Exception $exception) {
                        app('log')->error($exception->getMessage());
                    }
                }
            }
        };
    }

    /**
     * @return \Closure
     */
    public static function callback(): \Closure
    {
        $that = new static;

        if ($dispatcher = $that->config()) {
            return $dispatcher;
        }

        return $that->default();
    }
}