FloatItem.php 1.81 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Field\Plugin\Field\FieldType\FloatItem.
6 7
 */

8
namespace Drupal\Core\Field\Plugin\Field\FieldType;
9

10
use Drupal\Core\Field\FieldDefinitionInterface;
11
use Drupal\Core\Field\FieldStorageDefinitionInterface;
12
use Drupal\Core\TypedData\DataDefinition;
13 14

/**
15
 * Defines the 'float' field type.
16
 *
17 18
 * @FieldType(
 *   id = "float",
19 20 21 22
 *   label = @Translation("Number (float)"),
 *   description = @Translation("This field stores a number in the database in a floating point format."),
 *   default_widget = "number",
 *   default_formatter = "number_decimal"
23 24
 * )
 */
25
class FloatItem extends NumericItemBase {
26 27

  /**
28
   * {@inheritdoc}
29
   */
30
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
31
    $properties['value'] = DataDefinition::create('float')
32 33
      ->setLabel(t('Float'))
      ->setRequired(TRUE);
34

35
    return $properties;
36
  }
37 38 39 40

  /**
   * {@inheritdoc}
   */
41
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
42 43 44 45 46 47 48 49 50
    return array(
      'columns' => array(
        'value' => array(
          'type' => 'float',
        ),
      ),
    );
  }

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $settings = $field_definition->getSettings();
    $precision = rand(10, 32);
    $scale = rand(0, 2);
    $max = is_numeric($settings['max']) ?: pow(10, ($precision - $scale)) - 1;
    $min = is_numeric($settings['min']) ?: -pow(10, ($precision - $scale)) + 1;
    // @see "Example #1 Calculate a random floating-point number" in
    // http://php.net/manual/en/function.mt-getrandmax.php
    $random_decimal = $min + mt_rand() / mt_getrandmax() * ($max - $min);
    $values['value'] = self::truncateDecimal($random_decimal, $scale);
    return $values;
  }

67
}