function LinkItem::generateSampleValue

Same name and namespace in other branches
  1. 9 core/modules/link/src/Plugin/Field/FieldType/LinkItem.php \Drupal\link\Plugin\Field\FieldType\LinkItem::generateSampleValue()
  2. 8.9.x core/modules/link/src/Plugin/Field/FieldType/LinkItem.php \Drupal\link\Plugin\Field\FieldType\LinkItem::generateSampleValue()
  3. 10 core/modules/link/src/Plugin/Field/FieldType/LinkItem.php \Drupal\link\Plugin\Field\FieldType\LinkItem::generateSampleValue()

Overrides FieldItemBase::generateSampleValue

File

core/modules/link/src/Plugin/Field/FieldType/LinkItem.php, line 124

Class

LinkItem
Plugin implementation of the 'link' field type.

Namespace

Drupal\link\Plugin\Field\FieldType

Code

public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
    if ($field_definition->getItemDefinition()
        ->getSetting('link_type') & LinkItemInterface::LINK_EXTERNAL) {
        // Set of possible top-level domains.
        $tlds = [
            'com',
            'net',
            'gov',
            'org',
            'edu',
            'biz',
            'info',
        ];
        // Set random length for the domain name.
        $domain_length = mt_rand(7, 15);
        switch ($field_definition->getSetting('title')) {
            case DRUPAL_DISABLED:
                $values['title'] = '';
                break;
            case DRUPAL_REQUIRED:
                $values['title'] = $random->sentences(4);
                break;
            case DRUPAL_OPTIONAL:
                // In case of optional title, randomize its generation.
                $values['title'] = mt_rand(0, 1) ? $random->sentences(4) : '';
                break;
        }
        $values['uri'] = 'https://www.' . $random->word($domain_length) . '.' . $tlds[mt_rand(0, count($tlds) - 1)];
    }
    else {
        $values['uri'] = 'base:' . $random->name(mt_rand(1, 64));
    }
    return $values;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.