1#!/usr/bin/env php
2<?php
3
4use dokuwiki\Extension\PluginController;
5use splitbrain\phpcli\CLI;
6use splitbrain\phpcli\Colors;
7use splitbrain\phpcli\Options;
8
9if(!defined('DOKU_INC')) define('DOKU_INC', realpath(dirname(__FILE__) . '/../') . '/');
10define('NOSESSION', 1);
11require_once(DOKU_INC . 'inc/init.php');
12
13class PluginCLI extends CLI {
14
15    /**
16     * Register options and arguments on the given $options object
17     *
18     * @param Options $options
19     * @return void
20     */
21    protected function setup(Options $options) {
22        $options->setHelp('Excecutes Plugin command line tools');
23        $options->registerArgument('plugin', 'The plugin CLI you want to run. Leave off to see list', false);
24    }
25
26    /**
27     * Your main program
28     *
29     * Arguments and options have been parsed when this is run
30     *
31     * @param Options $options
32     * @return void
33     */
34    protected function main(Options $options) {
35        global $argv;
36        $argv = $options->getArgs();
37
38        if($argv) {
39            $plugin = $this->loadPlugin($argv[0]);
40            if($plugin !== null) {
41                $plugin->run();
42            } else {
43                $this->fatal('Command {cmd} not found.', ['cmd' => $argv[0]]);
44            }
45        } else {
46            echo $options->help();
47            $this->listPlugins();
48        }
49    }
50
51    /**
52     * List available plugins
53     */
54    protected function listPlugins() {
55        /** @var PluginController $plugin_controller */
56        global $plugin_controller;
57
58        echo "\n";
59        echo "\n";
60        echo $this->colors->wrap('AVAILABLE PLUGINS:', Colors::C_BROWN);
61        echo "\n";
62
63        $list = $plugin_controller->getList('cli');
64        sort($list);
65        if(!count($list)) {
66            echo $this->colors->wrap("  No plugins providing CLI components available\n", Colors::C_RED);
67        } else {
68            $tf = new \splitbrain\phpcli\TableFormatter($this->colors);
69
70            foreach($list as $name) {
71                $plugin = $this->loadPlugin($name);
72                if($plugin === null) continue;
73                $info = $plugin->getInfo();
74
75                echo $tf->format(
76                    [2, '30%', '*'],
77                    ['', $name, $info['desc']],
78                    ['', Colors::C_CYAN, '']
79
80                );
81            }
82        }
83    }
84
85    /**
86     * Instantiate a CLI plugin
87     *
88     * @param string $name
89     * @return \dokuwiki\Extension\CLIPlugin|null
90     */
91    protected function loadPlugin($name) {
92        // execute the plugin CLI
93        $class = "cli_plugin_$name";
94        if(class_exists($class)) {
95            return new $class();
96        }
97        return null;
98    }
99}
100
101// Main
102$cli = new PluginCLI();
103$cli->run();
104