first commit

This commit is contained in:
2024-07-15 12:33:27 +02:00
commit ce50ae282b
22084 changed files with 2623791 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
/*
* DO NOT EDIT THIS FILE.
* See the following change record for more information,
* https://www.drupal.org/node/3084859
* @preserve
*/
.field-icon-telephone {
background-image: url("data:image/svg+xml,%3csvg height='36' viewBox='0 0 36 36' width='36' xmlns='http://www.w3.org/2000/svg'%3e%3cpath d='m9.82246 14.9148c2.20964 4.9719 6.27314 8.9558 11.32454 11.0949.8278-.5984 1.2952-1.6427 1.853-2.4896.4167-.4122 1.25-1.2162 2.0833-.8243 2.0728.9746 3.0622 1.3152 5.4167 1.6486.2314.0328.8678.2463 1.25.2844.5749.0574 1.25.54 1.25 1.7046v4.6058c0 .8243-.6765 1.9233-1.5492 1.9844-.7289.0509-1.3237.0764-1.7841.0764-14.7917 0-26.6667-12.2065-26.6667-26.70265 0-.45554.02574-1.0438.07726-1.7649.0617-.86328 1.17274-1.53245 2.00607-1.53245h4.65592c1.17745 0 1.66525.66786 1.72325 1.23651.0386.37783.2543 1.00757.2875 1.23651.3371 2.32911.6814 3.30781 1.6667 5.35818.3961.8244-.4167 1.6487-.8334 2.0609-.9004.5803-2.2133 1.1-2.76084 2.0227z' fill='%2355565b'/%3e%3c/svg%3e");
}

View File

@@ -0,0 +1,3 @@
.field-icon-telephone {
background-image: url(../../../misc/icons/55565b/telephone.svg);
}

View File

@@ -0,0 +1,4 @@
finished:
7:
phone: telephone
telephone: telephone

View File

@@ -0,0 +1,109 @@
<?php
namespace Drupal\telephone\Plugin\Field\FieldFormatter;
use Drupal\Core\Field\Attribute\FieldFormatter;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
/**
* Plugin implementation of the 'telephone_link' formatter.
*/
#[FieldFormatter(
id: 'telephone_link',
label: new TranslatableMarkup('Telephone link'),
field_types: [
'telephone',
],
)]
class TelephoneLinkFormatter extends FormatterBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'title' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$elements['title'] = [
'#type' => 'textfield',
'#title' => $this->t('Title to replace basic numeric telephone number display'),
'#default_value' => $this->getSetting('title'),
];
return $elements;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$settings = $this->getSettings();
if (!empty($settings['title'])) {
$summary[] = $this->t('Link using text: @title', ['@title' => $settings['title']]);
}
else {
$summary[] = $this->t('Link using provided telephone number.');
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];
$title_setting = $this->getSetting('title');
foreach ($items as $delta => $item) {
// If the telephone number is 5 or less digits, parse_url() will think
// it's a port number rather than a phone number which causes the link
// formatter to throw an InvalidArgumentException. Avoid this by inserting
// a dash (-) after the first digit - RFC 3966 defines the dash as a
// visual separator character and so will be removed before the phone
// number is used. See https://bugs.php.net/bug.php?id=70588 for more.
// While the bug states this only applies to numbers <= 65535, a 5 digit
// number greater than 65535 will cause parse_url() to return FALSE so
// we need the work around on any 5 digit (or less) number.
// First we strip whitespace so we're counting actual digits.
$phone_number = preg_replace('/\s+/', '', $item->value);
if (strlen($phone_number) <= 5) {
$phone_number = substr_replace($phone_number, '-', 1, 0);
}
// Render each element as link.
$element[$delta] = [
'#type' => 'link',
// Use custom title if available, otherwise use the telephone number
// itself as title.
'#title' => $title_setting ?: $item->value,
// Prepend 'tel:' to the telephone number.
'#url' => Url::fromUri('tel:' . rawurlencode($phone_number)),
'#options' => ['external' => TRUE],
];
if (!empty($item->_attributes)) {
$element[$delta]['#options'] += ['attributes' => []];
$element[$delta]['#options']['attributes'] += $item->_attributes;
// Unset field item attributes since they have been included in the
// formatter output and should not be rendered in the field template.
unset($item->_attributes);
}
}
return $element;
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace Drupal\telephone\Plugin\Field\FieldType;
use Drupal\Core\Field\Attribute\FieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
/**
* Plugin implementation of the 'telephone' field type.
*/
#[FieldType(
id: "telephone",
label: new TranslatableMarkup("Telephone number"),
description: new TranslatableMarkup("This field stores a telephone number."),
default_widget: "telephone_default",
default_formatter: "basic_string"
)]
class TelephoneItem extends FieldItemBase {
/**
* The maximum length for a telephone value.
*/
const MAX_LENGTH = 256;
/**
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return [
'columns' => [
'value' => [
'type' => 'varchar',
'length' => self::MAX_LENGTH,
],
],
];
}
/**
* {@inheritdoc}
*/
public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('string')
->setLabel(new TranslatableMarkup('Telephone number'))
->setRequired(TRUE);
return $properties;
}
/**
* {@inheritdoc}
*/
public function isEmpty() {
$value = $this->get('value')->getValue();
return $value === NULL || $value === '';
}
/**
* {@inheritdoc}
*/
public function getConstraints() {
$constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
$constraints = parent::getConstraints();
$constraints[] = $constraint_manager->create('ComplexData', [
'value' => [
'Length' => [
'max' => self::MAX_LENGTH,
'maxMessage' => $this->t('%name: the telephone number may not be longer than @max characters.', ['%name' => $this->getFieldDefinition()->getLabel(), '@max' => self::MAX_LENGTH]),
],
],
]);
return $constraints;
}
/**
* {@inheritdoc}
*/
public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
$values['value'] = rand(pow(10, 8), pow(10, 9) - 1);
return $values;
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Drupal\telephone\Plugin\Field\FieldWidget;
use Drupal\Core\Field\Attribute\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\telephone\Plugin\Field\FieldType\TelephoneItem;
/**
* Plugin implementation of the 'telephone_default' widget.
*/
#[FieldWidget(
id: 'telephone_default',
label: new TranslatableMarkup('Telephone number'),
field_types: ['telephone'],
)]
class TelephoneDefaultWidget extends WidgetBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return [
'placeholder' => '',
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['placeholder'] = [
'#type' => 'textfield',
'#title' => $this->t('Placeholder'),
'#default_value' => $this->getSetting('placeholder'),
'#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
];
return $element;
}
/**
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = [];
$placeholder = $this->getSetting('placeholder');
if (!empty($placeholder)) {
$summary[] = $this->t('Placeholder: @placeholder', ['@placeholder' => $placeholder]);
}
else {
$summary[] = $this->t('No placeholder');
}
return $summary;
}
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['value'] = $element + [
'#type' => 'tel',
'#default_value' => $items[$delta]->value ?? NULL,
'#placeholder' => $this->getSetting('placeholder'),
'#maxlength' => TelephoneItem::MAX_LENGTH,
];
return $element;
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Drupal\telephone\Plugin\migrate\field\d7;
use Drupal\migrate_drupal\Attribute\MigrateField;
use Drupal\migrate_drupal\Plugin\migrate\field\FieldPluginBase;
#[MigrateField(
id: 'phone',
core: [7],
type_map: [
'phone' => 'telephone',
],
source_module: 'phone',
destination_module: 'telephone',
)]
class PhoneField extends FieldPluginBase {
/**
* {@inheritdoc}
*/
public function getFieldFormatterMap() {
return [
'phone' => 'basic_string',
];
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace Drupal\telephone\Plugin\migrate\field\d7;
use Drupal\migrate_drupal\Attribute\MigrateField;
use Drupal\migrate_drupal\Plugin\migrate\field\FieldPluginBase;
#[MigrateField(
id: 'telephone',
core: [7],
source_module: 'telephone',
destination_module: 'telephone',
)]
class TelephoneField extends FieldPluginBase {
/**
* {@inheritdoc}
*/
public function getFieldWidgetMap() {
// The widget IDs are identical in Drupal 7 and 8, so we do not need any
// mapping.
return [];
}
/**
* {@inheritdoc}
*/
public function getFieldFormatterMap() {
return [
'text_plain' => 'string',
'telephone_link' => 'telephone_link',
];
}
}

View File

@@ -0,0 +1,12 @@
name: Telephone
type: module
description: 'Defines a field type for telephone numbers.'
package: Field types
# version: VERSION
dependencies:
- drupal:field
# Information added by Drupal.org packaging script on 2024-07-04
version: '10.3.1'
project: 'drupal'
datestamp: 1720094222

View File

@@ -0,0 +1,7 @@
drupal.telephone-icon:
version: VERSION
css:
theme:
css/telephone.icon.theme.css: {}
dependencies:
- field_ui/drupal.field_ui.manage_fields

View File

@@ -0,0 +1,46 @@
<?php
/**
* @file
* Defines a simple telephone number field type.
*/
use Drupal\Core\Field\FieldTypeCategoryManagerInterface;
use Drupal\Core\Url;
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function telephone_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.telephone':
$output = '';
$output .= '<h2>' . t('About') . '</h2>';
$output .= '<p>' . t('The Telephone module allows you to create fields that contain telephone numbers. See the <a href=":field">Field module help</a> and the <a href=":field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href=":telephone_documentation">online documentation for the Telephone module</a>.', [':field' => Url::fromRoute('help.page', ['name' => 'field'])->toString(), ':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#', ':telephone_documentation' => 'https://www.drupal.org/documentation/modules/telephone']) . '</p>';
$output .= '<h2>' . t('Uses') . '</h2>';
$output .= '<dl>';
$output .= '<dt>' . t('Managing and displaying telephone fields') . '</dt>';
$output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the telephone field can be configured separately. See the <a href=":field_ui">Field UI help</a> for more information on how to manage fields and their display.', [':field_ui' => (\Drupal::moduleHandler()->moduleExists('field_ui')) ? Url::fromRoute('help.page', ['name' => 'field_ui'])->toString() : '#']) . '</dd>';
$output .= '<dt>' . t('Displaying telephone numbers as links') . '</dt>';
$output .= '<dd>' . t('Telephone numbers can be displayed as links with the scheme name <em>tel:</em> by choosing the <em>Telephone</em> display format on the <em>Manage display</em> page. Any spaces will be stripped out of the link text. This semantic markup improves the user experience on mobile and assistive technology devices.') . '</dd>';
$output .= '</dl>';
return $output;
}
}
/**
* Implements hook_field_formatter_info_alter().
*/
function telephone_field_formatter_info_alter(&$info) {
$info['string']['field_types'][] = 'telephone';
}
/**
* Implements hook_field_type_category_info_alter().
*/
function telephone_field_type_category_info_alter(&$definitions) {
// The `telephone` field type belongs in the `general` category, so the
// libraries need to be attached using an alter hook.
$definitions[FieldTypeCategoryManagerInterface::FALLBACK_CATEGORY]['libraries'][] = 'telephone/drupal.telephone-icon';
}

View File

@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\telephone\Functional;
use Drupal\Tests\system\Functional\Module\GenericModuleTestBase;
/**
* Generic module test for telephone.
*
* @group telephone
*/
class GenericTest extends GenericModuleTestBase {}

View File

@@ -0,0 +1,138 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\telephone\Functional;
use Drupal\field\Entity\FieldConfig;
use Drupal\telephone\Plugin\Field\FieldType\TelephoneItem;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests the creation of telephone fields.
*
* @group telephone
* @group #slow
*/
class TelephoneFieldTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = [
'field',
'node',
'telephone',
];
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* A user with permission to create articles.
*
* @var \Drupal\user\UserInterface
*/
protected $webUser;
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->drupalCreateContentType(['type' => 'article']);
$this->webUser = $this->drupalCreateUser([
'create article content',
'edit own article content',
]);
$this->drupalLogin($this->webUser);
// Add the telephone field to the article content type.
FieldStorageConfig::create([
'field_name' => 'field_telephone',
'entity_type' => 'node',
'type' => 'telephone',
])->save();
FieldConfig::create([
'field_name' => 'field_telephone',
'label' => 'Telephone Number',
'entity_type' => 'node',
'bundle' => 'article',
])->save();
/** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
$display_repository = \Drupal::service('entity_display.repository');
$display_repository->getFormDisplay('node', 'article')
->setComponent('field_telephone', [
'type' => 'telephone_default',
'settings' => [
'placeholder' => '123-456-7890',
],
])
->save();
$display_repository->getViewDisplay('node', 'article')
->setComponent('field_telephone', [
'type' => 'telephone_link',
'weight' => 1,
])
->save();
}
/**
* Tests to confirm the widget is setup.
*
* @covers \Drupal\telephone\Plugin\Field\FieldWidget\TelephoneDefaultWidget::formElement
*/
public function testTelephoneWidget(): void {
$this->drupalGet('node/add/article');
$this->assertSession()->fieldValueEquals("field_telephone[0][value]", '');
$this->assertSession()->elementAttributeContains('css', 'input[name="field_telephone[0][value]"]', 'maxlength', (string) TelephoneItem::MAX_LENGTH);
$this->assertSession()->responseContains('placeholder="123-456-7890"');
}
/**
* Tests the telephone formatter.
*
* @covers \Drupal\telephone\Plugin\Field\FieldFormatter\TelephoneLinkFormatter::viewElements
*
* @dataProvider providerPhoneNumbers
*/
public function testTelephoneFormatter($input, $expected): void {
// Test basic entry of telephone field.
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_telephone[0][value]' => $input,
];
$this->drupalGet('node/add/article');
$this->submitForm($edit, 'Save');
$this->assertSession()->responseContains('<a href="tel:' . $expected . '">');
}
/**
* Provides the phone numbers to check and expected results.
*/
public static function providerPhoneNumbers() {
return [
'standard phone number' => ['123456789', '123456789'],
'whitespace is removed' => ['1234 56789', '123456789'],
'parse_url(0) return FALSE workaround' => ['0', '0-'],
'php bug 70588 workaround - lower edge check' => ['1', '1-'],
'php bug 70588 workaround' => ['123', '1-23'],
'php bug 70588 workaround - with whitespace removal' => ['1 2 3 4 5', '1-2345'],
'php bug 70588 workaround - upper edge check' => ['65534', '6-5534'],
'php bug 70588 workaround - edge check' => ['65535', '6-5535'],
'php bug 70588 workaround - invalid port number - lower edge check' => ['65536', '6-5536'],
'php bug 70588 workaround - invalid port number - upper edge check' => ['99999', '9-9999'],
'lowest number not affected by php bug 70588' => ['100000', '100000'],
];
}
}

View File

@@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\telephone\Kernel;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests the new entity API for the telephone field type.
*
* @group telephone
*/
class TelephoneItemTest extends FieldKernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['telephone'];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create a telephone field storage and field for validation.
FieldStorageConfig::create([
'field_name' => 'field_test',
'entity_type' => 'entity_test',
'type' => 'telephone',
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test',
'bundle' => 'entity_test',
'default_value' => [0 => ['value' => '+012345678']],
])->save();
}
/**
* Tests using entity fields of the telephone field type.
*/
public function testTestItem(): void {
// Verify entity creation.
$entity = EntityTest::create();
$value = '+0123456789';
$entity->field_test = $value;
$entity->name->value = $this->randomMachineName();
$entity->save();
// Verify entity has been created properly.
$id = $entity->id();
$entity = EntityTest::load($id);
$this->assertInstanceOf(FieldItemListInterface::class, $entity->field_test);
$this->assertInstanceOf(FieldItemInterface::class, $entity->field_test[0]);
$this->assertEquals($value, $entity->field_test->value);
$this->assertEquals($value, $entity->field_test[0]->value);
// Verify changing the field value.
$new_value = '+41' . rand(1000000, 9999999);
$entity->field_test->value = $new_value;
$this->assertEquals($new_value, $entity->field_test->value);
// Read changed entity and assert changed values.
$entity->save();
$entity = EntityTest::load($id);
$this->assertEquals($new_value, $entity->field_test->value);
// Test sample item generation.
$entity = EntityTest::create();
$entity->field_test->generateSampleItems();
$this->entityValidateAndSave($entity);
}
}