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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
|
<?php
/**
* Matomo - free/libre analytics platform
*
* @link https://matomo.org
* @license https://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
namespace Piwik\Plugin;
use Piwik\Container\StaticContainer;
use Piwik\Plugins\CoreConsole\FeatureFlags\SystemSignals;
use Piwik\Plugins\FeatureFlags\FeatureFlagManager;
use Symfony\Component\Console\Command\Command as SymfonyCommand;
use Symfony\Component\Console\Command\SignalableCommandInterface;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Helper\HelperInterface;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\NullOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;
use Throwable;
use Closure;
/**
* The base class for console commands.
*
* @api
*/
class ConsoleCommand extends SymfonyCommand implements SignalableCommandInterface
{
/**
* @var ProgressBar|null
*/
private $progress = null;
/**
* @var OutputInterface|null
*/
private $output = null;
/**
* @var InputInterface|null
*/
private $input = null;
/**
* Sends the given message(s) as success message(s) to the output interface (surrounded by empty lines)
*
* @param string|string[] $messages
*/
public function writeSuccessMessage($messages): void
{
if (is_string($messages)) {
$messages = [$messages];
}
$this->getOutput()->writeln('');
foreach ($messages as $message) {
$this->getOutput()->writeln(self::wrapInTag('info', $message));
}
$this->getOutput()->writeln('');
}
/**
* Sends the given message(s) as error message(s) to the output interface (surrounded by empty lines)
*
* @param string|string[] $messages
*/
public function writeErrorMessage($messages): void
{
if (is_string($messages)) {
$messages = [$messages];
}
$this->getOutput()->writeln('');
foreach ($messages as $message) {
$this->getOutput()->writeln(self::wrapInTag('error', $message));
}
$this->getOutput()->writeln('');
}
/**
* Sends the given messages as comment message to the output interface (surrounded by empty lines)
*
* @param string|string[] $messages
*/
public function writeComment($messages): void
{
if (is_string($messages)) {
$messages = [$messages];
}
$this->getOutput()->writeln('');
foreach ($messages as $message) {
$this->getOutput()->writeln(self::wrapInTag('comment', $message));
}
$this->getOutput()->writeln('');
}
/**
* Checks if all input options that are marked as requires-value were provided
*
* @throws \InvalidArgumentException
*/
protected function checkAllRequiredOptionsAreNotEmpty(): void
{
$options = $this->getDefinition()->getOptions();
foreach ($options as $option) {
$name = $option->getName();
$value = $this->getInput()->getOption($name);
if ($option->isValueRequired() && empty($value)) {
throw new \InvalidArgumentException(sprintf('The required option --%s is not set', $name));
}
}
}
/**
* This method can't be used.
*
* @see doExecute
*/
final protected function execute(InputInterface $input, OutputInterface $output): int
{
return $this->doExecute();
}
/**
* Method is final to make it impossible to overwrite it in plugin commands
*
*/
final public function run(InputInterface $input, OutputInterface $output): int
{
// Ensure input and output are available for methods like `doExecute`, `doInteract` and `doInitialize`
$this->input = $input;
$this->output = $output;
return parent::run($input, $output);
}
/**
* Method is final to make it impossible to overwrite it in plugin commands
* use getSystemSignalsToHandle() instead.
*
* Will only have an effect if the "SystemSignals" feature flag is enabled.
*
* @return array<int>
*/
final public function getSubscribedSignals(): array
{
$canSubscribe = false;
// The required DI configuration may not be loaded during the update process.
// This can happen for an upgrade from a version that did not yet contain
// the feature flag plugin.
try {
$featureFlagManager = StaticContainer::get(FeatureFlagManager::class);
$canSubscribe = $featureFlagManager->isFeatureActive(SystemSignals::class);
} catch (Throwable $e) {
}
if (!$canSubscribe) {
return [];
}
return $this->getSystemSignalsToHandle();
}
/**
* Method is final to make it impossible to overwrite it in plugin commands
* use handleSystemSignal() instead.
*
* Will only have an effect if the "SystemSignals" feature flag is enabled.
*/
final public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false
{
$this->handleSystemSignal($signal);
return false;// Not sure about that
}
/**
* Returns the list of system signals to subscribe.
*
* @return array<int>
*/
public function getSystemSignalsToHandle(): array
{
return [];
}
/**
* The method will be called when the application is signaled.
*/
public function handleSystemSignal(int $signal): void
{
}
/**
* Adds a negatable option (e.g. --ansi / --no-ansi)
*
* @param array|null|string $shortcut
* @param mixed $default
* @return ConsoleCommand
*/
public function addNegatableOption(string $name, array|string|null $shortcut = null, string $description = '', mixed $default = null)
{
return parent::addOption($name, $shortcut, InputOption::VALUE_NEGATABLE, $description, $default);
}
/**
* Adds an option with optional value
*
* @param array|null|string $shortcut
* @param mixed $default
* @return ConsoleCommand
*/
public function addOptionalValueOption(
string $name,
array|string|null $shortcut = null,
string $description = '',
mixed $default = null,
bool $acceptArrays = false
) {
$mode = $acceptArrays ? InputOption::VALUE_IS_ARRAY : 0;
return parent::addOption($name, $shortcut, $mode | InputOption::VALUE_OPTIONAL, $description, $default);
}
/**
* Adds a valueless option
*
* @param array|null|string $shortcut
* @param mixed $default
* @return ConsoleCommand
*/
public function addNoValueOption(string $name, array|string|null $shortcut = null, string $description = '', mixed $default = null)
{
return parent::addOption($name, $shortcut, InputOption::VALUE_NONE, $description, $default);
}
/**
* Adds an option with required value
*
* @param array|null|string $shortcut
* @param mixed $default
* @return ConsoleCommand
*/
public function addRequiredValueOption(
string $name,
array|string|null $shortcut = null,
string $description = '',
mixed $default = null,
bool $acceptArrays = false
) {
$mode = $acceptArrays ? InputOption::VALUE_IS_ARRAY : 0;
return parent::addOption($name, $shortcut, $mode | InputOption::VALUE_REQUIRED, $description, $default);
}
/**
* This method can't be used.
*
* @see addNegatableOption, addOptionalValueOption, addNoValueOption, addRequiredValueOption
*/
public function addOption(
string $name,
array|string|null $shortcut = null,
?int $mode = null,
string $description = '',
mixed $default = null,
Closure|array $suggestedValues = []
): static {
throw new \LogicException('addOption should not be used.');
}
/**
* Adds an optional argument to the command
*
* @param string $name Name of the command
* @param null $default
* @param bool $acceptArrays Defines if the option accepts multiple values (array)
* @return ConsoleCommand
*/
public function addOptionalArgument(
string $name,
string $description = '',
mixed $default = null,
bool $acceptArrays = false
) {
$mode = $acceptArrays ? InputArgument::IS_ARRAY : 0;
return parent::addArgument($name, $mode | InputArgument::OPTIONAL, $description, $default);
}
/**
* Adds a required argument to the command
*
* @param $default
* @param bool $acceptArrays Defines if the option accepts multiple values (array)
* @return ConsoleCommand
*/
public function addRequiredArgument(
string $name,
string $description = '',
mixed $default = null,
bool $acceptArrays = false
) {
$mode = $acceptArrays ? InputArgument::IS_ARRAY : 0;
return parent::addArgument($name, $mode | InputArgument::REQUIRED, $description, $default);
}
/**
* This method can't be used.
*
* @see addOptionalArgument, addRequiredArgument
*/
public function addArgument(string $name, ?int $mode = null, string $description = '', mixed $default = null, Closure|array $suggestedValues = []): static
{
throw new \LogicException('addArgument can not be used.');
}
/**
* Method that implements the actual command code
*
* @return int use self::SUCCESS or self::FAILURE
*/
protected function doExecute(): int
{
throw new LogicException('You must override the doExecute() method in the concrete command class.');
}
/**
* This method can't be used.
*
* @see doInteract
*/
final protected function interact(InputInterface $input, OutputInterface $output)
{
$this->doInteract();
}
/**
* Interacts with the user.
*
* Can be overwritten by plugin command
*
* @see parent::interact()
*
*/
protected function doInteract(): void
{
}
/**
* This method can't be used.
*
* @see doInitialize
*/
final protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->doInitialize();
}
/**
* Initializes the command after the input has been bound and before the input is validated.
*
* Can be overwritten by plugin command
*
* @see parent::initialize()
*
*/
protected function doInitialize(): void
{
}
protected function getOutput(): OutputInterface
{
return $this->output;
}
protected function setOutput(OutputInterface $output): void
{
$this->output = $output;
}
protected function getInput(): InputInterface
{
return $this->input;
}
/**
* This method can't be used.
*
* @see askAndValidate(), askForConfirmation(), ask(), initProgressBar(), startProgressBar(), advanceProgressBar(), finishProgressBar(), renderTable()
*/
public function getHelper(string $name): HelperInterface
{
throw new \LogicException('getHelper can not be used');
}
/**
* Helper method to ask the user for confirmation
*
* @see QuestionHelper
*
*/
protected function askForConfirmation(string $question, bool $default = true, string $trueAnswerRegex = '/^y/i'): bool
{
/** @var QuestionHelper $helper */
$helper = parent::getHelper('question');
$question = new ConfirmationQuestion($question, $default, $trueAnswerRegex);
return (bool) $helper->ask($this->getInput(), $this->getOutput(), $question);
}
/**
* Ask the user for input and validates the provided value using the given callable
*
* @see QuestionHelper
*
* @param mixed|null $default
* @param iterable|null $autocompleterValues
* @return mixed
*/
protected function askAndValidate(
string $question,
?callable $validator = null,
mixed $default = null,
?iterable $autocompleterValues = null
) {
/** @var QuestionHelper $helper */
$helper = parent::getHelper('question');
$question = new Question($question, $default);
$question->setValidator($validator);
$question->setAutocompleterValues($autocompleterValues);
return $helper->ask($this->getInput(), $this->getOutput(), $question);
}
/**
* Ask the user for input
*
* @see QuestionHelper
*
* @param mixed|null $default
* @return mixed
*/
protected function ask(string $question, mixed $default = null)
{
return $this->askAndValidate($question, null, $default);
}
/**
* Initializes a progress bar for the current command
*
* Note: Only one progress bar can be used at a time
*
* @see ProgressBar
*
*/
protected function initProgressBar(int $numChangesToPerform = 0): ProgressBar
{
$this->progress = new ProgressBar($this->getOutput(), $numChangesToPerform);
return $this->progress;
}
/**
* Starts a previously initialized progress bar
*
*/
protected function startProgressBar(int $numChangesToPerform = 0): void
{
$this->progress->start($numChangesToPerform);
}
/**
* Advances the previously initialized progress bar
*
*/
protected function advanceProgressBar(int $step = 1): void
{
if (empty($this->progress)) {
throw new \Exception('No progress bar initialized.');
}
$this->progress->advance($step);
}
/**
* Finished the initialized progress bar
*
*/
protected function finishProgressBar(): void
{
if (empty($this->progress)) {
throw new \Exception('No progress bar initialized.');
}
$this->progress->finish();
}
/**
* Helper for rendering tables in console output
*
* @see Table
*
* @param array $header
* @param array $rows
* @return void
*/
protected function renderTable(array $header, array $rows)
{
$table = new Table($this->getOutput());
$table
->setHeaders($header)
->setRows($rows);
$table->render();
}
/**
* Runs a certain command
*
* @param array $arguments
* @throws \Symfony\Component\Console\Exception\ExceptionInterface
*/
protected function runCommand(string $command, array $arguments, bool $hideOutput = false): int
{
$command = $this->getApplication()->find($command);
$arguments = ['command' => $command] + $arguments;
$inputObject = new ArrayInput($arguments);
$inputObject->setInteractive($this->getInput()->isInteractive());
return $command->run($inputObject, $hideOutput ? new NullOutput() : $this->getOutput());
}
/**
* Wrap the input string in an open and closing HTML/XML tag.
* E.g. wrap_in_tag('info', 'my string') returns '<info>my string</info>'
*
* @param string $tagname Tag name to wrap the string in.
* @param string $str String to wrap with the tag.
* @return string The wrapped string.
*/
public static function wrapInTag(string $tagname, string $str): string
{
return "<$tagname>$str</$tagname>";
}
}
|