summaryrefslogtreecommitdiff
path: root/app/Core/Cli.php
blob: 13533b9a1b16c184fd1e799f7e0333295b394b3a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php

namespace Core;

use Closure;

/**
 * CLI class
 *
 * @package core
 * @author  Frederic Guillot
 */
class Cli
{
    /**
     * Default command name
     *
     * @access public
     * @var    string
     */
    public $default_command = 'help';

    /**
     * List of registered commands
     *
     * @access private
     * @var    array
     */
    private $commands = array();

    /**
     *
     *
     * @access public
     * @param  string    $command      Command name
     * @param  Closure   $callback     Command callback
     */
    public function register($command, Closure $callback)
    {
        $this->commands[$command] = $callback;
    }

    /**
     * Execute a command
     *
     * @access public
     * @param  string   $command   Command name
     */
    public function call($command)
    {
        if (isset($this->commands[$command])) {
            $this->commands[$command]();
            exit;
        }
    }

    /**
     * Determine which command to execute
     *
     * @access public
     */
    public function execute()
    {
        if (php_sapi_name() !== 'cli') {
            die('This script work only from the command line.');
        }

        if ($GLOBALS['argc'] === 1) {
            $this->call($this->default_command);
        }

        $this->call($GLOBALS['argv'][1]);
        $this->call($this->default_command);
    }
}