|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace splitbrain\phpcli; |
| 4 | + |
| 5 | +/** |
| 6 | + * Class CLIBase |
| 7 | + * |
| 8 | + * All base functionality is implemented here. |
| 9 | + * |
| 10 | + * Your commandline should not inherit from this class, but from one of the *CLI* classes |
| 11 | + * |
| 12 | + * @author Andreas Gohr <[email protected]> |
| 13 | + * @license MIT |
| 14 | + */ |
| 15 | +abstract class Base |
| 16 | +{ |
| 17 | + /** @var string the executed script itself */ |
| 18 | + protected $bin; |
| 19 | + /** @var Options the option parser */ |
| 20 | + protected $options; |
| 21 | + /** @var Colors */ |
| 22 | + public $colors; |
| 23 | + |
| 24 | + /** @var array PSR-3 compatible loglevels and their prefix, color, output channel */ |
| 25 | + protected $loglevel = array( |
| 26 | + 'debug' => array('', Colors::C_RESET, STDOUT), |
| 27 | + 'info' => array('ℹ ', Colors::C_CYAN, STDOUT), |
| 28 | + 'notice' => array('☛ ', Colors::C_CYAN, STDOUT), |
| 29 | + 'success' => array('✓ ', Colors::C_GREEN, STDOUT), |
| 30 | + 'warning' => array('⚠ ', Colors::C_BROWN, STDERR), |
| 31 | + 'error' => array('✗ ', Colors::C_RED, STDERR), |
| 32 | + 'critical' => array('☠ ', Colors::C_LIGHTRED, STDERR), |
| 33 | + 'alert' => array('✖ ', Colors::C_LIGHTRED, STDERR), |
| 34 | + 'emergency' => array('✘ ', Colors::C_LIGHTRED, STDERR), |
| 35 | + ); |
| 36 | + |
| 37 | + protected $logdefault = 'info'; |
| 38 | + |
| 39 | + /** |
| 40 | + * constructor |
| 41 | + * |
| 42 | + * Initialize the arguments, set up helper classes and set up the CLI environment |
| 43 | + * |
| 44 | + * @param bool $autocatch should exceptions be catched and handled automatically? |
| 45 | + */ |
| 46 | + public function __construct($autocatch = true) |
| 47 | + { |
| 48 | + if ($autocatch) { |
| 49 | + set_exception_handler(array($this, 'fatal')); |
| 50 | + } |
| 51 | + |
| 52 | + $this->colors = new Colors(); |
| 53 | + $this->options = new Options($this->colors); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Register options and arguments on the given $options object |
| 58 | + * |
| 59 | + * @param Options $options |
| 60 | + * @return void |
| 61 | + * |
| 62 | + * @throws Exception |
| 63 | + */ |
| 64 | + abstract protected function setup(Options $options); |
| 65 | + |
| 66 | + /** |
| 67 | + * Your main program |
| 68 | + * |
| 69 | + * Arguments and options have been parsed when this is run |
| 70 | + * |
| 71 | + * @param Options $options |
| 72 | + * @return void |
| 73 | + * |
| 74 | + * @throws Exception |
| 75 | + */ |
| 76 | + abstract protected function main(Options $options); |
| 77 | + |
| 78 | + /** |
| 79 | + * Execute the CLI program |
| 80 | + * |
| 81 | + * Executes the setup() routine, adds default options, initiate the options parsing and argument checking |
| 82 | + * and finally executes main() - Each part is split into their own protected function below, so behaviour |
| 83 | + * can easily be overwritten |
| 84 | + * |
| 85 | + * @throws Exception |
| 86 | + */ |
| 87 | + public function run() |
| 88 | + { |
| 89 | + if ('cli' != php_sapi_name()) { |
| 90 | + throw new Exception('This has to be run from the command line'); |
| 91 | + } |
| 92 | + |
| 93 | + $this->setup($this->options); |
| 94 | + $this->registerDefaultOptions(); |
| 95 | + $this->parseOptions(); |
| 96 | + $this->handleDefaultOptions(); |
| 97 | + $this->setupLogging(); |
| 98 | + $this->checkArgments(); |
| 99 | + $this->execute(); |
| 100 | + |
| 101 | + exit(0); |
| 102 | + } |
| 103 | + |
| 104 | + // region run handlers - for easier overriding |
| 105 | + |
| 106 | + /** |
| 107 | + * Add the default help, color and log options |
| 108 | + */ |
| 109 | + protected function registerDefaultOptions() |
| 110 | + { |
| 111 | + $this->options->registerOption( |
| 112 | + 'help', |
| 113 | + 'Display this help screen and exit immediately.', |
| 114 | + 'h' |
| 115 | + ); |
| 116 | + $this->options->registerOption( |
| 117 | + 'no-colors', |
| 118 | + 'Do not use any colors in output. Useful when piping output to other tools or files.' |
| 119 | + ); |
| 120 | + $this->options->registerOption( |
| 121 | + 'loglevel', |
| 122 | + 'Minimum level of messages to display. Default is ' . $this->colors->wrap($this->logdefault, Colors::C_CYAN) . '. ' . |
| 123 | + 'Valid levels are: debug, info, notice, success, warning, error, critical, alert, emergency.', |
| 124 | + null, |
| 125 | + 'level' |
| 126 | + ); |
| 127 | + } |
| 128 | + |
| 129 | + /** |
| 130 | + * Handle the default options |
| 131 | + */ |
| 132 | + protected function handleDefaultOptions() |
| 133 | + { |
| 134 | + if ($this->options->getOpt('no-colors')) { |
| 135 | + $this->colors->disable(); |
| 136 | + } |
| 137 | + if ($this->options->getOpt('help')) { |
| 138 | + echo $this->options->help(); |
| 139 | + exit(0); |
| 140 | + } |
| 141 | + } |
| 142 | + |
| 143 | + /** |
| 144 | + * Handle the logging options |
| 145 | + */ |
| 146 | + protected function setupLogging() |
| 147 | + { |
| 148 | + $level = $this->options->getOpt('loglevel', $this->logdefault); |
| 149 | + if (!isset($this->loglevel[$level])) $this->fatal('Unknown log level'); |
| 150 | + foreach (array_keys($this->loglevel) as $l) { |
| 151 | + if ($l == $level) break; |
| 152 | + unset($this->loglevel[$l]); |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + /** |
| 157 | + * Wrapper around the option parsing |
| 158 | + */ |
| 159 | + protected function parseOptions() |
| 160 | + { |
| 161 | + $this->options->parseOptions(); |
| 162 | + } |
| 163 | + |
| 164 | + /** |
| 165 | + * Wrapper around the argument checking |
| 166 | + */ |
| 167 | + protected function checkArgments() |
| 168 | + { |
| 169 | + $this->options->checkArguments(); |
| 170 | + } |
| 171 | + |
| 172 | + /** |
| 173 | + * Wrapper around main |
| 174 | + */ |
| 175 | + protected function execute() |
| 176 | + { |
| 177 | + $this->main($this->options); |
| 178 | + } |
| 179 | + |
| 180 | + // endregion |
| 181 | + |
| 182 | + // region logging |
| 183 | + |
| 184 | + /** |
| 185 | + * Exits the program on a fatal error |
| 186 | + * |
| 187 | + * @param \Exception|string $error either an exception or an error message |
| 188 | + * @param array $context |
| 189 | + */ |
| 190 | + public function fatal($error, array $context = array()) |
| 191 | + { |
| 192 | + $code = 0; |
| 193 | + if (is_object($error) && is_a($error, 'Exception')) { |
| 194 | + /** @var Exception $error */ |
| 195 | + $this->logMessage('debug', get_class($error) . ' caught in ' . $error->getFile() . ':' . $error->getLine()); |
| 196 | + $this->logMessage('debug', $error->getTraceAsString()); |
| 197 | + $code = $error->getCode(); |
| 198 | + $error = $error->getMessage(); |
| 199 | + |
| 200 | + } |
| 201 | + if (!$code) { |
| 202 | + $code = Exception::E_ANY; |
| 203 | + } |
| 204 | + |
| 205 | + $this->logMessage('critical', $error, $context); |
| 206 | + exit($code); |
| 207 | + } |
| 208 | + |
| 209 | + /** |
| 210 | + * Normal, positive outcome (This is not a PSR-3 level) |
| 211 | + * |
| 212 | + * @param string $string |
| 213 | + * @param array $context |
| 214 | + */ |
| 215 | + public function success($string, array $context = array()) |
| 216 | + { |
| 217 | + $this->logMessage('success', $string, $context); |
| 218 | + } |
| 219 | + |
| 220 | + /** |
| 221 | + * @param string $level |
| 222 | + * @param string $message |
| 223 | + * @param array $context |
| 224 | + */ |
| 225 | + protected function logMessage($level, $message, array $context = array()) |
| 226 | + { |
| 227 | + // is this log level wanted? |
| 228 | + if (!isset($this->loglevel[$level])) return; |
| 229 | + |
| 230 | + /** @var string $prefix */ |
| 231 | + /** @var string $color */ |
| 232 | + /** @var resource $channel */ |
| 233 | + list($prefix, $color, $channel) = $this->loglevel[$level]; |
| 234 | + if (!$this->colors->isEnabled()) $prefix = ''; |
| 235 | + |
| 236 | + $message = $this->interpolate($message, $context); |
| 237 | + $this->colors->ptln($prefix . $message, $color, $channel); |
| 238 | + } |
| 239 | + |
| 240 | + /** |
| 241 | + * Interpolates context values into the message placeholders. |
| 242 | + * |
| 243 | + * @param $message |
| 244 | + * @param array $context |
| 245 | + * @return string |
| 246 | + */ |
| 247 | + protected function interpolate($message, array $context = array()) |
| 248 | + { |
| 249 | + // build a replacement array with braces around the context keys |
| 250 | + $replace = array(); |
| 251 | + foreach ($context as $key => $val) { |
| 252 | + // check that the value can be casted to string |
| 253 | + if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) { |
| 254 | + $replace['{' . $key . '}'] = $val; |
| 255 | + } |
| 256 | + } |
| 257 | + |
| 258 | + // interpolate replacement values into the message and return |
| 259 | + return strtr((string)$message, $replace); |
| 260 | + } |
| 261 | + |
| 262 | + // endregion |
| 263 | +} |
0 commit comments