UriItem.php 2.32 KB
Newer Older
1 2
<?php

3
namespace Drupal\Core\Field\Plugin\Field\FieldType;
4

5
use Drupal\Core\Field\FieldDefinitionInterface;
6
use Drupal\Core\Field\FieldStorageDefinitionInterface;
7
use Drupal\Core\TypedData\DataDefinition;
8 9

/**
10
 * Defines the 'uri' entity field type.
11
 *
12 13 14 15
 * URIs are not length limited by RFC 2616, but we need to provide a sensible
 * default. There is a de-facto limit of 2000 characters in browsers and other
 * implementors, so we go with 2048.
 *
16 17 18
 * @FieldType(
 *   id = "uri",
 *   label = @Translation("URI"),
19
 *   description = @Translation("An entity field containing a URI."),
20 21
 *   no_ui = TRUE,
 *   default_formatter = "uri_link",
22
 *   default_widget = "uri",
23
 * )
24
 */
25
class UriItem extends StringItem {
26

27 28 29
  /**
   * {@inheritdoc}
   */
30
  public static function defaultStorageSettings() {
31 32 33 34 35
    $storage_settings = parent::defaultStorageSettings();
    // is_ascii doesn't make sense for URIs.
    unset($storage_settings['is_ascii']);
    $storage_settings['max_length'] = 2048;
    return $storage_settings;
36 37
  }

38
  /**
39
   * {@inheritdoc}
40
   */
41
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
42
    $properties['value'] = DataDefinition::create('uri')
43
      ->setLabel(t('URI value'))
44 45
      ->setSetting('case_sensitive', $field_definition->getSetting('case_sensitive'))
      ->setRequired(TRUE);
46

47
    return $properties;
48
  }
49

50 51 52
  /**
   * {@inheritdoc}
   */
53
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
54 55 56
    return [
      'columns' => [
        'value' => [
57 58
          'type' => 'varchar',
          'length' => (int) $field_definition->getSetting('max_length'),
59
          'binary' => $field_definition->getSetting('case_sensitive'),
60 61 62
        ],
      ],
    ];
63 64
  }

65 66 67 68 69 70 71 72 73 74 75
  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->getValue();
    if (!isset($value['value']) || $value['value'] === '') {
      return TRUE;
    }
    return parent::isEmpty();
  }

76 77 78 79 80 81 82
  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $values = parent::generateSampleValue($field_definition);
    $suffix_length = $field_definition->getSetting('max_length') - 7;
    foreach ($values as $key => $value) {
83
      $values[$key] = 'http://' . mb_substr($value, 0, $suffix_length);
84 85 86 87
    }
    return $values;
  }

88
}