You are here

public static function ScssNumber::valueCallback in SCSS Compiler 1.0.x

Determines how user input is mapped to an element's #value property.

Parameters

array $element: An associative array containing the properties of the element.

mixed $input: The incoming input to populate the form element. If this is FALSE, the element's default value should be returned.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

mixed The value to assign to the element.

Overrides FormElement::valueCallback

File

src/Element/ScssNumber.php, line 573

Class

ScssNumber
A form element to represent Sass numbers with a unit.

Namespace

Drupal\compiler_scss\Element

Code

public static function valueCallback(&$element, $input, FormStateInterface $form_state) {

  // Populate the element with a default value if none already exists.
  $element += [
    '#default_value' => [],
  ];

  // Allow typed data to be supplied.
  if ($element['#default_value'] instanceof IntermediateNumber) {
    $element['#default_value'] = [
      'value' => $element['#default_value']
        ->value(),
      'unit' => $element['#default_value']
        ->unit(),
    ];
  }

  // Allow a scalar value to be supplied instead of a value & unit pair.
  if (is_scalar($element['#default_value'])) {
    $element['#default_value'] = [
      'value' => $element['#default_value'],
    ];
  }

  // Check if the element's default value should be used in lieu of an input.
  if ($input === FALSE) {

    // Replace the input with the element's default value if FALSE.
    $input = $element['#default_value'];
  }

  // Only attempt to process the input (or default value) if it's an array.
  if (is_array($input)) {

    // Extract the value & unit from this element's input (if available).
    $value = $input['value'] ?? NULL;
    $unit = $input['unit'] ?? NULL;

    // Canonicalize the input value and return it.
    $unit = is_numeric($value) ? array_filter([
      'unit' => $unit,
    ]) : [];
    $value = is_numeric($value) ? [
      'value' => $value,
    ] : [];

    // Only return a value if a numeric input was supplied.
    return $value + $unit ?: NULL;
  }
  return NULL;
}