Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
AbstractDispatcher
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
3 / 3
7
100.00% covered (success)
100.00%
1 / 1
 setDefaultAction
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getDefaultAction
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 dispatch
100.00% covered (success)
100.00%
8 / 8
100.00% covered (success)
100.00%
1 / 1
5
1<?php
2declare(strict_types=1);
3/**
4 * Pop PHP Framework (https://www.popphp.org/)
5 *
6 * @link       https://github.com/popphp/popphp-framework
7 * @author     Nick Sagona, III <nick@popphp.org>
8 * @copyright  Copyright (c) 2009-2026 Nick Sagona, III
9 * @license    https://www.popphp.org/license     New BSD License
10 */
11
12/**
13 * @namespace
14 */
15namespace Pop\Dispatch;
16
17/**
18 * Abstract dispatcher class
19 *
20 * @category   Pop
21 * @package    Pop
22 * @author     Nick Sagona, III <nick@popphp.org>
23 * @copyright  Copyright (c) 2009-2026 Nick Sagona, III
24 * @license    https://www.popphp.org/license     New BSD License
25 * @version    5.0.0
26 */
27abstract class AbstractDispatcher implements DispatchableInterface
28{
29
30    /**
31     * Default action
32     * @var string
33     */
34    protected string $defaultAction = 'error';
35
36    /**
37     * Set the default action
38     *
39     * @param  string $default
40     * @return static
41     */
42    public function setDefaultAction(string $default): static
43    {
44        $this->defaultAction = $default;
45        return $this;
46    }
47
48    /**
49     * Get the default action
50     *
51     * @return string
52     */
53    public function getDefaultAction(): string
54    {
55        return $this->defaultAction;
56    }
57
58    /**
59     * Dispatch the controller based on the action
60     *
61     * @param  ?string $action
62     * @param  ?array  $params
63     * @throws Exception
64     * @return void
65     */
66    public function dispatch(?string $action = null, ?array $params = null): void
67    {
68        // Dispatch route action
69        if (($action !== null) && method_exists($this, $action)) {
70            if ($params !== null) {
71                call_user_func_array([$this, $action], array_values($params));
72            } else {
73                $this->$action();
74            }
75        // Else, fallback to default route action
76        } else if (method_exists($this, $this->defaultAction)) {
77            $action = $this->defaultAction;
78            $this->$action();
79        } else {
80            throw new Exception("The action to handle the route is not defined.");
81        }
82    }
83
84}