You are here

public function Math::tamper in Tamper 8

Tamper data.

Performs the operations on the data to transform it.

Parameters

mixed $data: The data to tamper.

\Drupal\tamper\TamperableItemInterface $item: Item that can be tampered as part of a plugin's execution.

Return value

mixed The tampered data.

Throws

\Drupal\tamper\Exception\TamperException When the plugin can not tamper the given data.

\Drupal\tamper\Exception\SkipTamperDataException When the calling tamper process should be skipped for the given data.

\Drupal\tamper\Exception\SkipTamperItemException When the calling tamper process should be skipped for the given item.

Overrides TamperInterface::tamper

File

src/Plugin/Tamper/Math.php, line 115

Class

Math
Plugin implementation for performing basic math.

Namespace

Drupal\tamper\Plugin\Tamper

Code

public function tamper($data, TamperableItemInterface $item = NULL) {
  $operation = $this
    ->getSetting(self::SETTING_OPERATION);
  $flip = $this
    ->getSetting(self::SETTING_FLIP);
  $value = $this
    ->getSetting(self::SETTING_VALUE);
  if ($data === TRUE || $data === FALSE || $data === NULL) {
    $data = (int) $data;
  }
  if (!is_numeric($data)) {
    throw new TamperException('Math plugin failed because data was not numeric.');
  }
  if ($flip) {
    switch ($operation) {
      case 'subtraction':
        $data = $value - $data;
        break;
      case 'division':

        // Avoid divide by zero.
        if (empty($data)) {
          throw new TamperException('Math plugin failed because divide by zero was attempted.');
        }
        $data = $value / $data;
    }
    return $data;
  }
  switch ($operation) {
    case 'addition':
      $data = $data + $value;
      break;
    case 'subtraction':
      $data = $data - $value;
      break;
    case 'multiplication':
      $data = $data * $value;
      break;
    case 'division':
      $data = $data / $value;
  }
  return $data;
}