commands-1.x-dev/src/CommandPluginBase.php
src/CommandPluginBase.php
<?php
namespace Drupal\commands;
use Drupal\Component\Plugin\PluginBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Base class for task_command plugins.
*/
abstract class CommandPluginBase extends PluginBase implements CommandInterface {
/**
* {@inheritdoc}
*/
public function id() {
// Cast the label to a string since it is a TranslatableMarkup object.
return (string) $this->pluginDefinition['id'];
}
/**
* {@inheritdoc}
*/
public function label() {
// Cast the label to a string since it is a TranslatableMarkup object.
return (string) $this->pluginDefinition['label'];
}
/**
* {@inheritdoc}
*/
public function description() {
// Cast the label to a string since it is a TranslatableMarkup object.
return (string) $this->pluginDefinition['description'];
}
/**
* Generate a command by parsing parameters.
*
* @usage
* In a Plugin, wrap strings to replace with brackets:
* command: echo [message]
*
* [message] will be replaced with $parameters['message'].
*/
public function command($parameters = []) {
// Load command from plugin definition.
$commands = is_array($this->pluginDefinition['command']) ? $this->pluginDefinition['command'] : [$this->pluginDefinition['command']];
$parameters = array_filter($parameters);
foreach ($commands as &$command) {
// Inject parameters into command.
foreach ($parameters as $name => $value) {
$command = str_replace("[$name]", $value, $command);
}
}
return $commands;
}
/**
* @return string
*/
public function commandString() {
return implode(PHP_EOL, $this->command());
}
/**
* Render form elements on the /command/run form.
* Put form elements under $form['parameters'] to automatically save to the 'parameters' field.
* @return void
*/
public function form($form, FormStateInterface $form_state)
{
$form['parameters']['#tree'] = 'true';
return $form;
}
}
