function DataConvert::doExecute

Executes the plugin.

Parameters

mixed $value: The input value.

string $target_type: The target type the value should be converted into.

string $rounding_behavior: The behavior for rounding.

File

src/Plugin/RulesAction/DataConvert.php, line 67

Class

DataConvert
Provides an action to convert data from one type to another.

Namespace

Drupal\rules\Plugin\RulesAction

Code

protected function doExecute($value, $target_type, $rounding_behavior = NULL) {
    // @todo Add support for objects implementing __toString().
    if (!is_scalar($value)) {
        throw new InvalidArgumentException('Only scalar values are supported.');
    }
    // Ensure valid contexts have been provided.
    // @todo check how this works. May need to use !empty to allow the selection
    // list to be used and give an empty value?
    if (isset($rounding_behavior) && $target_type != 'integer') {
        throw new InvalidArgumentException('A rounding behavior only makes sense with an integer target type.');
    }
    // First apply the rounding behavior if given.
    if (!empty($rounding_behavior)) {
        switch ($rounding_behavior) {
            case 'up':
                $value = ceil($value);
                break;
            case 'down':
                $value = floor($value);
                break;
            case 'round':
                $value = round($value);
                break;
            default:
                throw new InvalidArgumentException("Unknown rounding behavior: {$rounding_behavior}");
        }
    }
    switch ($target_type) {
        case 'float':
            $result = floatval($value);
            break;
        case 'integer':
            $result = intval($value);
            break;
        case 'string':
            $result = strval($value);
            break;
        default:
            throw new InvalidArgumentException("Unknown target type: {$target_type}");
    }
    $this->setProvidedValue('conversion_result', $result);
}