datafield-1.x-dev/src/Plugin/DataField/FieldType/NumericItem.php

src/Plugin/DataField/FieldType/NumericItem.php
<?php

namespace Drupal\datafield\Plugin\DataField\FieldType;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\datafield\Attribute\DataFieldType;
use Drupal\datafield\Plugin\DataFieldTypeInterface;

/**
 * Defines the 'decimal' field type.
 */
#[DataFieldType(
  id: 'numeric',
  label: new TranslatableMarkup('Number (decimal)'),
  description: new TranslatableMarkup('This field stores a number in the database in a fixed decimal format.'),
  category: 'number',
  default_widget: 'number',
  default_formatter: 'number_unformatted',
)]
class NumericItem implements DataFieldTypeInterface {
  use StringTranslationTrait;

  /**
   * {@inheritdoc}
   */
  public static function defaultStorageSettings() {
    return [
      'type' => 'numeric',
      'precision' => 10,
      'scale' => 2,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(array $settings) {
    $default = self::defaultStorageSettings();
    if (!empty($settings['unsigned'])) {
      $default['unsigned'] = $settings['unsigned'];
    }
    if (!empty($settings['precision'])) {
      $default['precision'] = $settings['precision'];
    }
    if (!empty($settings['scale'])) {
      $default['scale'] = $settings['scale'];
    }
    $column = [
      'columns' => [
        'value' => $default,
      ],
    ];

    return $column;
  }

  /**
   * Helper method to truncate a decimal number to a given number of decimals.
   *
   * @param float $decimal
   *   Decimal number to truncate.
   * @param int $num
   *   Number of digits the output will have.
   *
   * @return float
   *   Decimal number truncated.
   */
  protected static function truncateDecimal($decimal, $num) {
    return floor($decimal * pow(10, $num)) / pow(10, $num);
  }

  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue($settings = []) {
    $precision = $settings['precision'] ?: 10;
    $scale = $settings['scale'] ?: 2;
    // $precision - $scale is the number of digits on the left of the decimal
    // point.
    // The maximum number you can get with 3 digits is 10^3 - 1 --> 999.
    // The minimum number you can get with 3 digits is -1 * (10^3 - 1).
    $max = is_numeric($settings['max']) ? $settings['max'] : pow(10, ($precision - $scale)) - 1;
    $min = is_numeric($settings['min']) ? $settings['min'] : -pow(10, ($precision - $scale)) + 1;

    // Get the number of decimal digits for the $max.
    $decimal_digits = self::getDecimalDigits($max);
    // Do the same for the min and keep the higher number of decimal digits.
    $decimal_digits = max(self::getDecimalDigits($min), $decimal_digits);
    // If $min = 1.234 and $max = 1.33 then $decimal_digits = 3.
    $scale = rand($decimal_digits, $scale);

    // @see "Example #1 Calculate a random floating-point number" in
    // http://php.net/manual/function.mt-getrandmax.php
    $random_decimal = $min + mt_rand() / mt_getrandmax() * ($max - $min);
    return self::truncateDecimal($random_decimal, $scale);
  }

  /**
   * Helper method to get the number of decimal digits out of a decimal number.
   *
   * @param int $decimal
   *   The number to calculate the number of decimals digits from.
   *
   * @return int
   *   The number of decimal digits.
   */
  protected static function getDecimalDigits($decimal) {
    $digits = 0;
    while ($decimal - round($decimal)) {
      $decimal *= 10;
      $digits++;
    }
    return $digits;
  }

  /**
   * {@inheritdoc}
   */
  public function getPluginId() {
    return '';
  }

  /**
   * {@inheritdoc}
   */
  public function getPluginDefinition() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(array $settings) {
    $name = $settings['name'];
    $data_type = 'float';
    return DataDefinition::create($data_type)
      ->setLabel(new TranslatableMarkup('%name value', ['%name' => $name]))
      ->setRequired(FALSE);
  }

  /**
   * {@inheritdoc}
   */
  public function getLabel() {
    return $this->t('Number');
  }

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $field_settings, array $settings) {
    $description = [$this->t('The possible values this field can contain. Enter one value per line, in the format key|label.')];
    $description[] = $this->t('The label will be used in displayed values and edit forms.');
    $description[] = $this->t('The label is optional: if a line contains a single item, it will be used as key and label.');
    $subfield = $field_settings['machine_name'];
    $field_form = [
      'label' => [
        '#type' => 'textfield',
        '#title' => $this->t('Label'),
        '#default_value' => $field_settings['label'] ?? ucfirst($settings["name"]),
      ],
      'required' => [
        '#type' => 'checkbox',
        '#title' => $this->t('Required'),
        '#default_value' => $field_settings['required'] ?? FALSE,
      ],
      'list' => [
        '#type' => 'checkbox',
        '#title' => $this->t('Limit allowed values'),
        '#default_value' => $field_settings['list'] ?? FALSE,
      ],
      'allowed_values' => [
        '#type' => 'textarea',
        '#title' => $this->t('Allowed values list'),
        '#description' => implode('<br/>', $description),
        '#default_value' => !empty($field_settings['allowed_values']) ? $this->allowedValuesString($field_settings['allowed_values']) : '',
        '#rows' => 10,
        '#element_validate' => [[get_class($this), 'validateAllowedValues']],
        '#storage_type' => $settings['type'],
        '#storage_max_length' => $settings['max_length'],
        '#field_name' => $field_settings['field_name'],
        '#entity_type' => $field_settings['entity_type'],
        '#allowed_values' => $field_settings['allowed_values'] ?? '',
        '#states' => [
          'invisible' => [":input[name='settings[field_settings][$subfield][list]']" => ['checked' => FALSE]],
        ],
      ],
      'min' => [
        '#type' => 'number',
        '#title' => $this->t('Minimum'),
        '#description' => $this->t('The minimum value that should be allowed in this field. Leave blank for no minimum.'),
        '#default_value' => $field_settings['min'] ?? NULL,
      ],
      'max' => [
        '#type' => 'number',
        '#title' => $this->t('Maximum'),
        '#description' => $this->t('The maximum value that should be allowed in this field. Leave blank for no maximum.'),
        '#default_value' => $field_settings['max'] ?? NULL,
      ],
      'prefix' => [
        '#type' => 'textfield',
        '#title' => $this->t('Prefix'),
        '#default_value' => $field_settings['prefix'] ?? NULL,
        '#description' => $this->t("Define a string that should be prefixed to the value, like '$ ' or '&euro; '. Leave blank for none. Separate singular and plural values with a pipe ('pound|pounds')."),
      ],
      'suffix' => [
        '#type' => 'textfield',
        '#title' => $this->t('Suffix'),
        '#default_value' => $field_settings['suffix'] ?? NULL,
        '#description' => $this->t("Define a string that should be suffixed to the value, like ' m', ' kb/s'. Leave blank for none. Separate singular and plural values with a pipe ('pound|pounds')."),
      ],
    ];
    return $field_form;
  }

  /**
   * Get constraints.
   *
   * {@inheritdoc}
   */
  public function getConstraints(array $settings) {
    $constraints = [];
    if (is_numeric($settings['min'])) {
      $constraints['Range']['min'] = $settings['min'];
    }
    if (is_numeric($settings['max'])) {
      $constraints['Range']['max'] = $settings['max'];
    }
    if ($settings['required']) {
      $constraints['NotBlank'] = [];
    }
    return $constraints;
  }

  /**
   * Validate allowed values.
   *
   * {@inheritdoc}
   */
  public static function validateAllowedValues(array $element, FormStateInterface $form_state) {
    $values = static::extractAllowedValues($element['#value']);
    // Check if keys are valid for the field type.
    foreach ($values as $key => $value) {
      if (!is_numeric($key)) {
        $form_state->setError($element, ('Allowed values list: each key must be a valid integer or decimal.'));
      }
    }
  }

  /**
   * Extracts the allowed values array from the allowed_values element.
   *
   * @param string $string
   *   The raw string to extract values from.
   *
   * @return array
   *   The array of extracted key/value pairs.
   *
   * @see \Drupal\options\Plugin\Field\FieldType\ListTextItem::extractAllowedValues()
   */
  protected static function extractAllowedValues(string $string): array {

    $values = [];

    $list = explode("\n", $string);
    $list = array_map('trim', $list);
    $list = array_filter($list, 'strlen');

    foreach ($list as $text) {
      // Check for an explicit key.
      if (preg_match('/(.*)\|(.*)/', $text, $matches)) {
        // Trim key and value to avoid unwanted spaces issues.
        $key = trim($matches[1]);
        $value = trim($matches[2]);
      }
      else {
        $key = $value = $text;
      }
      $values[$key] = $value;
    }

    return $values;
  }

  /**
   * Generates a string representation of an array of 'allowed values'.
   *
   * This string format is suitable for edition in a textarea.
   *
   * @param mixed $values
   *   An array|string of values, where array keys are values and array values
   *   are labels.
   *
   * @return string
   *   The string representation of the $values array:
   *    - Values are separated by a carriage return.
   *    - Each value is in the format "value|label" or "value".
   */
  protected function allowedValuesString($values): string {
    if (is_string($values)) {
      return $values;
    }
    $lines = [];
    foreach ($values as $key => $value) {
      $lines[] = "$key|$value";
    }
    return implode("\n", $lines);
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc