You are here

public static function DecimalItem::generateSampleValue in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/DecimalItem.php \Drupal\Core\Field\Plugin\Field\FieldType\DecimalItem::generateSampleValue()

Generates placeholder field values.

Useful when populating site with placeholder content during site building or profiling.

Parameters

\Drupal\Core\Field\FieldDefinitionInterface $field_definition: The field definition.

Return value

array An associative array of values.

Overrides FieldItemBase::generateSampleValue

File

core/lib/Drupal/Core/Field/Plugin/Field/FieldType/DecimalItem.php, line 131

Class

DecimalItem
Defines the 'decimal' field type.

Namespace

Drupal\Core\Field\Plugin\Field\FieldType

Code

public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
  $settings = $field_definition
    ->getSettings();
  $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']) ?: pow(10, $precision - $scale) - 1;
  $min = is_numeric($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);
  $values['value'] = self::truncateDecimal($random_decimal, $scale);
  return $values;
}