You are here

ScssColor.php in SCSS Compiler 1.0.x

File

src/Element/ScssColor.php
View source
<?php

namespace Drupal\compiler_scss\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\FormElement;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\compiler_scss\Type\Color as IntermediateColor;

/**
 * A form element to represent null-able Sass colors.
 *
 * Copyright (C) 2021  Library Solutions, LLC (et al.).
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * @FormElement("compiler_scss_color")
 */
class ScssColor extends FormElement {

  /**
   * {@inheritdoc}
   */
  public function getInfo() {
    return [
      '#children' => [],
      '#element_validate' => [
        [
          get_class(),
          'validateColor',
        ],
      ],
      '#input' => TRUE,
      '#required' => FALSE,
      '#theme' => 'container',
      '#theme_wrappers' => [
        'form_element',
      ],
      '#title' => NULL,
      '#tree' => TRUE,
      '#process' => [
        [
          get_class(),
          'processColor',
        ],
      ],
    ];
  }

  /**
   * Attempt to extract the value of the supplied element.
   *
   * @param array $element
   *   The element for which to attempt to extract a value.
   *
   * @return string
   *   The requested value from the supplied element.
   */
  protected static function getValue(array $element) {
    $value = $element['#value'] ?? '';
    if ($value instanceof IntermediateColor) {
      $value = $value
        ->toHex();
    }
    return $value;
  }

  /**
   * Process the element before it gets rendered in the form.
   *
   * @param array $element
   *   The element to process before being rendered.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form.
   *
   * @return array
   *   The resulting element after having been processed.
   */
  public static function processColor(array &$element, FormStateInterface $form_state, array &$complete_form) {
    $element['enable'] = [
      '#type' => 'checkbox',
      '#title' => t('Set value?'),
      '#name' => "{$element['#name']}[enable]",
      '#access' => !$element['#required'],
      '#default_value' => !empty(self::getValue($element)),
    ];
    $element['value'] = [
      '#type' => 'color',
      '#name' => "{$element['#name']}[value]",
      '#title' => $element['#title'],
      '#title_display' => 'none',
      // The "color" element only supports hex codes with long channels and no
      // alpha channel value, so we trim the value here.
      '#default_value' => substr(self::getValue($element), 0, 7),
      '#required' => $element['#required'],
      '#states' => [
        'visible' => [
          ":input[name=\"{$element['enable']['#name']}\"]" => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
    $element['#children'][] =& $element['enable'];
    $element['#children'][] =& $element['value'];
    return $element;
  }

  /**
   * Validate this element's value on form submission.
   *
   * @param array $element
   *   The element that should be validated.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param array $complete_form
   *   The complete form.
   */
  public static function validateColor(array &$element, FormStateInterface $form_state, array &$complete_form) {

    // Extract the input value from the element.
    $input = self::getValue($element);

    // Represent the input as a typed data instance to facilitate validation.
    $definition = DataDefinition::create('compiler_scss_color');
    $color = \Drupal::typedDataManager()
      ->create($definition, $input);

    // Check if the input value failed validation.
    if ($color
      ->validate()
      ->count() > 0) {
      $error = $element['#title'] ? t('%name must be a valid color.', [
        '%name' => $element['#title'],
      ]) : t('This field must be a valid color.');
      $form_state
        ->setError($element, $error);
    }
    else {
      $form_state
        ->setValueForElement($element, $input ?: NULL);
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function valueCallback(&$element, $input, FormStateInterface $form_state) {

    // Populate the element with a default value if none already exists.
    $element += [
      '#default_value' => '',
    ];
    if ($element['#default_value'] instanceof IntermediateColor) {
      $element['#default_value'] = $element['#default_value']
        ->toHex();
    }

    // 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'];
      $input = [
        'enable' => is_string($input) && !empty($input),
        'value' => is_string($input) ? $input : '',
      ];
    }

    // Only attempt to process the input (or default value) if it's an array.
    if (is_array($input) && array_key_exists('value', $input)) {
      if (!$element['#required']) {
        $enable = $input['enable'] ?? FALSE;

        // Only return a color value if this element is enabled.
        return $enable ? $input['value'] : '';
      }
      else {

        // Always return a value if the field is required.
        return $input['value'];
      }
    }
    return '';
  }

}

Classes

Namesort descending Description
ScssColor A form element to represent null-able Sass colors.