Trim.php in Tamper 8
File
src/Plugin/Tamper/Trim.php
View source
<?php
namespace Drupal\tamper\Plugin\Tamper;
use Drupal\Core\Form\FormStateInterface;
use Drupal\tamper\Exception\TamperException;
use Drupal\tamper\TamperableItemInterface;
use Drupal\tamper\TamperBase;
class Trim extends TamperBase {
const SETTING_CHARACTER = 'character';
const SETTING_SIDE = 'side';
public function defaultConfiguration() {
$config = parent::defaultConfiguration();
$config[self::SETTING_CHARACTER] = '';
$config[self::SETTING_SIDE] = 'trim';
return $config;
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form[self::SETTING_CHARACTER] = [
'#type' => 'textfield',
'#title' => $this
->t('Characters to trim'),
'#default_value' => $this
->getSetting(self::SETTING_CHARACTER),
'#description' => $this
->t('The characters to remove from the string. If blank, then whitespace will be removed.'),
];
$form[self::SETTING_SIDE] = [
'#type' => 'select',
'#title' => $this
->t('Side'),
'#options' => $this
->getOptions(),
'#default_value' => $this
->getSetting(self::SETTING_SIDE),
];
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
$this
->setConfiguration([
self::SETTING_CHARACTER => $form_state
->getValue(self::SETTING_CHARACTER),
]);
$this
->setConfiguration([
self::SETTING_SIDE => $form_state
->getValue(self::SETTING_SIDE),
]);
}
protected function getOptions() {
return [
'trim' => $this
->t('Both'),
'ltrim' => $this
->t('Left'),
'rtrim' => $this
->t('Right'),
];
}
public function tamper($data, TamperableItemInterface $item = NULL) {
if (!is_string($data)) {
throw new TamperException('Input should be a string.');
}
$operation = $this
->getSetting(self::SETTING_SIDE);
$mask = $this
->getSetting(self::SETTING_CHARACTER);
if (!empty($mask)) {
return call_user_func($operation, $data, $mask);
}
else {
return call_user_func($operation, $data);
}
}
}
Classes
Name |
Description |
Trim |
Plugin implementation for trimming text. |