|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace CodeIgniter\Shield\Commands; |
| 6 | + |
| 7 | +use CodeIgniter\CLI\BaseCommand as FrameworkBaseCommand; |
| 8 | +use CodeIgniter\CLI\Commands; |
| 9 | +use CodeIgniter\Shield\Commands\Utils\InputOutput; |
| 10 | +use Psr\Log\LoggerInterface; |
| 11 | + |
| 12 | +abstract class BaseCommand extends FrameworkBaseCommand |
| 13 | +{ |
| 14 | + protected static ?InputOutput $io = null; |
| 15 | + |
| 16 | + /** |
| 17 | + * The group the command is lumped under |
| 18 | + * when listing commands. |
| 19 | + * |
| 20 | + * @var string |
| 21 | + */ |
| 22 | + protected $group = 'Shield'; |
| 23 | + |
| 24 | + public function __construct(LoggerInterface $logger, Commands $commands) |
| 25 | + { |
| 26 | + parent::__construct($logger, $commands); |
| 27 | + |
| 28 | + $this->ensureInputOutput(); |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Asks the user for input. |
| 33 | + * |
| 34 | + * @param string $field Output "field" question |
| 35 | + * @param array|string $options String to a default value, array to a list of options (the first option will be the default value) |
| 36 | + * @param array|string $validation Validation rules |
| 37 | + * |
| 38 | + * @return string The user input |
| 39 | + */ |
| 40 | + protected function prompt(string $field, $options = null, $validation = null): string |
| 41 | + { |
| 42 | + return self::$io->prompt($field, $options, $validation); |
| 43 | + } |
| 44 | + |
| 45 | + /** |
| 46 | + * Outputs a string to the cli on its own line. |
| 47 | + */ |
| 48 | + protected function write( |
| 49 | + string $text = '', |
| 50 | + ?string $foreground = null, |
| 51 | + ?string $background = null |
| 52 | + ): void { |
| 53 | + self::$io->write($text, $foreground, $background); |
| 54 | + } |
| 55 | + |
| 56 | + /** |
| 57 | + * Outputs an error to the CLI using STDERR instead of STDOUT |
| 58 | + */ |
| 59 | + protected function error( |
| 60 | + string $text, |
| 61 | + string $foreground = 'light_red', |
| 62 | + ?string $background = null |
| 63 | + ): void { |
| 64 | + self::$io->error($text, $foreground, $background); |
| 65 | + } |
| 66 | + |
| 67 | + protected function ensureInputOutput(): void |
| 68 | + { |
| 69 | + if (self::$io === null) { |
| 70 | + self::$io = new InputOutput(); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * @internal Testing purpose only |
| 76 | + */ |
| 77 | + public static function setInputOutput(InputOutput $io): void |
| 78 | + { |
| 79 | + self::$io = $io; |
| 80 | + } |
| 81 | + |
| 82 | + /** |
| 83 | + * @internal Testing purpose only |
| 84 | + */ |
| 85 | + public static function resetInputOutput(): void |
| 86 | + { |
| 87 | + self::$io = null; |
| 88 | + } |
| 89 | +} |
0 commit comments