Update core 8.3.0

This commit is contained in:
Rob Davies 2017-04-13 15:53:35 +01:00
parent da7a7918f8
commit cd7a898e66
6144 changed files with 132297 additions and 87747 deletions

View file

@ -19,7 +19,7 @@ function field_test_entity_type_alter(array &$entity_types) {
* Helper function to enable entity translations.
*/
function field_test_entity_info_translatable($entity_type_id = NULL, $translatable = NULL) {
$stored_value = &drupal_static(__FUNCTION__, array());
$stored_value = &drupal_static(__FUNCTION__, []);
if (isset($entity_type_id)) {
$entity_manager = \Drupal::entityManager();
$original = $entity_manager->getDefinition($entity_type_id);

View file

@ -34,7 +34,7 @@ function field_test_field_storage_config_update_forbid(FieldStorageConfigInterfa
* Sample 'default value' callback.
*/
function field_test_default_value(FieldableEntityInterface $entity, FieldDefinitionInterface $definition) {
return array(array('value' => 99));
return [['value' => 99]];
}
/**

View file

@ -66,7 +66,7 @@ function field_test_memorize($key = NULL, $value = NULL) {
if (!isset($key)) {
$return = $memorize;
$memorize = array();
$memorize = [];
return $return;
}
if (is_array($memorize)) {
@ -88,11 +88,11 @@ function field_test_field_storage_config_create(FieldStorageConfigInterface $fie
function field_test_entity_display_build_alter(&$output, $context) {
$display_options = $context['display']->getComponent('test_field');
if (isset($display_options['settings']['alter'])) {
$output['test_field'][] = array('#markup' => 'field_test_entity_display_build_alter');
$output['test_field'][] = ['#markup' => 'field_test_entity_display_build_alter'];
}
if (isset($output['test_field'])) {
$output['test_field'][] = array('#markup' => 'entity language is ' . $context['entity']->language()->getId());
$output['test_field'][] = ['#markup' => 'entity language is ' . $context['entity']->language()->getId()];
}
}

View file

@ -54,11 +54,11 @@ class NestedEntityTestForm extends FormBase {
];
}
$form['save'] = array(
$form['save'] = [
'#type' => 'submit',
'#value' => t('Save'),
'#weight' => 100,
);
];
return $form;
}
@ -101,7 +101,7 @@ class NestedEntityTestForm extends FormBase {
$entity_2 = $form_state->get('entity_2');
$entity_2->save();
drupal_set_message($this->t('test_entities @id_1 and @id_2 have been updated.', array('@id_1' => $entity_1->id(), '@id_2' => $entity_2->id())));
drupal_set_message($this->t('test_entities @id_1 and @id_2 have been updated.', ['@id_1' => $entity_1->id(), '@id_2' => $entity_2->id()]));
}
}

View file

@ -34,7 +34,7 @@ class TestFieldApplicableFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
return array('#markup' => 'Nothing to see here');
return ['#markup' => 'Nothing to see here'];
}
}

View file

@ -26,22 +26,22 @@ class TestFieldDefaultFormatter extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_formatter_setting' => 'dummy test string',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_formatter_setting'] = array(
$element['test_formatter_setting'] = [
'#title' => t('Setting'),
'#type' => 'textfield',
'#size' => 20,
'#default_value' => $this->getSetting('test_formatter_setting'),
'#required' => TRUE,
);
];
return $element;
}
@ -49,8 +49,8 @@ class TestFieldDefaultFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = t('@setting: @value', array('@setting' => 'test_formatter_setting', '@value' => $this->getSetting('test_formatter_setting')));
$summary = [];
$summary[] = t('@setting: @value', ['@setting' => 'test_formatter_setting', '@value' => $this->getSetting('test_formatter_setting')]);
return $summary;
}
@ -58,10 +58,10 @@ class TestFieldDefaultFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = array('#markup' => $this->getSetting('test_formatter_setting') . '|' . $item->value);
$elements[$delta] = ['#markup' => $this->getSetting('test_formatter_setting') . '|' . $item->value];
}
return $elements;

View file

@ -23,25 +23,25 @@ class TestFieldEmptyFormatter extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_empty_string' => '**EMPTY FIELD**',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
if ($items->isEmpty()) {
// For fields with no value, just add the configured "empty" value.
$elements[0] = array('#markup' => $this->getSetting('test_empty_string'));
$elements[0] = ['#markup' => $this->getSetting('test_empty_string')];
}
else {
foreach ($items as $delta => $item) {
// This formatter only needs to output raw for testing.
$elements[$delta] = array('#markup' => $item->value);
$elements[$delta] = ['#markup' => $item->value];
}
}

View file

@ -24,22 +24,22 @@ class TestFieldEmptySettingFormatter extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'field_empty_setting' => '',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['field_empty_setting'] = array(
$element['field_empty_setting'] = [
'#title' => t('Setting'),
'#type' => 'textfield',
'#size' => 20,
'#default_value' => $this->getSetting('field_empty_setting'),
'#required' => TRUE,
);
];
return $element;
}
@ -47,7 +47,7 @@ class TestFieldEmptySettingFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary = [];
$setting = $this->getSetting('field_empty_setting');
if (!empty($setting)) {
$summary[] = t('Default empty setting now has a value.');
@ -59,11 +59,11 @@ class TestFieldEmptySettingFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
if (!empty($items)) {
foreach ($items as $delta => $item) {
$elements[$delta] = array('#markup' => $this->getSetting('field_empty_setting'));
$elements[$delta] = ['#markup' => $this->getSetting('field_empty_setting')];
}
}

View file

@ -26,23 +26,23 @@ class TestFieldMultipleFormatter extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_formatter_setting_multiple' => 'dummy test string',
'alter' => FALSE,
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_formatter_setting_multiple'] = array(
$element['test_formatter_setting_multiple'] = [
'#title' => t('Setting'),
'#type' => 'textfield',
'#size' => 20,
'#default_value' => $this->getSetting('test_formatter_setting_multiple'),
'#required' => TRUE,
);
];
return $element;
}
@ -50,8 +50,8 @@ class TestFieldMultipleFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = t('@setting: @value', array('@setting' => 'test_formatter_setting_multiple', '@value' => $this->getSetting('test_formatter_setting_multiple')));
$summary = [];
$summary[] = t('@setting: @value', ['@setting' => 'test_formatter_setting_multiple', '@value' => $this->getSetting('test_formatter_setting_multiple')]);
return $summary;
}
@ -59,14 +59,14 @@ class TestFieldMultipleFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
if (!empty($items)) {
$array = array();
$array = [];
foreach ($items as $delta => $item) {
$array[] = $delta . ':' . $item->value;
}
$elements[0] = array('#markup' => $this->getSetting('test_formatter_setting_multiple') . '|' . implode('|', $array));
$elements[0] = ['#markup' => $this->getSetting('test_formatter_setting_multiple') . '|' . implode('|', $array)];
}
return $elements;

View file

@ -23,11 +23,11 @@ class TestFieldNoSettingsFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
foreach ($items as $delta => $item) {
// This formatter only needs to output raw for testing.
$elements[$delta] = array('#markup' => $item->value);
$elements[$delta] = ['#markup' => $item->value];
}
return $elements;

View file

@ -25,22 +25,22 @@ class TestFieldPrepareViewFormatter extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_formatter_setting_additional' => 'dummy test string',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_formatter_setting_additional'] = array(
$element['test_formatter_setting_additional'] = [
'#title' => t('Setting'),
'#type' => 'textfield',
'#size' => 20,
'#default_value' => $this->getSetting('test_formatter_setting_additional'),
'#required' => TRUE,
);
];
return $element;
}
@ -48,8 +48,8 @@ class TestFieldPrepareViewFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = t('@setting: @value', array('@setting' => 'test_formatter_setting_additional', '@value' => $this->getSetting('test_formatter_setting_additional')));
$summary = [];
$summary[] = t('@setting: @value', ['@setting' => 'test_formatter_setting_additional', '@value' => $this->getSetting('test_formatter_setting_additional')]);
return $summary;
}
@ -71,10 +71,10 @@ class TestFieldPrepareViewFormatter extends FormatterBase {
* {@inheritdoc}
*/
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = array();
$elements = [];
foreach ($items as $delta => $item) {
$elements[$delta] = array('#markup' => $this->getSetting('test_formatter_setting_additional') . '|' . $item->value . '|' . $item->additional_formatter_value);
$elements[$delta] = ['#markup' => $this->getSetting('test_formatter_setting_additional') . '|' . $item->value . '|' . $item->additional_formatter_value];
}
return $elements;

View file

@ -24,22 +24,22 @@ class TestItem extends FieldItemBase {
* {@inheritdoc}
*/
public static function defaultStorageSettings() {
return array(
return [
'test_field_storage_setting' => 'dummy test string',
'changeable' => 'a changeable field storage setting',
'unchangeable' => 'an unchangeable field storage setting',
'translatable_storage_setting' => 'a translatable field storage setting',
) + parent::defaultStorageSettings();
] + parent::defaultStorageSettings();
}
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return array(
return [
'test_field_setting' => 'dummy test string',
'translatable_field_setting' => 'a translatable field setting',
) + parent::defaultFieldSettings();
] + parent::defaultFieldSettings();
}
/**
@ -57,30 +57,30 @@ class TestItem extends FieldItemBase {
* {@inheritdoc}
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
'columns' => array(
'value' => array(
return [
'columns' => [
'value' => [
'type' => 'int',
'size' => 'medium',
),
),
'indexes' => array(
'value' => array('value'),
),
);
],
],
'indexes' => [
'value' => ['value'],
],
];
}
/**
* {@inheritdoc}
*/
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$form['test_field_storage_setting'] = array(
$form['test_field_storage_setting'] = [
'#type' => 'textfield',
'#title' => t('Field test field storage setting'),
'#default_value' => $this->getSetting('test_field_storage_setting'),
'#required' => FALSE,
'#description' => t('A dummy form element to simulate field storage setting.'),
);
];
return $form;
}
@ -89,13 +89,13 @@ class TestItem extends FieldItemBase {
* {@inheritdoc}
*/
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$form['test_field_setting'] = array(
$form['test_field_setting'] = [
'#type' => 'textfield',
'#title' => t('Field test field setting'),
'#default_value' => $this->getSetting('test_field_setting'),
'#required' => FALSE,
'#description' => t('A dummy form element to simulate field setting.'),
);
];
return $form;
}
@ -105,7 +105,7 @@ class TestItem extends FieldItemBase {
*/
public function delete() {
// Reports that delete() method is executed for testing purposes.
field_test_memorize('field_test_field_delete', array($this->getEntity()));
field_test_memorize('field_test_field_delete', [$this->getEntity()]);
}
/**
@ -115,14 +115,14 @@ class TestItem extends FieldItemBase {
$constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
$constraints = parent::getConstraints();
$constraints[] = $constraint_manager->create('ComplexData', array(
'value' => array(
'TestField' => array(
$constraints[] = $constraint_manager->create('ComplexData', [
'value' => [
'TestField' => [
'value' => -1,
'message' => t('%name does not accept the value @value.', array('%name' => $this->getFieldDefinition()->getLabel(), '@value' => -1)),
)
),
));
'message' => t('%name does not accept the value @value.', ['%name' => $this->getFieldDefinition()->getLabel(), '@value' => -1]),
]
],
]);
return $constraints;
}

View file

@ -27,24 +27,24 @@ class TestFieldWidget extends WidgetBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_widget_setting' => 'dummy test string',
'role' => 'anonymous',
'role2' => 'anonymous',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_widget_setting'] = array(
$element['test_widget_setting'] = [
'#type' => 'textfield',
'#title' => t('Field test field widget setting'),
'#description' => t('A dummy form element to simulate field widget setting.'),
'#default_value' => $this->getSetting('test_widget_setting'),
'#required' => FALSE,
);
];
return $element;
}
@ -52,8 +52,8 @@ class TestFieldWidget extends WidgetBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = t('@setting: @value', array('@setting' => 'test_widget_setting', '@value' => $this->getSetting('test_widget_setting')));
$summary = [];
$summary[] = t('@setting: @value', ['@setting' => 'test_widget_setting', '@value' => $this->getSetting('test_widget_setting')]);
return $summary;
}
@ -61,11 +61,11 @@ class TestFieldWidget extends WidgetBase {
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element += array(
$element += [
'#type' => 'textfield',
'#default_value' => isset($items[$delta]->value) ? $items[$delta]->value : '',
);
return array('value' => $element);
];
return ['value' => $element];
}
/**

View file

@ -29,22 +29,22 @@ class TestFieldWidgetMultiple extends WidgetBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'test_widget_setting_multiple' => 'dummy test string',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['test_widget_setting_multiple'] = array(
$element['test_widget_setting_multiple'] = [
'#type' => 'textfield',
'#title' => t('Field test field widget setting'),
'#description' => t('A dummy form element to simulate field widget setting.'),
'#default_value' => $this->getSetting('test_widget_setting_multiple'),
'#required' => FALSE,
);
];
return $element;
}
@ -52,8 +52,8 @@ class TestFieldWidgetMultiple extends WidgetBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary[] = t('@setting: @value', array('@setting' => 'test_widget_setting_multiple', '@value' => $this->getSetting('test_widget_setting_multiple')));
$summary = [];
$summary[] = t('@setting: @value', ['@setting' => 'test_widget_setting_multiple', '@value' => $this->getSetting('test_widget_setting_multiple')]);
return $summary;
}
@ -61,15 +61,15 @@ class TestFieldWidgetMultiple extends WidgetBase {
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$values = array();
$values = [];
foreach ($items as $item) {
$values[] = $item->value;
}
$element += array(
$element += [
'#type' => 'textfield',
'#default_value' => implode(', ', $values),
'#element_validate' => array(array(get_class($this), 'multipleValidate')),
);
'#element_validate' => [[get_class($this), 'multipleValidate']],
];
return $element;
}
@ -85,9 +85,9 @@ class TestFieldWidgetMultiple extends WidgetBase {
*/
public static function multipleValidate($element, FormStateInterface $form_state) {
$values = array_map('trim', explode(',', $element['#value']));
$items = array();
$items = [];
foreach ($values as $value) {
$items[] = array('value' => $value);
$items[] = ['value' => $value];
}
$form_state->setValueForElement($element, $items);
}

View file

@ -19,7 +19,7 @@ class TestFieldConstraint extends NotEqualTo {
* {@inheritdoc}
*/
public function getRequiredOptions() {
return array('value');
return ['value'];
}
/**

View file

@ -14,11 +14,11 @@ use Drupal\Core\Form\FormStateInterface;
* Implements hook_field_widget_third_party_settings_form().
*/
function field_third_party_test_field_widget_third_party_settings_form(WidgetInterface $plugin, FieldDefinitionInterface $field_definition, $form_mode, $form, FormStateInterface $form_state) {
$element['field_test_widget_third_party_settings_form'] = array(
$element['field_test_widget_third_party_settings_form'] = [
'#type' => 'textfield',
'#title' => t('3rd party widget settings form'),
'#default_value' => $plugin->getThirdPartySetting('field_third_party_test', 'field_test_widget_third_party_settings_form'),
);
];
return $element;
}
@ -34,11 +34,11 @@ function field_third_party_test_field_widget_settings_summary_alter(&$summary, $
* Implements hook_field_formatter_third_party_settings_form().
*/
function field_third_party_test_field_formatter_third_party_settings_form(FormatterInterface $plugin, FieldDefinitionInterface $field_definition, $view_mode, $form, FormStateInterface $form_state) {
$element['field_test_field_formatter_third_party_settings_form'] = array(
$element['field_test_field_formatter_third_party_settings_form'] = [
'#type' => 'textfield',
'#title' => t('3rd party formatter settings form'),
'#default_value' => $plugin->getThirdPartySetting('field_third_party_test', 'field_test_field_formatter_third_party_settings_form'),
);
];
return $element;
}

View file

@ -0,0 +1,229 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\node\Entity\Node;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests creating new entity (e.g. taxonomy-term) from an autocomplete widget.
*
* @group entity_reference
*/
class EntityReferenceAutoCreateTest extends BrowserTestBase {
use EntityReferenceTestTrait;
public static $modules = ['node', 'taxonomy'];
/**
* The name of a content type that will reference $referencedType.
*
* @var string
*/
protected $referencingType;
/**
* The name of a content type that will be referenced by $referencingType.
*
* @var string
*/
protected $referencedType;
protected function setUp() {
parent::setUp();
// Create "referencing" and "referenced" node types.
$referencing = $this->drupalCreateContentType();
$this->referencingType = $referencing->id();
$referenced = $this->drupalCreateContentType();
$this->referencedType = $referenced->id();
FieldStorageConfig::create([
'field_name' => 'test_field',
'entity_type' => 'node',
'translatable' => FALSE,
'entity_types' => [],
'settings' => [
'target_type' => 'node',
],
'type' => 'entity_reference',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
])->save();
FieldConfig::create([
'label' => 'Entity reference field',
'field_name' => 'test_field',
'entity_type' => 'node',
'bundle' => $referencing->id(),
'settings' => [
'handler' => 'default',
'handler_settings' => [
// Reference a single vocabulary.
'target_bundles' => [
$referenced->id(),
],
// Enable auto-create.
'auto_create' => TRUE,
],
],
])->save();
entity_get_display('node', $referencing->id(), 'default')
->setComponent('test_field')
->save();
entity_get_form_display('node', $referencing->id(), 'default')
->setComponent('test_field', [
'type' => 'entity_reference_autocomplete',
])
->save();
$account = $this->drupalCreateUser(['access content', "create $this->referencingType content"]);
$this->drupalLogin($account);
}
/**
* Tests that the autocomplete input element appears and the creation of a new
* entity.
*/
public function testAutoCreate() {
$this->drupalGet('node/add/' . $this->referencingType);
$this->assertFieldByXPath('//input[@id="edit-test-field-0-target-id" and contains(@class, "form-autocomplete")]', NULL, 'The autocomplete input element appears.');
$new_title = $this->randomMachineName();
// Assert referenced node does not exist.
$base_query = \Drupal::entityQuery('node');
$base_query
->condition('type', $this->referencedType)
->condition('title', $new_title);
$query = clone $base_query;
$result = $query->execute();
$this->assertFalse($result, 'Referenced node does not exist yet.');
$edit = [
'title[0][value]' => $this->randomMachineName(),
'test_field[0][target_id]' => $new_title,
];
$this->drupalPostForm("node/add/$this->referencingType", $edit, 'Save');
// Assert referenced node was created.
$query = clone $base_query;
$result = $query->execute();
$this->assertTrue($result, 'Referenced node was created.');
$referenced_nid = key($result);
$referenced_node = Node::load($referenced_nid);
// Assert the referenced node is associated with referencing node.
$result = \Drupal::entityQuery('node')
->condition('type', $this->referencingType)
->execute();
$referencing_nid = key($result);
$referencing_node = Node::load($referencing_nid);
$this->assertEqual($referenced_nid, $referencing_node->test_field->target_id, 'Newly created node is referenced from the referencing node.');
// Now try to view the node and check that the referenced node is shown.
$this->drupalGet('node/' . $referencing_node->id());
$this->assertText($referencing_node->label(), 'Referencing node label found.');
$this->assertText($referenced_node->label(), 'Referenced node label found.');
}
/**
* Tests if an entity reference field having multiple target bundles is
* storing the auto-created entity in the right destination.
*/
public function testMultipleTargetBundles() {
/** @var \Drupal\taxonomy\Entity\Vocabulary[] $vocabularies */
$vocabularies = [];
for ($i = 0; $i < 2; $i++) {
$vid = Unicode::strtolower($this->randomMachineName());
$vocabularies[$i] = Vocabulary::create([
'name' => $this->randomMachineName(),
'vid' => $vid,
]);
$vocabularies[$i]->save();
}
// Create a taxonomy term entity reference field that saves the auto-created
// taxonomy terms in the second vocabulary from the two that were configured
// as targets.
$field_name = Unicode::strtolower($this->randomMachineName());
$handler_settings = [
'target_bundles' => [
$vocabularies[0]->id() => $vocabularies[0]->id(),
$vocabularies[1]->id() => $vocabularies[1]->id(),
],
'auto_create' => TRUE,
'auto_create_bundle' => $vocabularies[1]->id(),
];
$this->createEntityReferenceField('node', $this->referencingType, $field_name, $this->randomString(), 'taxonomy_term', 'default', $handler_settings);
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $fd */
entity_get_form_display('node', $this->referencingType, 'default')
->setComponent($field_name, ['type' => 'entity_reference_autocomplete'])
->save();
$term_name = $this->randomString();
$edit = [
$field_name . '[0][target_id]' => $term_name,
'title[0][value]' => $this->randomString(),
];
$this->drupalPostForm('node/add/' . $this->referencingType, $edit, 'Save');
/** @var \Drupal\taxonomy\Entity\Term $term */
$term = taxonomy_term_load_multiple_by_name($term_name);
$term = reset($term);
// The new term is expected to be stored in the second vocabulary.
$this->assertEqual($vocabularies[1]->id(), $term->bundle());
/** @var \Drupal\field\Entity\FieldConfig $field_config */
$field_config = FieldConfig::loadByName('node', $this->referencingType, $field_name);
$handler_settings = $field_config->getSetting('handler_settings');
// Change the field setting to store the auto-created terms in the first
// vocabulary and test again.
$handler_settings['auto_create_bundle'] = $vocabularies[0]->id();
$field_config->setSetting('handler_settings', $handler_settings);
$field_config->save();
$term_name = $this->randomString();
$edit = [
$field_name . '[0][target_id]' => $term_name,
'title[0][value]' => $this->randomString(),
];
$this->drupalPostForm('node/add/' . $this->referencingType, $edit, 'Save');
/** @var \Drupal\taxonomy\Entity\Term $term */
$term = taxonomy_term_load_multiple_by_name($term_name);
$term = reset($term);
// The second term is expected to be stored in the first vocabulary.
$this->assertEqual($vocabularies[0]->id(), $term->bundle());
// @todo Re-enable this test when WebTestBase::curlHeaderCallback() provides
// a way to catch and assert user-triggered errors.
// Test the case when the field config settings are inconsistent.
//unset($handler_settings['auto_create_bundle']);
//$field_config->setSetting('handler_settings', $handler_settings);
//$field_config->save();
//
//$this->drupalGet('node/add/' . $this->referencingType);
//$error_message = sprintf(
// "Create referenced entities if they don't already exist option is enabled but a specific destination bundle is not set. You should re-visit and fix the settings of the '%s' (%s) field.",
// $field_config->getLabel(),
// $field_config->getName()
//);
//$this->assertErrorLogged($error_message);
}
}

View file

@ -0,0 +1,158 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference;
use Drupal\Component\Utility\Unicode;
use Drupal\Tests\SchemaCheckTestTrait;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\node\Entity\Node;
use Drupal\Tests\BrowserTestBase;
/**
* Tests entity reference field default values storage in CMI.
*
* @group entity_reference
*/
class EntityReferenceFieldDefaultValueTest extends BrowserTestBase {
use SchemaCheckTestTrait;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['field_ui', 'node'];
/**
* A user with permission to administer content types, node fields, etc.
*
* @var \Drupal\user\UserInterface
*/
protected $adminUser;
protected function setUp() {
parent::setUp();
// Create default content type.
$this->drupalCreateContentType(['type' => 'reference_content']);
$this->drupalCreateContentType(['type' => 'referenced_content']);
// Create admin user.
$this->adminUser = $this->drupalCreateUser(['access content', 'administer content types', 'administer node fields', 'administer node form display', 'bypass node access']);
$this->drupalLogin($this->adminUser);
}
/**
* Tests that default values are correctly translated to UUIDs in config.
*/
public function testEntityReferenceDefaultValue() {
// Create a node to be referenced.
$referenced_node = $this->drupalCreateNode(['type' => 'referenced_content']);
$field_name = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'node',
'type' => 'entity_reference',
'settings' => ['target_type' => 'node'],
]);
$field_storage->save();
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'reference_content',
'settings' => [
'handler' => 'default',
'handler_settings' => [
'target_bundles' => ['referenced_content'],
'sort' => ['field' => '_none'],
],
],
]);
$field->save();
// Set created node as default_value.
$field_edit = [
'default_value_input[' . $field_name . '][0][target_id]' => $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')',
];
$this->drupalPostForm('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name, $field_edit, t('Save settings'));
// Check that default value is selected in default value form.
$this->drupalGet('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name);
$this->assertRaw('name="default_value_input[' . $field_name . '][0][target_id]" value="' . $referenced_node->getTitle() . ' (' . $referenced_node->id() . ')', 'The default value is selected in instance settings page');
// Check if the ID has been converted to UUID in config entity.
$config_entity = $this->config('field.field.node.reference_content.' . $field_name)->get();
$this->assertTrue(isset($config_entity['default_value'][0]['target_uuid']), 'Default value contains target_uuid property');
$this->assertEqual($config_entity['default_value'][0]['target_uuid'], $referenced_node->uuid(), 'Content uuid and config entity uuid are the same');
// Ensure the configuration has the expected dependency on the entity that
// is being used a default value.
$this->assertEqual([$referenced_node->getConfigDependencyName()], $config_entity['dependencies']['content']);
// Clear field definitions cache in order to avoid stale cache values.
\Drupal::entityManager()->clearCachedFieldDefinitions();
// Create a new node to check that UUID has been converted to numeric ID.
$new_node = Node::create(['type' => 'reference_content']);
$this->assertEqual($new_node->get($field_name)->offsetGet(0)->target_id, $referenced_node->id());
// Ensure that the entity reference config schemas are correct.
$field_config = $this->config('field.field.node.reference_content.' . $field_name);
$this->assertConfigSchema(\Drupal::service('config.typed'), $field_config->getName(), $field_config->get());
$field_storage_config = $this->config('field.storage.node.' . $field_name);
$this->assertConfigSchema(\Drupal::service('config.typed'), $field_storage_config->getName(), $field_storage_config->get());
}
/**
* Tests that dependencies due to default values can be removed.
*
* @see \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::onDependencyRemoval()
*/
public function testEntityReferenceDefaultConfigValue() {
// Create a node to be referenced.
$referenced_node_type = $this->drupalCreateContentType(['type' => 'referenced_config_to_delete']);
$referenced_node_type2 = $this->drupalCreateContentType(['type' => 'referenced_config_to_preserve']);
$field_name = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'node',
'type' => 'entity_reference',
'settings' => ['target_type' => 'node_type'],
'cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED,
]);
$field_storage->save();
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'reference_content',
'settings' => [
'handler' => 'default',
'handler_settings' => [
'sort' => ['field' => '_none'],
],
],
]);
$field->save();
// Set created node as default_value.
$field_edit = [
'default_value_input[' . $field_name . '][0][target_id]' => $referenced_node_type->label() . ' (' . $referenced_node_type->id() . ')',
'default_value_input[' . $field_name . '][1][target_id]' => $referenced_node_type2->label() . ' (' . $referenced_node_type2->id() . ')',
];
$this->drupalPostForm('admin/structure/types/manage/reference_content/fields/node.reference_content.' . $field_name, $field_edit, t('Save settings'));
// Check that the field has a dependency on the default value.
$config_entity = $this->config('field.field.node.reference_content.' . $field_name)->get();
$this->assertTrue(in_array($referenced_node_type->getConfigDependencyName(), $config_entity['dependencies']['config'], TRUE), 'The node type referenced_config_to_delete is a dependency of the field.');
$this->assertTrue(in_array($referenced_node_type2->getConfigDependencyName(), $config_entity['dependencies']['config'], TRUE), 'The node type referenced_config_to_preserve is a dependency of the field.');
// Check that the field does not have a dependency on the default value
// after deleting the node type.
$referenced_node_type->delete();
$config_entity = $this->config('field.field.node.reference_content.' . $field_name)->get();
$this->assertFalse(in_array($referenced_node_type->getConfigDependencyName(), $config_entity['dependencies']['config'], TRUE), 'The node type referenced_config_to_delete not a dependency of the field.');
$this->assertTrue(in_array($referenced_node_type2->getConfigDependencyName(), $config_entity['dependencies']['config'], TRUE), 'The node type referenced_config_to_preserve is a dependency of the field.');
}
}

View file

@ -0,0 +1,322 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference;
use Drupal\field\Entity\FieldConfig;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests the translation of entity reference field display on nodes.
*
* @group entity_reference
*/
class EntityReferenceFieldTranslatedReferenceViewTest extends BrowserTestBase {
/**
* Flag indicating whether the field is translatable.
*
* @var bool
*/
protected $translatable = TRUE;
/**
* The langcode of the source language.
*
* @var string
*/
protected $baseLangcode = 'en';
/**
* Target langcode for translation.
*
* @var string
*/
protected $translateToLangcode = 'hu';
/**
* The test entity type name.
*
* @var string
*/
protected $testEntityTypeName = 'node';
/**
* Entity type which have the entity reference field.
*
* @var \Drupal\node\Entity\NodeType
*/
protected $referrerType;
/**
* Entity type which can be referenced.
*
* @var \Drupal\node\Entity\NodeType
*/
protected $referencedType;
/**
* The referrer entity.
*
* @var \Drupal\node\Entity\Node
*/
protected $referrerEntity;
/**
* The entity to refer.
*
* @var \Drupal\node\Entity\Node
*/
protected $referencedEntityWithoutTranslation;
/**
* The entity to refer.
*
* @var \Drupal\node\Entity\Node
*/
protected $referencedEntityWithTranslation;
/**
* The machine name of the entity reference field.
*
* @var string
*/
protected $referenceFieldName = 'test_reference_field';
/**
* The label of the untranslated referenced entity, used in assertions.
*
* @var string
*/
protected $labelOfNotTranslatedReference;
/**
* The original label of the referenced entity, used in assertions.
*
* @var string
*/
protected $originalLabel;
/**
* The translated label of the referenced entity, used in assertions.
*
* @var string
*/
protected $translatedLabel;
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'language',
'content_translation',
'node',
];
protected function setUp() {
parent::setUp();
$this->labelOfNotTranslatedReference = $this->randomMachineName();
$this->originalLabel = $this->randomMachineName();
$this->translatedLabel = $this->randomMachineName();
$this->setUpLanguages();
// We setup languages, so we need to ensure that the language manager
// and language path processor is updated.
$this->rebuildContainer();
$this->setUpContentTypes();
$this->enableTranslation();
$this->setUpEntityReferenceField();
$this->createContent();
}
/**
* Tests if the entity is displayed in an entity reference field.
*/
public function testEntityReferenceDisplay() {
// Create a translated referrer entity.
$this->referrerEntity = $this->createReferrerEntity();
$this->assertEntityReferenceDisplay();
// Disable translation for referrer content type.
$this->drupalLogin($this->rootUser);
$this->drupalPostForm('admin/config/regional/content-language', ['settings[node][referrer][translatable]' => FALSE], t('Save configuration'));
// Create a referrer entity without translation.
$this->referrerEntity = $this->createReferrerEntity(FALSE);
$this->assertEntityReferenceDisplay();
}
/**
* Assert entity reference display.
*/
protected function assertEntityReferenceDisplay() {
$url = $this->referrerEntity->urlInfo();
$translation_url = $this->referrerEntity->urlInfo('canonical', ['language' => ConfigurableLanguage::load($this->translateToLangcode)]);
$this->drupalGet($url);
$this->assertText($this->labelOfNotTranslatedReference, 'The label of not translated reference is displayed.');
$this->assertText($this->originalLabel, 'The default label of translated reference is displayed.');
$this->assertNoText($this->translatedLabel, 'The translated label of translated reference is not displayed.');
$this->drupalGet($translation_url);
$this->assertText($this->labelOfNotTranslatedReference, 'The label of not translated reference is displayed.');
$this->assertNoText($this->originalLabel, 'The default label of translated reference is not displayed.');
$this->assertText($this->translatedLabel, 'The translated label of translated reference is displayed.');
}
/**
* Adds additional languages.
*/
protected function setUpLanguages() {
ConfigurableLanguage::createFromLangcode($this->translateToLangcode)->save();
}
/**
* Creates a test subject contents, with translation.
*/
protected function createContent() {
$this->referencedEntityWithTranslation = $this->createReferencedEntityWithTranslation();
$this->referencedEntityWithoutTranslation = $this->createNotTranslatedReferencedEntity();
}
/**
* Enables translations where it needed.
*/
protected function enableTranslation() {
// Enable translation for the entity types and ensure the change is picked
// up.
\Drupal::service('content_translation.manager')->setEnabled($this->testEntityTypeName, $this->referrerType->id(), TRUE);
\Drupal::service('content_translation.manager')->setEnabled($this->testEntityTypeName, $this->referencedType->id(), TRUE);
drupal_static_reset();
\Drupal::entityManager()->clearCachedDefinitions();
\Drupal::service('router.builder')->rebuild();
\Drupal::service('entity.definition_update_manager')->applyUpdates();
}
/**
* Adds term reference field for the article content type.
*/
protected function setUpEntityReferenceField() {
FieldStorageConfig::create([
'field_name' => $this->referenceFieldName,
'entity_type' => $this->testEntityTypeName,
'type' => 'entity_reference',
'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
'translatable' => $this->translatable,
'settings' => [
'allowed_values' => [
[
'target_type' => $this->testEntityTypeName,
],
],
],
])->save();
FieldConfig::create([
'field_name' => $this->referenceFieldName,
'bundle' => $this->referrerType->id(),
'entity_type' => $this->testEntityTypeName,
])
->save();
entity_get_form_display($this->testEntityTypeName, $this->referrerType->id(), 'default')
->setComponent($this->referenceFieldName, [
'type' => 'entity_reference_autocomplete',
])
->save();
entity_get_display($this->testEntityTypeName, $this->referrerType->id(), 'default')
->setComponent($this->referenceFieldName, [
'type' => 'entity_reference_label',
])
->save();
}
/**
* Create content types.
*/
protected function setUpContentTypes() {
$this->referrerType = $this->drupalCreateContentType([
'type' => 'referrer',
'name' => 'Referrer',
]);
$this->referencedType = $this->drupalCreateContentType([
'type' => 'referenced_page',
'name' => 'Referenced Page',
]);
}
/**
* Create a referenced entity with a translation.
*/
protected function createReferencedEntityWithTranslation() {
/** @var \Drupal\node\Entity\Node $node */
$node = entity_create($this->testEntityTypeName, [
'title' => $this->originalLabel,
'type' => $this->referencedType->id(),
'description' => [
'value' => $this->randomMachineName(),
'format' => 'basic_html',
],
'langcode' => $this->baseLangcode,
]);
$node->save();
$node->addTranslation($this->translateToLangcode, [
'title' => $this->translatedLabel,
]);
$node->save();
return $node;
}
/**
* Create the referenced entity.
*/
protected function createNotTranslatedReferencedEntity() {
/** @var \Drupal\node\Entity\Node $node */
$node = entity_create($this->testEntityTypeName, [
'title' => $this->labelOfNotTranslatedReference,
'type' => $this->referencedType->id(),
'description' => [
'value' => $this->randomMachineName(),
'format' => 'basic_html',
],
'langcode' => $this->baseLangcode,
]);
$node->save();
return $node;
}
/**
* Create the referrer entity.
*/
protected function createReferrerEntity($translatable = TRUE) {
/** @var \Drupal\node\Entity\Node $node */
$node = entity_create($this->testEntityTypeName, [
'title' => $this->randomMachineName(),
'type' => $this->referrerType->id(),
'description' => [
'value' => $this->randomMachineName(),
'format' => 'basic_html',
],
$this->referenceFieldName => [
['target_id' => $this->referencedEntityWithTranslation->id()],
['target_id' => $this->referencedEntityWithoutTranslation->id()],
],
'langcode' => $this->baseLangcode,
]);
if ($translatable) {
$node->addTranslation($this->translateToLangcode, $node->toArray());
}
$node->save();
return $node;
}
}

View file

@ -0,0 +1,222 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference;
use Drupal\Component\Utility\SafeMarkup;
use Drupal\config\Tests\AssertConfigEntityImportTrait;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
/**
* Tests various Entity reference UI components.
*
* @group entity_reference
*/
class EntityReferenceIntegrationTest extends BrowserTestBase {
use AssertConfigEntityImportTrait;
use EntityReferenceTestTrait;
/**
* The entity type used in this test.
*
* @var string
*/
protected $entityType = 'entity_test';
/**
* The bundle used in this test.
*
* @var string
*/
protected $bundle = 'entity_test';
/**
* The name of the field used in this test.
*
* @var string
*/
protected $fieldName;
/**
* Modules to install.
*
* @var array
*/
public static $modules = ['config_test', 'entity_test', 'field_ui'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Create a test user.
$web_user = $this->drupalCreateUser(['administer entity_test content', 'administer entity_test fields', 'view test entity']);
$this->drupalLogin($web_user);
}
/**
* Tests the entity reference field with all its supported field widgets.
*/
public function testSupportedEntityTypesAndWidgets() {
foreach ($this->getTestEntities() as $key => $referenced_entities) {
$this->fieldName = 'field_test_' . $referenced_entities[0]->getEntityTypeId();
// Create an Entity reference field.
$this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, $this->fieldName, $referenced_entities[0]->getEntityTypeId(), 'default', [], 2);
// Test the default 'entity_reference_autocomplete' widget.
entity_get_form_display($this->entityType, $this->bundle, 'default')->setComponent($this->fieldName)->save();
$entity_name = $this->randomMachineName();
$edit = [
'name[0][value]' => $entity_name,
$this->fieldName . '[0][target_id]' => $referenced_entities[0]->label() . ' (' . $referenced_entities[0]->id() . ')',
// Test an input of the entity label without a ' (entity_id)' suffix.
$this->fieldName . '[1][target_id]' => $referenced_entities[1]->label(),
];
$this->drupalPostForm($this->entityType . '/add', $edit, t('Save'));
$this->assertFieldValues($entity_name, $referenced_entities);
// Try to post the form again with no modification and check if the field
// values remain the same.
/** @var \Drupal\Core\Entity\EntityStorageInterface $storage */
$storage = $this->container->get('entity_type.manager')->getStorage($this->entityType);
$entity = current($storage->loadByProperties(['name' => $entity_name]));
$this->drupalGet($this->entityType . '/manage/' . $entity->id() . '/edit');
$this->assertFieldByName($this->fieldName . '[0][target_id]', $referenced_entities[0]->label() . ' (' . $referenced_entities[0]->id() . ')');
$this->assertFieldByName($this->fieldName . '[1][target_id]', $referenced_entities[1]->label() . ' (' . $referenced_entities[1]->id() . ')');
$this->drupalPostForm(NULL, [], t('Save'));
$this->assertFieldValues($entity_name, $referenced_entities);
// Test the 'entity_reference_autocomplete_tags' widget.
entity_get_form_display($this->entityType, $this->bundle, 'default')->setComponent($this->fieldName, [
'type' => 'entity_reference_autocomplete_tags',
])->save();
$entity_name = $this->randomMachineName();
$target_id = $referenced_entities[0]->label() . ' (' . $referenced_entities[0]->id() . ')';
// Test an input of the entity label without a ' (entity_id)' suffix.
$target_id .= ', ' . $referenced_entities[1]->label();
$edit = [
'name[0][value]' => $entity_name,
$this->fieldName . '[target_id]' => $target_id,
];
$this->drupalPostForm($this->entityType . '/add', $edit, t('Save'));
$this->assertFieldValues($entity_name, $referenced_entities);
// Try to post the form again with no modification and check if the field
// values remain the same.
$entity = current($storage->loadByProperties(['name' => $entity_name]));
$this->drupalGet($this->entityType . '/manage/' . $entity->id() . '/edit');
$this->assertFieldByName($this->fieldName . '[target_id]', $target_id . ' (' . $referenced_entities[1]->id() . ')');
$this->drupalPostForm(NULL, [], t('Save'));
$this->assertFieldValues($entity_name, $referenced_entities);
// Test all the other widgets supported by the entity reference field.
// Since we don't know the form structure for these widgets, just test
// that editing and saving an already created entity works.
$exclude = ['entity_reference_autocomplete', 'entity_reference_autocomplete_tags'];
$entity = current($storage->loadByProperties(['name' => $entity_name]));
$supported_widgets = \Drupal::service('plugin.manager.field.widget')->getOptions('entity_reference');
$supported_widget_types = array_diff(array_keys($supported_widgets), $exclude);
foreach ($supported_widget_types as $widget_type) {
entity_get_form_display($this->entityType, $this->bundle, 'default')->setComponent($this->fieldName, [
'type' => $widget_type,
])->save();
$this->drupalPostForm($this->entityType . '/manage/' . $entity->id() . '/edit', [], t('Save'));
$this->assertFieldValues($entity_name, $referenced_entities);
}
// Reset to the default 'entity_reference_autocomplete' widget.
entity_get_form_display($this->entityType, $this->bundle, 'default')->setComponent($this->fieldName)->save();
// Set first entity as the default_value.
$field_edit = [
'default_value_input[' . $this->fieldName . '][0][target_id]' => $referenced_entities[0]->label() . ' (' . $referenced_entities[0]->id() . ')',
];
if ($key == 'content') {
$field_edit['settings[handler_settings][target_bundles][' . $referenced_entities[0]->getEntityTypeId() . ']'] = TRUE;
}
$this->drupalPostForm($this->entityType . '/structure/' . $this->bundle . '/fields/' . $this->entityType . '.' . $this->bundle . '.' . $this->fieldName, $field_edit, t('Save settings'));
// Ensure the configuration has the expected dependency on the entity that
// is being used a default value.
$field = FieldConfig::loadByName($this->entityType, $this->bundle, $this->fieldName);
$this->assertTrue(in_array($referenced_entities[0]->getConfigDependencyName(), $field->getDependencies()[$key]), SafeMarkup::format('Expected @type dependency @name found', ['@type' => $key, '@name' => $referenced_entities[0]->getConfigDependencyName()]));
// Ensure that the field can be imported without change even after the
// default value deleted.
$referenced_entities[0]->delete();
// Reload the field since deleting the default value can change the field.
\Drupal::entityManager()->getStorage($field->getEntityTypeId())->resetCache([$field->id()]);
$field = FieldConfig::loadByName($this->entityType, $this->bundle, $this->fieldName);
$this->assertConfigEntityImport($field);
// Once the default value has been removed after saving the dependency
// should be removed.
$field = FieldConfig::loadByName($this->entityType, $this->bundle, $this->fieldName);
$field->save();
$dependencies = $field->getDependencies();
$this->assertFalse(isset($dependencies[$key]) && in_array($referenced_entities[0]->getConfigDependencyName(), $dependencies[$key]), SafeMarkup::format('@type dependency @name does not exist.', ['@type' => $key, '@name' => $referenced_entities[0]->getConfigDependencyName()]));
}
}
/**
* Asserts that the reference field values are correct.
*
* @param string $entity_name
* The name of the test entity.
* @param \Drupal\Core\Entity\EntityInterface[] $referenced_entities
* An array of referenced entities.
*/
protected function assertFieldValues($entity_name, $referenced_entities) {
$entity = current($this->container->get('entity_type.manager')->getStorage(
$this->entityType)->loadByProperties(['name' => $entity_name]));
$this->assertTrue($entity, format_string('%entity_type: Entity found in the database.', ['%entity_type' => $this->entityType]));
$this->assertEqual($entity->{$this->fieldName}->target_id, $referenced_entities[0]->id());
$this->assertEqual($entity->{$this->fieldName}->entity->id(), $referenced_entities[0]->id());
$this->assertEqual($entity->{$this->fieldName}->entity->label(), $referenced_entities[0]->label());
$this->assertEqual($entity->{$this->fieldName}[1]->target_id, $referenced_entities[1]->id());
$this->assertEqual($entity->{$this->fieldName}[1]->entity->id(), $referenced_entities[1]->id());
$this->assertEqual($entity->{$this->fieldName}[1]->entity->label(), $referenced_entities[1]->label());
}
/**
* Creates two content and two config test entities.
*
* @return array
* An array of entity objects.
*/
protected function getTestEntities() {
$config_entity_1 = entity_create('config_test', ['id' => $this->randomMachineName(), 'label' => $this->randomMachineName()]);
$config_entity_1->save();
$config_entity_2 = entity_create('config_test', ['id' => $this->randomMachineName(), 'label' => $this->randomMachineName()]);
$config_entity_2->save();
$content_entity_1 = EntityTest::create(['name' => $this->randomMachineName()]);
$content_entity_1->save();
$content_entity_2 = EntityTest::create(['name' => $this->randomMachineName()]);
$content_entity_2->save();
return [
'config' => [
$config_entity_1,
$config_entity_2,
],
'content' => [
$content_entity_1,
$content_entity_2,
],
];
}
}

View file

@ -0,0 +1,78 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\Core\Entity\Entity\EntityViewDisplay;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
/**
* Tests possible XSS security issues in entity references.
*
* @group entity_reference
*/
class EntityReferenceXSSTest extends BrowserTestBase {
use EntityReferenceTestTrait;
/**
* Modules to enable.
*
* @var array
*/
protected static $modules = ['node'];
/**
* Tests markup is escaped in the entity reference select and label formatter.
*/
public function testEntityReferenceXSS() {
$this->drupalCreateContentType(['type' => 'article']);
// Create a node with markup in the title.
$node_type_one = $this->drupalCreateContentType();
$node = [
'type' => $node_type_one->id(),
'title' => '<em>I am kitten</em>',
];
$referenced_node = $this->drupalCreateNode($node);
$node_type_two = $this->drupalCreateContentType(['name' => '<em>bundle with markup</em>']);
$this->drupalCreateNode([
'type' => $node_type_two->id(),
'title' => 'My bundle has markup',
]);
$this->createEntityReferenceField('node', 'article', 'entity_reference_test', 'Entity Reference test', 'node', 'default', ['target_bundles' => [$node_type_one->id(), $node_type_two->id()]]);
EntityFormDisplay::load('node.article.default')
->setComponent('entity_reference_test', ['type' => 'options_select'])
->save();
EntityViewDisplay::load('node.article.default')
->setComponent('entity_reference_test', ['type' => 'entity_reference_label'])
->save();
// Create a node and reference the node with markup in the title.
$this->drupalLogin($this->rootUser);
$this->drupalGet('node/add/article');
$this->assertEscaped($referenced_node->getTitle());
$this->assertEscaped($node_type_two->label());
$edit = [
'title[0][value]' => $this->randomString(),
'entity_reference_test' => $referenced_node->id()
];
$this->drupalPostForm(NULL, $edit, 'Save and publish');
$this->assertEscaped($referenced_node->getTitle());
// Test the options_buttons type.
EntityFormDisplay::load('node.article.default')
->setComponent('entity_reference_test', ['type' => 'options_buttons'])
->save();
$this->drupalGet('node/add/article');
$this->assertEscaped($referenced_node->getTitle());
// options_buttons does not support optgroups.
$this->assertNoText('bundle with markup');
}
}

View file

@ -0,0 +1,145 @@
<?php
namespace Drupal\Tests\field\Functional\EntityReference\Views;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\BrowserTestBase;
use Drupal\views\Views;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests entity reference selection handler.
*
* @group entity_reference
*/
class SelectionTest extends BrowserTestBase {
public static $modules = ['node', 'views', 'entity_reference_test', 'entity_test'];
/**
* Nodes for testing.
*
* @var array
*/
protected $nodes = [];
/**
* The entity reference field to test.
*
* @var \Drupal\Core\Field\FieldDefinitionInterface
*/
protected $field;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Create nodes.
$type = $this->drupalCreateContentType()->id();
$node1 = $this->drupalCreateNode(['type' => $type]);
$node2 = $this->drupalCreateNode(['type' => $type]);
$node3 = $this->drupalCreateNode();
foreach ([$node1, $node2, $node3] as $node) {
$this->nodes[$node->getType()][$node->id()] = $node->label();
}
// Create a field.
$field_storage = FieldStorageConfig::create([
'field_name' => 'test_field',
'entity_type' => 'entity_test',
'translatable' => FALSE,
'settings' => [
'target_type' => 'node',
],
'type' => 'entity_reference',
'cardinality' => '1',
]);
$field_storage->save();
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'test_bundle',
'settings' => [
'handler' => 'views',
'handler_settings' => [
'view' => [
'view_name' => 'test_entity_reference',
'display_name' => 'entity_reference_1',
'arguments' => [],
],
],
],
]);
$field->save();
$this->field = $field;
}
/**
* Confirm the expected results are returned.
*
* @param array $result
* Query results keyed by node type and nid.
*/
protected function assertResults(array $result) {
$success = FALSE;
foreach ($result as $node_type => $values) {
foreach ($values as $nid => $label) {
if (!$success = $this->nodes[$node_type][$nid] == trim(strip_tags($label))) {
// There was some error, so break.
break;
}
}
}
$this->assertTrue($success, 'Views selection handler returned expected values.');
}
/**
* Tests the selection handler.
*/
public function testSelectionHandler() {
// Get values from selection handler.
$handler = $this->container->get('plugin.manager.entity_reference_selection')->getSelectionHandler($this->field);
$result = $handler->getReferenceableEntities();
$this->assertResults($result);
}
/**
* Tests the selection handler with a relationship.
*/
public function testSelectionHandlerRelationship() {
// Add a relationship to the view.
$view = Views::getView('test_entity_reference');
$view->setDisplay();
$view->displayHandlers->get('default')->setOption('relationships', [
'test_relationship' => [
'id' => 'uid',
'table' => 'node_field_data',
'field' => 'uid',
],
]);
// Add a filter depending on the relationship to the test view.
$view->displayHandlers->get('default')->setOption('filters', [
'uid' => [
'id' => 'uid',
'table' => 'users_field_data',
'field' => 'uid',
'relationship' => 'test_relationship',
]
]);
// Set view to distinct so only one row per node is returned.
$query_options = $view->display_handler->getOption('query');
$query_options['options']['distinct'] = TRUE;
$view->display_handler->setOption('query', $query_options);
$view->save();
// Get values from the selection handler.
$handler = $this->container->get('plugin.manager.entity_reference_selection')->getSelectionHandler($this->field);
$result = $handler->getReferenceableEntities();
$this->assertResults($result);
}
}

View file

@ -0,0 +1,92 @@
<?php
namespace Drupal\Tests\field\Functional;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests Field access.
*
* @group field
*/
class FieldAccessTest extends FieldTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['node', 'field_test'];
/**
* Node entity to use in this test.
*
* @var \Drupal\node\Entity\Node
*/
protected $node;
/**
* Field value to test display on nodes.
*
* @var string
*/
protected $testViewFieldValue;
protected function setUp() {
parent::setUp();
$web_user = $this->drupalCreateUser(['view test_view_field content']);
$this->drupalLogin($web_user);
// Create content type.
$content_type_info = $this->drupalCreateContentType();
$content_type = $content_type_info->id();
$field_storage = [
'field_name' => 'test_view_field',
'entity_type' => 'node',
'type' => 'text',
];
FieldStorageConfig::create($field_storage)->save();
$field = [
'field_name' => $field_storage['field_name'],
'entity_type' => 'node',
'bundle' => $content_type,
];
FieldConfig::create($field)->save();
// Assign display properties for the 'default' and 'teaser' view modes.
foreach (['default', 'teaser'] as $view_mode) {
entity_get_display('node', $content_type, $view_mode)
->setComponent($field_storage['field_name'])
->save();
}
// Create test node.
$this->testViewFieldValue = 'This is some text';
$settings = [];
$settings['type'] = $content_type;
$settings['title'] = 'Field view access test';
$settings['test_view_field'] = [['value' => $this->testViewFieldValue]];
$this->node = $this->drupalCreateNode($settings);
}
/**
* Test that hook_entity_field_access() is called.
*/
public function testFieldAccess() {
// Assert the text is visible.
$this->drupalGet('node/' . $this->node->id());
$this->assertText($this->testViewFieldValue);
// Assert the text is not visible for anonymous users.
// The field_test module implements hook_entity_field_access() which will
// specifically target the 'test_view_field' field.
$this->drupalLogout();
$this->drupalGet('node/' . $this->node->id());
$this->assertNoText($this->testViewFieldValue);
}
}

View file

@ -0,0 +1,59 @@
<?php
namespace Drupal\Tests\field\Functional;
use Drupal\Tests\BrowserTestBase;
/**
* Tests help display for the Field module.
*
* @group field
*/
class FieldHelpTest extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array.
*/
public static $modules = ['field', 'help'];
// Tests field help implementation without optional core modules enabled.
protected $profile = 'minimal';
/**
* The admin user that will be created.
*/
protected $adminUser;
protected function setUp() {
parent::setUp();
// Create the admin user.
$this->adminUser = $this->drupalCreateUser(['access administration pages', 'view the administration theme']);
}
/**
* Test the Field module's help page.
*/
public function testFieldHelp() {
// Log in the admin user.
$this->drupalLogin($this->adminUser);
// Visit the Help page and make sure no warnings or notices are thrown.
$this->drupalGet('admin/help/field');
// Enable the Options, Email and Field API Test modules.
\Drupal::service('module_installer')->install(['options', 'field_test']);
$this->resetAll();
\Drupal::service('plugin.manager.field.widget')->clearCachedDefinitions();
\Drupal::service('plugin.manager.field.field_type')->clearCachedDefinitions();
$this->drupalGet('admin/help/field');
$this->assertLink('Options', 0, 'Options module is listed on the Field help page.');
$this->assertText('Field API Test', 'Modules with field types that do not implement hook_help are listed.');
$this->assertNoLink('Field API Test', 'Modules with field types that do not implement hook_help are not linked.');
$this->assertNoLink('Link', 'Modules that have not been installed, are not listed.');
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace Drupal\Tests\field\Functional;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Language\LanguageInterface;
use Drupal\Tests\BrowserTestBase;
/**
* Parent class for Field API tests.
*/
abstract class FieldTestBase extends BrowserTestBase {
/**
* Generate random values for a field_test field.
*
* @param $cardinality
* Number of values to generate.
* @return
* An array of random values, in the format expected for field values.
*/
public function _generateTestFieldValues($cardinality) {
$values = [];
for ($i = 0; $i < $cardinality; $i++) {
// field_test fields treat 0 as 'empty value'.
$values[$i]['value'] = mt_rand(1, 127);
}
return $values;
}
/**
* Assert that a field has the expected values in an entity.
*
* This function only checks a single column in the field values.
*
* @param EntityInterface $entity
* The entity to test.
* @param $field_name
* The name of the field to test
* @param $expected_values
* The array of expected values.
* @param $langcode
* (Optional) The language code for the values. Defaults to
* \Drupal\Core\Language\LanguageInterface::LANGCODE_DEFAULT.
* @param $column
* (Optional) The name of the column to check. Defaults to 'value'.
*/
public function assertFieldValues(EntityInterface $entity, $field_name, $expected_values, $langcode = LanguageInterface::LANGCODE_DEFAULT, $column = 'value') {
// Re-load the entity to make sure we have the latest changes.
$storage = $this->container->get('entity_type.manager')
->getStorage($entity->getEntityTypeId());
$storage->resetCache([$entity->id()]);
$e = $storage->load($entity->id());
$field = $values = $e->getTranslation($langcode)->$field_name;
// Filter out empty values so that they don't mess with the assertions.
$field->filterEmptyItems();
$values = $field->getValue();
$this->assertEqual(count($values), count($expected_values), 'Expected number of values were saved.');
foreach ($expected_values as $key => $value) {
$this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', ['@value' => $value]));
}
}
}

View file

@ -0,0 +1,136 @@
<?php
namespace Drupal\Tests\field\Functional;
use Drupal\Component\Utility\Unicode;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Entity\FieldConfig;
use Drupal\language\Entity\ConfigurableLanguage;
/**
* Tests multilanguage fields logic that require a full environment.
*
* @group field
*/
class TranslationWebTest extends FieldTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['language', 'field_test', 'entity_test'];
/**
* The name of the field to use in this test.
*
* @var string
*/
protected $fieldName;
/**
* The name of the entity type to use in this test.
*
* @var string
*/
protected $entityTypeId = 'entity_test_mulrev';
/**
* The field storage to use in this test.
*
* @var \Drupal\field\Entity\FieldStorageConfig
*/
protected $fieldStorage;
/**
* The field to use in this test.
*
* @var \Drupal\field\Entity\FieldConfig
*/
protected $field;
protected function setUp() {
parent::setUp();
$this->fieldName = Unicode::strtolower($this->randomMachineName() . '_field_name');
$field_storage = [
'field_name' => $this->fieldName,
'entity_type' => $this->entityTypeId,
'type' => 'test_field',
'cardinality' => 4,
];
FieldStorageConfig::create($field_storage)->save();
$this->fieldStorage = FieldStorageConfig::load($this->entityTypeId . '.' . $this->fieldName);
$field = [
'field_storage' => $this->fieldStorage,
'bundle' => $this->entityTypeId,
];
FieldConfig::create($field)->save();
$this->field = FieldConfig::load($this->entityTypeId . '.' . $field['bundle'] . '.' . $this->fieldName);
entity_get_form_display($this->entityTypeId, $this->entityTypeId, 'default')
->setComponent($this->fieldName)
->save();
for ($i = 0; $i < 3; ++$i) {
ConfigurableLanguage::create([
'id' => 'l' . $i,
'label' => $this->randomString(),
])->save();
}
}
/**
* Tests field translations when creating a new revision.
*/
public function testFieldFormTranslationRevisions() {
$web_user = $this->drupalCreateUser(['view test entity', 'administer entity_test content']);
$this->drupalLogin($web_user);
// Prepare the field translations.
field_test_entity_info_translatable($this->entityTypeId, TRUE);
$entity = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)
->create();
$available_langcodes = array_flip(array_keys($this->container->get('language_manager')->getLanguages()));
$field_name = $this->fieldStorage->getName();
// Store the field translations.
ksort($available_langcodes);
$entity->langcode->value = key($available_langcodes);
foreach ($available_langcodes as $langcode => $value) {
$translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
$translation->{$field_name}->value = $value + 1;
}
$entity->save();
// Create a new revision.
$edit = [
"{$field_name}[0][value]" => $entity->{$field_name}->value,
'revision' => TRUE,
];
$this->drupalPostForm($this->entityTypeId . '/manage/' . $entity->id() . '/edit', $edit, t('Save'));
// Check translation revisions.
$this->checkTranslationRevisions($entity->id(), $entity->getRevisionId(), $available_langcodes);
$this->checkTranslationRevisions($entity->id(), $entity->getRevisionId() + 1, $available_langcodes);
}
/**
* Check if the field translation attached to the entity revision identified
* by the passed arguments were correctly stored.
*/
private function checkTranslationRevisions($id, $revision_id, $available_langcodes) {
$field_name = $this->fieldStorage->getName();
$entity = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)
->loadRevision($revision_id);
foreach ($available_langcodes as $langcode => $value) {
$passed = $entity->getTranslation($langcode)->{$field_name}->value == $value + 1;
$this->assertTrue($passed, format_string('The @language translation for revision @revision was correctly stored', ['@language' => $langcode, '@revision' => $entity->getRevisionId()]));
}
}
}

View file

@ -23,11 +23,11 @@ class BooleanItemTest extends FieldKernelTestBase {
parent::setUp();
// Create a boolean field and storage for validation.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'field_boolean',
'entity_type' => 'entity_test',
'type' => 'boolean',
))->save();
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_boolean',
@ -36,9 +36,9 @@ class BooleanItemTest extends FieldKernelTestBase {
// Create a form display for the default form mode.
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent('field_boolean', array(
->setComponent('field_boolean', [
'type' => 'boolean_checkbox',
))
])
->save();
}

View file

@ -58,7 +58,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
* @param $actual_hooks
* The array of actual hook invocations recorded by field_test_memorize().
*/
function checkHooksInvocations($expected_hooks, $actual_hooks) {
public function checkHooksInvocations($expected_hooks, $actual_hooks) {
foreach ($expected_hooks as $hook => $invocations) {
$actual_invocations = $actual_hooks[$hook];
@ -90,31 +90,31 @@ class BulkDeleteTest extends FieldKernelTestBase {
protected function setUp() {
parent::setUp();
$this->fieldStorages = array();
$this->entities = array();
$this->entitiesByBundles = array();
$this->fieldStorages = [];
$this->entities = [];
$this->entitiesByBundles = [];
// Create two bundles.
$this->bundles = array('bb_1' => 'bb_1', 'bb_2' => 'bb_2');
$this->bundles = ['bb_1' => 'bb_1', 'bb_2' => 'bb_2'];
foreach ($this->bundles as $name => $desc) {
entity_test_create_bundle($name, $desc);
}
// Create two field storages.
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'bf_1',
'entity_type' => $this->entityTypeId,
'type' => 'test_field',
'cardinality' => 1
));
]);
$field_storage->save();
$this->fieldStorages[] = $field_storage;
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'bf_2',
'entity_type' => $this->entityTypeId,
'type' => 'test_field',
'cardinality' => 4
));
]);
$field_storage->save();
$this->fieldStorages[] = $field_storage;
@ -130,7 +130,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
for ($i = 0; $i < 10; $i++) {
$entity = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)
->create(array('type' => $bundle));
->create(['type' => $bundle]);
foreach ($this->fieldStorages as $field_storage) {
$entity->{$field_storage->getName()}->setValue($this->_generateTestFieldValues($field_storage->getCardinality()));
}
@ -158,7 +158,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
* This tests how EntityFieldQuery interacts with field deletion and could be
* moved to FieldCrudTestCase, but depends on this class's setUp().
*/
function testDeleteField() {
public function testDeleteField() {
$bundle = reset($this->bundles);
$field_storage = reset($this->fieldStorages);
$field_name = $field_storage->getName();
@ -175,7 +175,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
$field->delete();
// The field still exists, deleted.
$fields = entity_load_multiple_by_properties('field_config', array('field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 1, 'There is one deleted field');
$field = $fields[$field->uuid()];
$this->assertEqual($field->getTargetBundle(), $bundle, 'The deleted field is for the correct bundle');
@ -218,12 +218,12 @@ class BulkDeleteTest extends FieldKernelTestBase {
$bundle = reset($this->bundles);
// Create another field storage.
$field_name = 'bf_3';
$deleted_field_storage = FieldStorageConfig::create(array(
$deleted_field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => $this->entityTypeId,
'type' => 'test_field',
'cardinality' => 1
));
]);
$deleted_field_storage->save();
// Create the field.
FieldConfig::create([
@ -234,7 +234,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
for ($i = 0; $i < 20; $i++) {
$entity = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)
->create(array('type' => $bundle));
->create(['type' => $bundle]);
$entity->{$field_name}->setValue($this->_generateTestFieldValues(1));
$entity->save();
}
@ -245,16 +245,16 @@ class BulkDeleteTest extends FieldKernelTestBase {
$deleted_field_uuid = $deleted_field->uuid();
// Reload the field storage.
$field_storages = entity_load_multiple_by_properties('field_storage_config', array('uuid' => $deleted_field_storage->uuid(), 'include_deleted' => TRUE));
$field_storages = entity_load_multiple_by_properties('field_storage_config', ['uuid' => $deleted_field_storage->uuid(), 'include_deleted' => TRUE]);
$deleted_field_storage = reset($field_storages);
// Create the field again.
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => $this->entityTypeId,
'type' => 'test_field',
'cardinality' => 1
));
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
@ -262,14 +262,14 @@ class BulkDeleteTest extends FieldKernelTestBase {
])->save();
// The field still exists, deleted, with the same field name.
$fields = entity_load_multiple_by_properties('field_config', array('uuid' => $deleted_field_uuid, 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['uuid' => $deleted_field_uuid, 'include_deleted' => TRUE]);
$this->assertTrue(isset($fields[$deleted_field_uuid]) && $fields[$deleted_field_uuid]->isDeleted(), 'The field exists and is deleted');
$this->assertTrue(isset($fields[$deleted_field_uuid]) && $fields[$deleted_field_uuid]->getName() == $field_name);
for ($i = 0; $i < 10; $i++) {
$entity = $this->container->get('entity_type.manager')
->getStorage($this->entityTypeId)
->create(array('type' => $bundle));
->create(['type' => $bundle]);
$entity->{$field_name}->setValue($this->_generateTestFieldValues(1));
$entity->save();
}
@ -289,13 +289,13 @@ class BulkDeleteTest extends FieldKernelTestBase {
$this->assertFalse(\Drupal::database()->schema()->tableExists($deleted_table_name));
// The field has been removed from the system.
$fields = entity_load_multiple_by_properties('field_config', array('field_storage_uuid' => $deleted_field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['field_storage_uuid' => $deleted_field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 0, 'The field is gone');
// Verify there are still 10 entries in the main table.
$count = \Drupal::database()
->select('entity_test__' . $field_name, 'f')
->fields('f', array('entity_id'))
->fields('f', ['entity_id'])
->condition('bundle', $bundle)
->countQuery()
->execute()
@ -307,7 +307,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
* Verify that field data items and fields are purged when a field storage is
* deleted.
*/
function testPurgeField() {
public function testPurgeField() {
// Start recording hook invocations.
field_test_memorize();
@ -340,7 +340,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
// FieldItemInterface::delete() should have been called once for each entity in the
// bundle.
$actual_hooks = field_test_memorize();
$hooks = array();
$hooks = [];
$entities = $this->entitiesByBundles[$bundle];
foreach ($entities as $id => $entity) {
$hooks['field_test_field_delete'][] = $entity;
@ -348,19 +348,19 @@ class BulkDeleteTest extends FieldKernelTestBase {
$this->checkHooksInvocations($hooks, $actual_hooks);
// The field still exists, deleted.
$fields = entity_load_multiple_by_properties('field_config', array('field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 1, 'There is one deleted field');
// Purge the field.
field_purge_batch($batch_size);
// The field is gone.
$fields = entity_load_multiple_by_properties('field_config', array('field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['field_storage_uuid' => $field_storage->uuid(), 'deleted' => TRUE, 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 0, 'The field is gone');
// The field storage still exists, not deleted, because it has a second
// field.
$storages = entity_load_multiple_by_properties('field_storage_config', array('uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
$storages = entity_load_multiple_by_properties('field_storage_config', ['uuid' => $field_storage->uuid(), 'include_deleted' => TRUE]);
$this->assertTrue(isset($storages[$field_storage->uuid()]), 'The field storage exists and is not deleted');
}
@ -368,7 +368,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
* Verify that field storages are preserved and purged correctly as multiple
* fields are deleted and purged.
*/
function testPurgeFieldStorage() {
public function testPurgeFieldStorage() {
// Start recording hook invocations.
field_test_memorize();
@ -391,7 +391,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
// FieldItemInterface::delete() should have been called once for each entity in the
// bundle.
$actual_hooks = field_test_memorize();
$hooks = array();
$hooks = [];
$entities = $this->entitiesByBundles[$bundle];
foreach ($entities as $id => $entity) {
$hooks['field_test_field_delete'][] = $entity;
@ -399,17 +399,17 @@ class BulkDeleteTest extends FieldKernelTestBase {
$this->checkHooksInvocations($hooks, $actual_hooks);
// The field still exists, deleted.
$fields = entity_load_multiple_by_properties('field_config', array('uuid' => $field->uuid(), 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['uuid' => $field->uuid(), 'include_deleted' => TRUE]);
$this->assertTrue(isset($fields[$field->uuid()]) && $fields[$field->uuid()]->isDeleted(), 'The field exists and is deleted');
// Purge again to purge the field.
field_purge_batch(0);
// The field is gone.
$fields = entity_load_multiple_by_properties('field_config', array('uuid' => $field->uuid(), 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['uuid' => $field->uuid(), 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 0, 'The field is purged.');
// The field storage still exists, not deleted.
$storages = entity_load_multiple_by_properties('field_storage_config', array('uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
$storages = entity_load_multiple_by_properties('field_storage_config', ['uuid' => $field_storage->uuid(), 'include_deleted' => TRUE]);
$this->assertTrue(isset($storages[$field_storage->uuid()]) && !$storages[$field_storage->uuid()]->isDeleted(), 'The field storage exists and is not deleted');
// Delete the second field.
@ -426,7 +426,7 @@ class BulkDeleteTest extends FieldKernelTestBase {
// Check hooks invocations (same as above, for the 2nd bundle).
$actual_hooks = field_test_memorize();
$hooks = array();
$hooks = [];
$entities = $this->entitiesByBundles[$bundle];
foreach ($entities as $id => $entity) {
$hooks['field_test_field_delete'][] = $entity;
@ -434,18 +434,18 @@ class BulkDeleteTest extends FieldKernelTestBase {
$this->checkHooksInvocations($hooks, $actual_hooks);
// The field and the storage still exist, deleted.
$fields = entity_load_multiple_by_properties('field_config', array('uuid' => $field->uuid(), 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['uuid' => $field->uuid(), 'include_deleted' => TRUE]);
$this->assertTrue(isset($fields[$field->uuid()]) && $fields[$field->uuid()]->isDeleted(), 'The field exists and is deleted');
$storages = entity_load_multiple_by_properties('field_storage_config', array('uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
$storages = entity_load_multiple_by_properties('field_storage_config', ['uuid' => $field_storage->uuid(), 'include_deleted' => TRUE]);
$this->assertTrue(isset($storages[$field_storage->uuid()]) && $storages[$field_storage->uuid()]->isDeleted(), 'The field storage exists and is deleted');
// Purge again to purge the field and the storage.
field_purge_batch(0);
// The field and the storage are gone.
$fields = entity_load_multiple_by_properties('field_config', array('uuid' => $field->uuid(), 'include_deleted' => TRUE));
$fields = entity_load_multiple_by_properties('field_config', ['uuid' => $field->uuid(), 'include_deleted' => TRUE]);
$this->assertEqual(count($fields), 0, 'The field is purged.');
$storages = entity_load_multiple_by_properties('field_storage_config', array('uuid' => $field_storage->uuid(), 'include_deleted' => TRUE));
$storages = entity_load_multiple_by_properties('field_storage_config', ['uuid' => $field_storage->uuid(), 'include_deleted' => TRUE]);
$this->assertEqual(count($storages), 0, 'The field storage is purged.');
}

View file

@ -69,33 +69,33 @@ class DisplayApiTest extends FieldKernelTestBase {
$this->label = $this->randomMachineName();
$this->cardinality = 4;
$field_storage = array(
$field_storage = [
'field_name' => $this->fieldName,
'entity_type' => 'entity_test',
'type' => 'test_field',
'cardinality' => $this->cardinality,
);
$field = array(
];
$field = [
'field_name' => $this->fieldName,
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
'label' => $this->label,
);
];
$this->displayOptions = array(
'default' => array(
$this->displayOptions = [
'default' => [
'type' => 'field_test_default',
'settings' => array(
'settings' => [
'test_formatter_setting' => $this->randomMachineName(),
),
),
'teaser' => array(
],
],
'teaser' => [
'type' => 'field_test_default',
'settings' => array(
'settings' => [
'test_formatter_setting' => $this->randomMachineName(),
),
),
);
],
],
];
FieldStorageConfig::create($field_storage)->save();
FieldConfig::create($field)->save();
@ -104,7 +104,7 @@ class DisplayApiTest extends FieldKernelTestBase {
->setComponent($this->fieldName, $this->displayOptions['default'])
->save();
// Create a display for the teaser view mode.
EntityViewMode::create(array('id' => 'entity_test.teaser', 'targetEntityType' => 'entity_test'))->save();
EntityViewMode::create(['id' => 'entity_test.teaser', 'targetEntityType' => 'entity_test'])->save();
entity_get_display($field['entity_type'], $field['bundle'], 'teaser')
->setComponent($this->fieldName, $this->displayOptions['teaser'])
->save();
@ -119,11 +119,11 @@ class DisplayApiTest extends FieldKernelTestBase {
/**
* Tests the FieldItemListInterface::view() method.
*/
function testFieldItemListView() {
public function testFieldItemListView() {
$items = $this->entity->get($this->fieldName);
\Drupal::service('theme_handler')->install(['classy']);
\Drupal::service('theme_handler')->setDefault('classy');
$this->config('system.theme')->set('default', 'classy')->save();
// No display settings: check that default display settings are used.
$build = $items->view();
@ -132,66 +132,66 @@ class DisplayApiTest extends FieldKernelTestBase {
$setting = $settings['test_formatter_setting'];
$this->assertText($this->label, 'Label was displayed.');
foreach ($this->values as $delta => $value) {
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// Display settings: Check hidden field.
$display = array(
$display = [
'label' => 'hidden',
'type' => 'field_test_multiple',
'settings' => array(
'settings' => [
'test_formatter_setting_multiple' => $this->randomMachineName(),
'alter' => TRUE,
),
);
],
];
$build = $items->view($display);
$this->render($build);
$setting = $display['settings']['test_formatter_setting_multiple'];
$this->assertNoText($this->label, 'Label was not displayed.');
$this->assertText('field_test_entity_display_build_alter', 'Alter fired, display passed.');
$this->assertText('entity language is en', 'Language is placed onto the context.');
$array = array();
$array = [];
foreach ($this->values as $delta => $value) {
$array[] = $delta . ':' . $value['value'];
}
$this->assertText($setting . '|' . implode('|', $array), 'Values were displayed with expected setting.');
// Display settings: Check visually_hidden field.
$display = array(
$display = [
'label' => 'visually_hidden',
'type' => 'field_test_multiple',
'settings' => array(
'settings' => [
'test_formatter_setting_multiple' => $this->randomMachineName(),
'alter' => TRUE,
),
);
],
];
$build = $items->view($display);
$this->render($build);
$setting = $display['settings']['test_formatter_setting_multiple'];
$this->assertRaw('visually-hidden', 'Label was visually hidden.');
$this->assertText('field_test_entity_display_build_alter', 'Alter fired, display passed.');
$this->assertText('entity language is en', 'Language is placed onto the context.');
$array = array();
$array = [];
foreach ($this->values as $delta => $value) {
$array[] = $delta . ':' . $value['value'];
}
$this->assertText($setting . '|' . implode('|', $array), 'Values were displayed with expected setting.');
// Check the prepare_view steps are invoked.
$display = array(
$display = [
'label' => 'hidden',
'type' => 'field_test_with_prepare_view',
'settings' => array(
'settings' => [
'test_formatter_setting_additional' => $this->randomMachineName(),
),
);
],
];
$build = $items->view($display);
$this->render($build);
$setting = $display['settings']['test_formatter_setting_additional'];
$this->assertNoText($this->label, 'Label was not displayed.');
$this->assertNoText('field_test_entity_display_build_alter', 'Alter not fired.');
foreach ($this->values as $delta => $value) {
$this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// View mode: check that display settings specified in the display object
@ -201,7 +201,7 @@ class DisplayApiTest extends FieldKernelTestBase {
$setting = $this->displayOptions['teaser']['settings']['test_formatter_setting'];
$this->assertText($this->label, 'Label was displayed.');
foreach ($this->values as $delta => $value) {
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// Unknown view mode: check that display settings for 'default' view mode
@ -211,14 +211,14 @@ class DisplayApiTest extends FieldKernelTestBase {
$setting = $this->displayOptions['default']['settings']['test_formatter_setting'];
$this->assertText($this->label, 'Label was displayed.');
foreach ($this->values as $delta => $value) {
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
}
/**
* Tests the FieldItemInterface::view() method.
*/
function testFieldItemView() {
public function testFieldItemView() {
// No display settings: check that default display settings are used.
$settings = \Drupal::service('plugin.manager.field.formatter')->getDefaultSettings('field_test_default');
$setting = $settings['test_formatter_setting'];
@ -226,37 +226,37 @@ class DisplayApiTest extends FieldKernelTestBase {
$item = $this->entity->{$this->fieldName}[$delta];
$build = $item->view();
$this->render($build);
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// Check that explicit display settings are used.
$display = array(
$display = [
'type' => 'field_test_multiple',
'settings' => array(
'settings' => [
'test_formatter_setting_multiple' => $this->randomMachineName(),
),
);
],
];
$setting = $display['settings']['test_formatter_setting_multiple'];
foreach ($this->values as $delta => $value) {
$item = $this->entity->{$this->fieldName}[$delta];
$build = $item->view($display);
$this->render($build);
$this->assertText($setting . '|0:' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|0:' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// Check that prepare_view steps are invoked.
$display = array(
$display = [
'type' => 'field_test_with_prepare_view',
'settings' => array(
'settings' => [
'test_formatter_setting_additional' => $this->randomMachineName(),
),
);
],
];
$setting = $display['settings']['test_formatter_setting_additional'];
foreach ($this->values as $delta => $value) {
$item = $this->entity->{$this->fieldName}[$delta];
$build = $item->view($display);
$this->render($build);
$this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'] . '|' . ($value['value'] + 1), format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// View mode: check that display settings specified in the field are used.
@ -265,7 +265,7 @@ class DisplayApiTest extends FieldKernelTestBase {
$item = $this->entity->{$this->fieldName}[$delta];
$build = $item->view('teaser');
$this->render($build);
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
// Unknown view mode: check that display settings for 'default' view mode
@ -275,22 +275,22 @@ class DisplayApiTest extends FieldKernelTestBase {
$item = $this->entity->{$this->fieldName}[$delta];
$build = $item->view('unknown_view_mode');
$this->render($build);
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', array('@delta' => $delta)));
$this->assertText($setting . '|' . $value['value'], format_string('Value @delta was displayed with expected setting.', ['@delta' => $delta]));
}
}
/**
* Tests that the prepareView() formatter method still fires for empty values.
*/
function testFieldEmpty() {
public function testFieldEmpty() {
// Uses \Drupal\field_test\Plugin\Field\FieldFormatter\TestFieldEmptyFormatter.
$display = array(
$display = [
'label' => 'hidden',
'type' => 'field_empty_test',
'settings' => array(
'settings' => [
'test_empty_string' => '**EMPTY FIELD**' . $this->randomMachineName(),
),
);
],
];
// $this->entity is set by the setUp() method and by default contains 4
// numeric values. We only want to test the display of this one field.
$build = $this->entity->get($this->fieldName)->view($display);
@ -300,7 +300,7 @@ class DisplayApiTest extends FieldKernelTestBase {
$this->assertNoText($display['settings']['test_empty_string']);
// Now remove the values from the test field and retest.
$this->entity->{$this->fieldName} = array();
$this->entity->{$this->fieldName} = [];
$this->entity->save();
$build = $this->entity->get($this->fieldName)->view($display);
$this->render($build);

View file

@ -20,11 +20,11 @@ class EmailItemTest extends FieldKernelTestBase {
parent::setUp();
// Create an email field storage and field for validation.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'field_email',
'entity_type' => 'entity_test',
'type' => 'email',
))->save();
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_email',
@ -33,9 +33,9 @@ class EmailItemTest extends FieldKernelTestBase {
// Create a form display for the default form mode.
entity_get_form_display('entity_test', 'entity_test', 'default')
->setComponent('field_email', array(
->setComponent('field_email', [
'type' => 'email_default',
))
])
->save();
}

View file

@ -65,10 +65,10 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
// Use Classy theme for testing markup output.
\Drupal::service('theme_handler')->install(['classy']);
\Drupal::service('theme_handler')->setDefault('classy');
$this->config('system.theme')->set('default', 'classy')->save();
$this->installEntitySchema('entity_test');
// Grant the 'view test entity' permission.
$this->installConfig(array('user'));
$this->installConfig(['user']);
Role::load(RoleInterface::ANONYMOUS_ID)
->grantPermission('view test entity')
->save();
@ -76,16 +76,16 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
// The label formatter rendering generates links, so build the router.
$this->container->get('router.builder')->rebuild();
$this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType, 'default', array(), FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
$this->createEntityReferenceField($this->entityType, $this->bundle, $this->fieldName, 'Field test', $this->entityType, 'default', [], FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);
// Set up a field, so that the entity that'll be referenced bubbles up a
// cache tag when rendering it entirely.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'body',
'entity_type' => $this->entityType,
'type' => 'text',
'settings' => array(),
))->save();
'settings' => [],
])->save();
FieldConfig::create([
'entity_type' => $this->entityType,
'bundle' => $this->bundle,
@ -93,35 +93,35 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
'label' => 'Body',
])->save();
entity_get_display($this->entityType, $this->bundle, 'default')
->setComponent('body', array(
->setComponent('body', [
'type' => 'text_default',
'settings' => array(),
))
'settings' => [],
])
->save();
FilterFormat::create(array(
FilterFormat::create([
'format' => 'full_html',
'name' => 'Full HTML',
))->save();
])->save();
// Create the entity to be referenced.
$this->referencedEntity = $this->container->get('entity_type.manager')
->getStorage($this->entityType)
->create(array('name' => $this->randomMachineName()));
$this->referencedEntity->body = array(
->create(['name' => $this->randomMachineName()]);
$this->referencedEntity->body = [
'value' => '<p>Hello, world!</p>',
'format' => 'full_html',
);
];
$this->referencedEntity->save();
// Create another entity to be referenced but do not save it.
$this->unsavedReferencedEntity = $this->container->get('entity_type.manager')
->getStorage($this->entityType)
->create(array('name' => $this->randomMachineName()));
$this->unsavedReferencedEntity->body = array(
->create(['name' => $this->randomMachineName()]);
$this->unsavedReferencedEntity->body = [
'value' => '<p>Hello, unsaved world!</p>',
'format' => 'full_html',
);
];
}
/**
@ -137,7 +137,7 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
$referencing_entity = $this->container->get('entity_type.manager')
->getStorage($this->entityType)
->create(array('name' => $this->randomMachineName()));
->create(['name' => $this->randomMachineName()]);
$referencing_entity->save();
$referencing_entity->{$field_name}->entity = $this->referencedEntity;
@ -150,16 +150,16 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
foreach ($formatter_manager->getOptions('entity_reference') as $formatter => $name) {
// Set formatter type for the 'full' view mode.
entity_get_display($this->entityType, $this->bundle, 'default')
->setComponent($field_name, array(
->setComponent($field_name, [
'type' => $formatter,
))
])
->save();
// Invoke entity view.
entity_view($referencing_entity, 'default');
// Verify the un-accessible item still exists.
$this->assertEqual($referencing_entity->{$field_name}->target_id, $this->referencedEntity->id(), format_string('The un-accessible item still exists after @name formatter was executed.', array('@name' => $name)));
$this->assertEqual($referencing_entity->{$field_name}->target_id, $this->referencedEntity->id(), format_string('The un-accessible item still exists after @name formatter was executed.', ['@name' => $name]));
}
}
@ -198,7 +198,7 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
$this->assertEqual($build[0]['#markup'], 'default | ' . $this->referencedEntity->label() . $expected_rendered_name_field_1 . $expected_rendered_body_field_1, sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
$expected_cache_tags = Cache::mergeTags(\Drupal::entityManager()->getViewBuilder($this->entityType)->getCacheTags(), $this->referencedEntity->getCacheTags());
$expected_cache_tags = Cache::mergeTags($expected_cache_tags, FilterFormat::load('full_html')->getCacheTags());
$this->assertEqual($build[0]['#cache']['tags'], $expected_cache_tags, format_string('The @formatter formatter has the expected cache tags.', array('@formatter' => $formatter)));
$this->assertEqual($build[0]['#cache']['tags'], $expected_cache_tags, format_string('The @formatter formatter has the expected cache tags.', ['@formatter' => $formatter]));
// Test the second field item.
$expected_rendered_name_field_2 = '
@ -338,37 +338,37 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
'max-age' => Cache::PERMANENT,
];
$this->assertEqual($build['#cache'], $expected_field_cacheability, 'The field render array contains the entity access cacheability metadata');
$expected_item_1 = array(
$expected_item_1 = [
'#type' => 'link',
'#title' => $this->referencedEntity->label(),
'#url' => $this->referencedEntity->urlInfo(),
'#options' => $this->referencedEntity->urlInfo()->getOptions(),
'#cache' => array(
'#cache' => [
'contexts' => [
'user.permissions',
],
'tags' => $this->referencedEntity->getCacheTags(),
),
);
],
];
$this->assertEqual($renderer->renderRoot($build[0]), $renderer->renderRoot($expected_item_1), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
$this->assertEqual(CacheableMetadata::createFromRenderArray($build[0]), CacheableMetadata::createFromRenderArray($expected_item_1));
// The second referenced entity is "autocreated", therefore not saved and
// lacking any URL info.
$expected_item_2 = array(
$expected_item_2 = [
'#plain_text' => $this->unsavedReferencedEntity->label(),
'#cache' => array(
'#cache' => [
'contexts' => [
'user.permissions',
],
'tags' => $this->unsavedReferencedEntity->getCacheTags(),
'max-age' => Cache::PERMANENT,
),
);
],
];
$this->assertEqual($build[1], $expected_item_2, sprintf('The render array returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
// Test with the 'link' setting set to FALSE.
$build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter, array('link' => FALSE));
$build = $this->buildRenderArray([$this->referencedEntity, $this->unsavedReferencedEntity], $formatter, ['link' => FALSE]);
$this->assertEqual($build[0]['#plain_text'], $this->referencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a saved entity.', $formatter));
$this->assertEqual($build[1]['#plain_text'], $this->unsavedReferencedEntity->label(), sprintf('The markup returned by the %s formatter is correct for an item with a unsaved entity.', $formatter));
@ -379,12 +379,12 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
$field_storage_config->setSetting('target_type', 'entity_test_label');
$field_storage_config->save();
$referenced_entity_with_no_link_template = EntityTestLabel::create(array(
$referenced_entity_with_no_link_template = EntityTestLabel::create([
'name' => $this->randomMachineName(),
));
]);
$referenced_entity_with_no_link_template->save();
$build = $this->buildRenderArray([$referenced_entity_with_no_link_template], $formatter, array('link' => TRUE));
$build = $this->buildRenderArray([$referenced_entity_with_no_link_template], $formatter, ['link' => TRUE]);
$this->assertEqual($build[0]['#plain_text'], $referenced_entity_with_no_link_template->label(), sprintf('The markup returned by the %s formatter is correct for an entity type with no valid link template.', $formatter));
}
@ -403,11 +403,11 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
* @return array
* A render array.
*/
protected function buildRenderArray(array $referenced_entities, $formatter, $formatter_options = array()) {
protected function buildRenderArray(array $referenced_entities, $formatter, $formatter_options = []) {
// Create the entity that will have the entity reference field.
$referencing_entity = $this->container->get('entity_type.manager')
->getStorage($this->entityType)
->create(array('name' => $this->randomMachineName()));
->create(['name' => $this->randomMachineName()]);
$items = $referencing_entity->get($this->fieldName);
@ -417,7 +417,7 @@ class EntityReferenceFormatterTest extends EntityKernelTestBase {
}
// Build the renderable array for the field.
return $items->view(array('type' => $formatter, 'settings' => $formatter_options));
return $items->view(['type' => $formatter, 'settings' => $formatter_options]);
}
}

View file

@ -15,6 +15,7 @@ use Drupal\entity_test\Entity\EntityTestStringId;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\node\NodeInterface;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use Drupal\file\Entity\File;
use Drupal\node\Entity\Node;
@ -174,7 +175,7 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
// Delete terms so we have nothing to reference and try again
$term->delete();
$term2->delete();
$entity = EntityTest::create(array('name' => $this->randomMachineName()));
$entity = EntityTest::create(['name' => $this->randomMachineName()]);
$entity->save();
// Test the generateSampleValue() method.
@ -182,6 +183,15 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
$entity->field_test_taxonomy_term->generateSampleItems();
$entity->field_test_taxonomy_vocabulary->generateSampleItems();
$this->entityValidateAndSave($entity);
// Tests that setting an integer target ID together with an entity object
// succeeds and does not cause any exceptions. There is no assertion here,
// as the assignment should not throw any exceptions and if it does the
// test will fail.
// @see \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::setValue().
$user = User::create(['name' => $this->randomString()]);
$user->save();
$entity = EntityTest::create(['user_id' => ['target_id' => (int) $user->id(), 'entity' => $user]]);
}
/**
@ -243,7 +253,7 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
// Delete terms so we have nothing to reference and try again
$this->vocabulary->delete();
$vocabulary2->delete();
$entity = EntityTest::create(array('name' => $this->randomMachineName()));
$entity = EntityTest::create(['name' => $this->randomMachineName()]);
$entity->save();
}
@ -252,11 +262,11 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
*/
public function testEntityAutoCreate() {
// The term entity is unsaved here.
$term = Term::create(array(
$term = Term::create([
'name' => $this->randomMachineName(),
'vid' => $this->term->bundle(),
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
));
]);
$entity = EntityTest::create();
// Now assign the unsaved term to the field.
$entity->field_test_taxonomy_term->entity = $term;
@ -303,22 +313,22 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
*/
public function testSelectionHandlerSettings() {
$field_name = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => $field_name,
'entity_type' => 'entity_test',
'type' => 'entity_reference',
'settings' => array(
'settings' => [
'target_type' => 'entity_test'
),
));
],
]);
$field_storage->save();
// Do not specify any value for the 'handler' setting in order to verify
// that the default handler with the correct derivative is used.
$field = FieldConfig::create(array(
$field = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'entity_test',
));
]);
$field->save();
$field = FieldConfig::load($field->id());
$this->assertEqual($field->getSetting('handler'), 'default:entity_test');
@ -349,11 +359,11 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
*/
public function testAutocreateValidation() {
// The term entity is unsaved here.
$term = Term::create(array(
$term = Term::create([
'name' => $this->randomMachineName(),
'vid' => $this->term->bundle(),
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
));
]);
$entity = EntityTest::create([
'field_test_taxonomy_term' => [
'entity' => $term,
@ -385,7 +395,7 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
$node = Node::create([
'title' => $title,
'type' => 'node',
'status' => NODE_NOT_PUBLISHED,
'status' => NodeInterface::NOT_PUBLISHED,
]);
$entity = EntityTest::create([
@ -409,14 +419,14 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
$unsaved_unpublished_node = Node::create([
'title' => $unsaved_unpublished_node_title,
'type' => 'node',
'status' => NODE_NOT_PUBLISHED,
'status' => NodeInterface::NOT_PUBLISHED,
]);
$saved_unpublished_node_title = $this->randomString();
$saved_unpublished_node = Node::create([
'title' => $saved_unpublished_node_title,
'type' => 'node',
'status' => NODE_NOT_PUBLISHED,
'status' => NodeInterface::NOT_PUBLISHED,
]);
$saved_unpublished_node->save();
@ -424,7 +434,7 @@ class EntityReferenceItemTest extends FieldKernelTestBase {
$saved_published_node = Node::create([
'title' => $saved_published_node_title,
'type' => 'node',
'status' => NODE_PUBLISHED,
'status' => NodeInterface::PUBLISHED,
]);
$saved_published_node->save();

View file

@ -3,6 +3,7 @@
namespace Drupal\Tests\field\Kernel\EntityReference\Views;
use Drupal\entity_test\Entity\EntityTestMulChanged;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\field\Tests\EntityReference\EntityReferenceTestTrait;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\entity_test\Entity\EntityTestMul;
@ -26,13 +27,14 @@ class EntityReferenceRelationshipTest extends ViewsKernelTestBase {
*
* @var array
*/
public static $testViews = array(
public static $testViews = [
'test_entity_reference_entity_test_view',
'test_entity_reference_entity_test_view_long',
'test_entity_reference_reverse_entity_test_view',
'test_entity_reference_entity_test_mul_view',
'test_entity_reference_reverse_entity_test_mul_view',
);
'test_entity_reference_group_by_empty_relationships',
];
/**
* Modules to install.
@ -46,7 +48,7 @@ class EntityReferenceRelationshipTest extends ViewsKernelTestBase {
*
* @var array
*/
protected $entities = array();
protected $entities = [];
/**
* {@inheritdoc}
@ -71,7 +73,10 @@ class EntityReferenceRelationshipTest extends ViewsKernelTestBase {
// @see \Drupal\Core\Entity\Sql\DefaultTableMapping::generateFieldTableName()
$this->createEntityReferenceField('entity_test_mul_changed', 'entity_test_mul_changed', 'field_test_data_with_a_long_name', 'field_test_data_with_a_long_name', 'entity_test');
ViewTestData::createTestViews(get_class($this), array('entity_reference_test_views'));
// Create reference from entity_test_mul to entity_test cardinality: infinite.
$this->createEntityReferenceField('entity_test_mul', 'entity_test_mul', 'field_data_test_unlimited', 'field_data_test_unlimited', 'entity_test', 'default', [], FieldStorageConfig::CARDINALITY_UNLIMITED);
ViewTestData::createTestViews(get_class($this), ['entity_reference_test_views']);
}
/**
@ -276,4 +281,56 @@ class EntityReferenceRelationshipTest extends ViewsKernelTestBase {
}
}
/**
* Tests group by with optional and empty relationship.
*/
public function testGroupByWithEmptyRelationships() {
$entities = [];
// Create 4 entities with name1 and 3 entities with name2.
for ($i = 1; $i <= 4; $i++) {
$entity = [
'name' => 'name' . $i,
];
$entity = EntityTest::create($entity);
$entities[] = $entity;
$entity->save();
}
$entity = EntityTestMul::create([
'name' => 'name1',
]);
$entity->field_data_test_unlimited = [
['target_id' => $entities[0]->id()],
['target_id' => $entities[1]->id()],
['target_id' => $entities[2]->id()],
];
$entity->save();
$entity = EntityTestMul::create([
'name' => 'name2',
]);
$entity->field_data_test_unlimited = [
['target_id' => $entities[0]->id()],
['target_id' => $entities[1]->id()],
];
$entity->save();
$entity = EntityTestMul::create([
'name' => 'name3',
]);
$entity->field_data_test_unlimited->target_id = $entities[0]->id();
$entity->save();
$view = Views::getView('test_entity_reference_group_by_empty_relationships');
$this->executeView($view);
$this->assertCount(4, $view->result);
// First three results should contain a reference from EntityTestMul.
$this->assertNotEmpty($view->getStyle()->getField(0, 'name_2'));
$this->assertNotEmpty($view->getStyle()->getField(1, 'name_2'));
$this->assertNotEmpty($view->getStyle()->getField(2, 'name_2'));
// Fourth result has no reference from EntityTestMul hence the output for
// should be empty.
$this->assertEqual('', $view->getStyle()->getField(3, 'name_2'));
}
}

View file

@ -23,7 +23,7 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
/**
* Test rendering fields with EntityDisplay build().
*/
function testEntityDisplayBuild() {
public function testEntityDisplayBuild() {
$this->createFieldWithStorage('_2');
$entity_type = 'entity_test';
@ -42,23 +42,23 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
$display = entity_get_display($entity_type, $entity->bundle(), 'full');
$formatter_setting = $this->randomMachineName();
$display_options = array(
$display_options = [
'label' => 'above',
'type' => 'field_test_default',
'settings' => array(
'settings' => [
'test_formatter_setting' => $formatter_setting,
),
);
],
];
$display->setComponent($this->fieldTestData->field_name, $display_options);
$formatter_setting_2 = $this->randomMachineName();
$display_options_2 = array(
$display_options_2 = [
'label' => 'above',
'type' => 'field_test_default',
'settings' => array(
'settings' => [
'test_formatter_setting' => $formatter_setting_2,
),
);
],
];
$display->setComponent($this->fieldTestData->field_name_2, $display_options_2);
// View all fields.
@ -94,13 +94,13 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
// Multiple formatter.
$entity = clone($entity_init);
$formatter_setting = $this->randomMachineName();
$display->setComponent($this->fieldTestData->field_name, array(
$display->setComponent($this->fieldTestData->field_name, [
'label' => 'above',
'type' => 'field_test_multiple',
'settings' => array(
'settings' => [
'test_formatter_setting_multiple' => $formatter_setting,
),
));
],
]);
$content = $display->build($entity);
$this->render($content);
$expected_output = $formatter_setting;
@ -112,13 +112,13 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
// Test a formatter that uses hook_field_formatter_prepare_view().
$entity = clone($entity_init);
$formatter_setting = $this->randomMachineName();
$display->setComponent($this->fieldTestData->field_name, array(
$display->setComponent($this->fieldTestData->field_name, [
'label' => 'above',
'type' => 'field_test_with_prepare_view',
'settings' => array(
'settings' => [
'test_formatter_setting_additional' => $formatter_setting,
),
));
],
]);
$content = $display->build($entity);
$this->render($content);
foreach ($values as $delta => $value) {
@ -133,21 +133,21 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
/**
* Tests rendering fields with EntityDisplay::buildMultiple().
*/
function testEntityDisplayViewMultiple() {
public function testEntityDisplayViewMultiple() {
// Use a formatter that has a prepareView() step.
$display = entity_get_display('entity_test', 'entity_test', 'full')
->setComponent($this->fieldTestData->field_name, array(
->setComponent($this->fieldTestData->field_name, [
'type' => 'field_test_with_prepare_view',
));
]);
// Create two entities.
$entity1 = EntityTest::create(array('id' => 1, 'type' => 'entity_test'));
$entity1 = EntityTest::create(['id' => 1, 'type' => 'entity_test']);
$entity1->{$this->fieldTestData->field_name}->setValue($this->_generateTestFieldValues(1));
$entity2 = EntityTest::create(array('id' => 2, 'type' => 'entity_test'));
$entity2 = EntityTest::create(['id' => 2, 'type' => 'entity_test']);
$entity2->{$this->fieldTestData->field_name}->setValue($this->_generateTestFieldValues(1));
// Run buildMultiple(), and check that the entities come out as expected.
$display->buildMultiple(array($entity1, $entity2));
$display->buildMultiple([$entity1, $entity2]);
$item1 = $entity1->{$this->fieldTestData->field_name}[0];
$this->assertEqual($item1->additional_formatter_value, $item1->value + 1, 'Entity 1 ran through the prepareView() formatter method.');
$item2 = $entity2->{$this->fieldTestData->field_name}[0];
@ -160,9 +160,9 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
* Complements unit test coverage in
* \Drupal\Tests\Core\Entity\Sql\SqlContentEntityStorageTest.
*/
function testEntityCache() {
public function testEntityCache() {
// Initialize random values and a test entity.
$entity_init = EntityTest::create(array('type' => $this->fieldTestData->field->getTargetBundle()));
$entity_init = EntityTest::create(['type' => $this->fieldTestData->field->getTargetBundle()]);
$values = $this->_generateTestFieldValues($this->fieldTestData->field_storage->getCardinality());
// Non-cacheable entity type.
@ -185,9 +185,9 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
$entity_init = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array(
->create([
'type' => $entity_type,
));
]);
// Check that no initial cache entry is present.
$cid = "values:$entity_type:" . $entity->id();
@ -243,15 +243,15 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
* This could be much more thorough, but it does verify that the correct
* widgets show up.
*/
function testEntityFormDisplayBuildForm() {
public function testEntityFormDisplayBuildForm() {
$this->createFieldWithStorage('_2');
$entity_type = 'entity_test';
$entity = entity_create($entity_type, array('id' => 1, 'revision_id' => 1, 'type' => $this->fieldTestData->field->getTargetBundle()));
$entity = entity_create($entity_type, ['id' => 1, 'revision_id' => 1, 'type' => $this->fieldTestData->field->getTargetBundle()]);
// Test generating widgets for all fields.
$display = entity_get_form_display($entity_type, $this->fieldTestData->field->getTargetBundle(), 'default');
$form = array();
$form = [];
$form_state = new FormState();
$display->buildForm($entity, $form, $form_state);
@ -273,7 +273,7 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
$display->removeComponent($name);
}
}
$form = array();
$form = [];
$form_state = new FormState();
$display->buildForm($entity, $form, $form_state);
@ -288,24 +288,24 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
/**
* Tests \Drupal\Core\Entity\Display\EntityFormDisplayInterface::extractFormValues().
*/
function testEntityFormDisplayExtractFormValues() {
public function testEntityFormDisplayExtractFormValues() {
$this->createFieldWithStorage('_2');
$entity_type = 'entity_test';
$entity_init = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => 1, 'revision_id' => 1, 'type' => $this->fieldTestData->field->getTargetBundle()));
->create(['id' => 1, 'revision_id' => 1, 'type' => $this->fieldTestData->field->getTargetBundle()]);
// Build the form for all fields.
$display = entity_get_form_display($entity_type, $this->fieldTestData->field->getTargetBundle(), 'default');
$form = array();
$form = [];
$form_state = new FormState();
$display->buildForm($entity_init, $form, $form_state);
// Simulate incoming values.
// First field.
$values = array();
$weights = array();
$values = [];
$weights = [];
for ($delta = 0; $delta < $this->fieldTestData->field_storage->getCardinality(); $delta++) {
$values[$delta]['value'] = mt_rand(1, 127);
// Assign random weight.
@ -318,8 +318,8 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
// Leave an empty value. 'field_test' fields are empty if empty().
$values[1]['value'] = 0;
// Second field.
$values_2 = array();
$weights_2 = array();
$values_2 = [];
$weights_2 = [];
for ($delta = 0; $delta < $this->fieldTestData->field_storage_2->getCardinality(); $delta++) {
$values_2[$delta]['value'] = mt_rand(1, 127);
// Assign random weight.
@ -345,17 +345,17 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
asort($weights);
asort($weights_2);
$expected_values = array();
$expected_values_2 = array();
$expected_values = [];
$expected_values_2 = [];
foreach ($weights as $key => $value) {
if ($key != 1) {
$expected_values[] = array('value' => $values[$key]['value']);
$expected_values[] = ['value' => $values[$key]['value']];
}
}
$this->assertIdentical($entity->{$this->fieldTestData->field_name}->getValue(), $expected_values, 'Submit filters empty values');
foreach ($weights_2 as $key => $value) {
if ($key != 1) {
$expected_values_2[] = array('value' => $values_2[$key]['value']);
$expected_values_2[] = ['value' => $values_2[$key]['value']];
}
}
$this->assertIdentical($entity->{$this->fieldTestData->field_name_2}->getValue(), $expected_values_2, 'Submit filters empty values');
@ -368,10 +368,10 @@ class FieldAttachOtherTest extends FieldKernelTestBase {
}
$entity = clone($entity_init);
$display->extractFormValues($entity, $form, $form_state);
$expected_values_2 = array();
$expected_values_2 = [];
foreach ($weights_2 as $key => $value) {
if ($key != 1) {
$expected_values_2[] = array('value' => $values_2[$key]['value']);
$expected_values_2[] = ['value' => $values_2[$key]['value']];
}
}
$this->assertTrue($entity->{$this->fieldTestData->field_name}->isEmpty(), 'The first field is empty in the entity object');

View file

@ -24,14 +24,14 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
* Works independently of the underlying field storage backend. Inserts or
* updates random field data and then loads and verifies the data.
*/
function testFieldAttachSaveLoad() {
public function testFieldAttachSaveLoad() {
$entity_type = 'entity_test_rev';
$this->createFieldWithStorage('', $entity_type);
$cardinality = $this->fieldTestData->field_storage->getCardinality();
// TODO : test empty values filtering and "compression" (store consecutive deltas).
// Preparation: create three revisions and store them in $revision array.
$values = array();
$values = [];
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create();
@ -54,17 +54,17 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
$this->assertEqual(count($entity->{$this->fieldTestData->field_name}), $cardinality, 'Current revision: expected number of values');
for ($delta = 0; $delta < $cardinality; $delta++) {
// The field value loaded matches the one inserted or updated.
$this->assertEqual($entity->{$this->fieldTestData->field_name}[$delta]->value, $values[$current_revision][$delta]['value'], format_string('Current revision: expected value %delta was found.', array('%delta' => $delta)));
$this->assertEqual($entity->{$this->fieldTestData->field_name}[$delta]->value, $values[$current_revision][$delta]['value'], format_string('Current revision: expected value %delta was found.', ['%delta' => $delta]));
}
// Confirm each revision loads the correct data.
foreach (array_keys($values) as $revision_id) {
$entity = $storage->loadRevision($revision_id);
// Number of values per field loaded equals the field cardinality.
$this->assertEqual(count($entity->{$this->fieldTestData->field_name}), $cardinality, format_string('Revision %revision_id: expected number of values.', array('%revision_id' => $revision_id)));
$this->assertEqual(count($entity->{$this->fieldTestData->field_name}), $cardinality, format_string('Revision %revision_id: expected number of values.', ['%revision_id' => $revision_id]));
for ($delta = 0; $delta < $cardinality; $delta++) {
// The field value loaded matches the one inserted or updated.
$this->assertEqual($entity->{$this->fieldTestData->field_name}[$delta]->value, $values[$revision_id][$delta]['value'], format_string('Revision %revision_id: expected value %delta was found.', array('%revision_id' => $revision_id, '%delta' => $delta)));
$this->assertEqual($entity->{$this->fieldTestData->field_name}[$delta]->value, $values[$revision_id][$delta]['value'], format_string('Revision %revision_id: expected value %delta was found.', ['%revision_id' => $revision_id, '%delta' => $delta]));
}
}
}
@ -72,32 +72,32 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
/**
* Test the 'multiple' load feature.
*/
function testFieldAttachLoadMultiple() {
public function testFieldAttachLoadMultiple() {
$entity_type = 'entity_test_rev';
// Define 2 bundles.
$bundles = array(
$bundles = [
1 => 'test_bundle_1',
2 => 'test_bundle_2',
);
];
entity_test_create_bundle($bundles[1]);
entity_test_create_bundle($bundles[2]);
// Define 3 fields:
// - field_1 is in bundle_1 and bundle_2,
// - field_2 is in bundle_1,
// - field_3 is in bundle_2.
$field_bundles_map = array(
1 => array(1, 2),
2 => array(1),
3 => array(2),
);
$field_bundles_map = [
1 => [1, 2],
2 => [1],
3 => [2],
];
for ($i = 1; $i <= 3; $i++) {
$field_names[$i] = 'field_' . $i;
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => $field_names[$i],
'entity_type' => $entity_type,
'type' => 'test_field',
));
]);
$field_storage->save();
$field_ids[$i] = $field_storage->uuid();
foreach ($field_bundles_map[$i] as $bundle) {
@ -113,14 +113,14 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
foreach ($bundles as $index => $bundle) {
$entities[$index] = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => $index, 'revision_id' => $index, 'type' => $bundle));
->create(['id' => $index, 'revision_id' => $index, 'type' => $bundle]);
$entity = clone($entities[$index]);
foreach ($field_names as $field_name) {
if (!$entity->hasField($field_name)) {
continue;
}
$values[$index][$field_name] = mt_rand(1, 127);
$entity->$field_name->setValue(array('value' => $values[$index][$field_name]));
$entity->$field_name->setValue(['value' => $values[$index][$field_name]]);
}
$entity->enforceIsnew();
$entity->save();
@ -136,7 +136,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
continue;
}
// The field value loaded matches the one inserted.
$this->assertEqual($entity->{$field_name}->value, $values[$index][$field_name], format_string('Entity %index: expected value was found.', array('%index' => $index)));
$this->assertEqual($entity->{$field_name}->value, $values[$index][$field_name], format_string('Entity %index: expected value was found.', ['%index' => $index]));
}
}
}
@ -144,13 +144,13 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
/**
* Tests insert and update with empty or NULL fields.
*/
function testFieldAttachSaveEmptyData() {
public function testFieldAttachSaveEmptyData() {
$entity_type = 'entity_test';
$this->createFieldWithStorage('', $entity_type);
$entity_init = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => 1));
->create(['id' => 1]);
// Insert: Field is NULL.
$entity = clone $entity_init;
@ -184,7 +184,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Update: Field is empty array. Data should be wiped.
$entity = clone($entity_init);
$entity->{$this->fieldTestData->field_name} = array();
$entity->{$this->fieldTestData->field_name} = [];
$entity = $this->entitySaveReload($entity);
$this->assertTrue($entity->{$this->fieldTestData->field_name}->isEmpty(), 'Update: empty array removes existing values');
}
@ -192,7 +192,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
/**
* Test insert with empty or NULL fields, with default value.
*/
function testFieldAttachSaveEmptyDataDefaultValue() {
public function testFieldAttachSaveEmptyDataDefaultValue() {
$entity_type = 'entity_test_rev';
$this->createFieldWithStorage('', $entity_type);
@ -203,7 +203,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Verify that fields are populated with default values.
$entity_init = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('id' => 1, 'revision_id' => 1));
->create(['id' => 1, 'revision_id' => 1]);
$default = field_test_default_value($entity_init, $this->fieldTestData->field);
$this->assertEqual($entity_init->{$this->fieldTestData->field_name}->getValue(), $default, 'Default field value correctly populated.');
@ -215,24 +215,24 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
$this->assertTrue($entity->{$this->fieldTestData->field_name}->isEmpty(), 'Insert: NULL field results in no value saved');
// Verify that prepopulated field values are not overwritten by defaults.
$value = array(array('value' => $default[0]['value'] - mt_rand(1, 127)));
$value = [['value' => $default[0]['value'] - mt_rand(1, 127)]];
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('type' => $entity_init->bundle(), $this->fieldTestData->field_name => $value));
->create(['type' => $entity_init->bundle(), $this->fieldTestData->field_name => $value]);
$this->assertEqual($entity->{$this->fieldTestData->field_name}->getValue(), $value, 'Prepopulated field value correctly maintained.');
}
/**
* Test entity deletion.
*/
function testFieldAttachDelete() {
public function testFieldAttachDelete() {
$entity_type = 'entity_test_rev';
$this->createFieldWithStorage('', $entity_type);
$cardinality = $this->fieldTestData->field_storage->getCardinality();
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('type' => $this->fieldTestData->field->getTargetBundle()));
$vids = array();
->create(['type' => $this->fieldTestData->field->getTargetBundle()]);
$vids = [];
// Create revision 0
$values = $this->_generateTestFieldValues($cardinality);
@ -261,7 +261,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Delete revision 1, confirm the other two still load.
$controller->deleteRevision($vids[1]);
$controller->resetCache();
foreach (array(0, 2) as $key) {
foreach ([0, 2] as $key) {
$vid = $vids[$key];
$revision = $controller->loadRevision($vid);
$this->assertEqual(count($revision->{$this->fieldTestData->field_name}), $cardinality, "The test entity revision $vid has $cardinality values.");
@ -275,7 +275,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Delete all field data, confirm nothing loads
$entity->delete();
$controller->resetCache();
foreach (array(0, 1, 2) as $vid) {
foreach ([0, 1, 2] as $vid) {
$revision = $controller->loadRevision($vid);
$this->assertFalse($revision);
}
@ -285,7 +285,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
/**
* Test entity_bundle_create().
*/
function testEntityCreateBundle() {
public function testEntityCreateBundle() {
$entity_type = 'entity_test_rev';
$this->createFieldWithStorage('', $entity_type);
$cardinality = $this->fieldTestData->field_storage->getCardinality();
@ -301,7 +301,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Save an entity with data in the field.
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('type' => $this->fieldTestData->field->getTargetBundle()));
->create(['type' => $this->fieldTestData->field->getTargetBundle()]);
$values = $this->_generateTestFieldValues($cardinality);
$entity->{$this->fieldTestData->field_name} = $values;
@ -313,7 +313,7 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
/**
* Test entity_bundle_delete().
*/
function testEntityDeleteBundle() {
public function testEntityDeleteBundle() {
$entity_type = 'entity_test_rev';
$this->createFieldWithStorage('', $entity_type);
@ -327,27 +327,27 @@ class FieldAttachStorageTest extends FieldKernelTestBase {
// Create a second field for the test bundle
$field_name = Unicode::strtolower($this->randomMachineName() . '_field_name');
$field_storage = array(
$field_storage = [
'field_name' => $field_name,
'entity_type' => $entity_type,
'type' => 'test_field',
'cardinality' => 1,
);
];
FieldStorageConfig::create($field_storage)->save();
$field = array(
$field = [
'field_name' => $field_name,
'entity_type' => $entity_type,
'bundle' => $this->fieldTestData->field->getTargetBundle(),
'label' => $this->randomMachineName() . '_label',
'description' => $this->randomMachineName() . '_description',
'weight' => mt_rand(0, 127),
);
];
FieldConfig::create($field)->save();
// Save an entity with data for both fields
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('type' => $this->fieldTestData->field->getTargetBundle()));
->create(['type' => $this->fieldTestData->field->getTargetBundle()]);
$values = $this->_generateTestFieldValues($this->fieldTestData->field_storage->getCardinality());
$entity->{$this->fieldTestData->field_name} = $values;
$entity->{$field_name} = $this->_generateTestFieldValues(1);

View file

@ -37,21 +37,21 @@ class FieldCrudTest extends FieldKernelTestBase {
*/
protected $fieldDefinition;
function setUp() {
public function setUp() {
parent::setUp();
$this->fieldStorageDefinition = array(
$this->fieldStorageDefinition = [
'field_name' => Unicode::strtolower($this->randomMachineName()),
'entity_type' => 'entity_test',
'type' => 'test_field',
);
];
$this->fieldStorage = FieldStorageConfig::create($this->fieldStorageDefinition);
$this->fieldStorage->save();
$this->fieldDefinition = array(
$this->fieldDefinition = [
'field_name' => $this->fieldStorage->getName(),
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
);
];
}
// TODO : test creation with
@ -63,7 +63,7 @@ class FieldCrudTest extends FieldKernelTestBase {
/**
* Test the creation of a field.
*/
function testCreateField() {
public function testCreateField() {
// Set a state flag so that field_test.module knows to add an in-memory
// constraint for this field.
\Drupal::state()->set('field_test_add_constraint', $this->fieldStorage->getName());
@ -174,7 +174,7 @@ class FieldCrudTest extends FieldKernelTestBase {
/**
* Test reading back a field definition.
*/
function testReadField() {
public function testReadField() {
FieldConfig::create($this->fieldDefinition)->save();
// Read the field back.
@ -187,7 +187,7 @@ class FieldCrudTest extends FieldKernelTestBase {
/**
* Test the update of a field.
*/
function testUpdateField() {
public function testUpdateField() {
FieldConfig::create($this->fieldDefinition)->save();
// Check that basic changes are saved.
@ -209,7 +209,7 @@ class FieldCrudTest extends FieldKernelTestBase {
/**
* Test the deletion of a field.
*/
function testDeleteField() {
public function testDeleteField() {
// TODO: Test deletion of the data stored in the field also.
// Need to check that data for a 'deleted' field / storage doesn't get loaded
// Need to check data marked deleted is cleaned on cron (not implemented yet...)
@ -223,12 +223,12 @@ class FieldCrudTest extends FieldKernelTestBase {
FieldConfig::create($another_field_definition)->save();
// Test that the first field is not deleted, and then delete it.
$field = current(entity_load_multiple_by_properties('field_config', array('entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE)));
$field = current(entity_load_multiple_by_properties('field_config', ['entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE]));
$this->assertTrue(!empty($field) && empty($field->deleted), 'A new field is not marked for deletion.');
$field->delete();
// Make sure the field is marked as deleted when it is specifically loaded.
$field = current(entity_load_multiple_by_properties('field_config', array('entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE)));
$field = current(entity_load_multiple_by_properties('field_config', ['entity_type' => 'entity_test', 'field_name' => $this->fieldDefinition['field_name'], 'bundle' => $this->fieldDefinition['bundle'], 'include_deleted' => TRUE]));
$this->assertTrue($field->isDeleted(), 'A deleted field is marked for deletion.');
// Try to load the field normally and make sure it does not show up.
@ -243,7 +243,7 @@ class FieldCrudTest extends FieldKernelTestBase {
/**
* Tests the cross deletion behavior between field storages and fields.
*/
function testDeleteFieldCrossDeletion() {
public function testDeleteFieldCrossDeletion() {
$field_definition_2 = $this->fieldDefinition;
$field_definition_2['bundle'] .= '_another_bundle';
entity_test_create_bundle($field_definition_2['bundle']);
@ -276,7 +276,7 @@ class FieldCrudTest extends FieldKernelTestBase {
$field->save();
$field_2 = FieldConfig::create($field_definition_2);
$field_2->save();
$this->container->get('entity.manager')->getStorage('field_config')->delete(array($field, $field_2));
$this->container->get('entity.manager')->getStorage('field_config')->delete([$field, $field_2]);
$this->assertFalse(FieldStorageConfig::loadByName('entity_test', $field_storage->getName()));
}

View file

@ -50,12 +50,12 @@ class FieldDataCountTest extends FieldKernelTestBase {
// Create a field with a cardinality of 2 to show that we are counting
// entities and not rows in a table.
/** @var \Drupal\field\Entity\FieldStorageConfig $field_storage */
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_int',
'entity_type' => 'entity_test',
'type' => 'integer',
'cardinality' => 2,
));
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
@ -112,7 +112,7 @@ class FieldDataCountTest extends FieldKernelTestBase {
$entity_init = $this->container->get('entity_type.manager')
->getStorage($entity_type)
->create(array('type' => $entity_type,));
->create(['type' => $entity_type]);
$cardinality = $this->fieldTestData->field_storage_2->getCardinality();
$this->assertIdentical($this->fieldTestData->field_storage_2->hasData(), FALSE, 'There are no entities with field data.');
@ -129,7 +129,7 @@ class FieldDataCountTest extends FieldKernelTestBase {
$this->assertIdentical($this->fieldTestData->field_storage_2->hasData(), TRUE, 'There are entities with field data.');
$this->assertIdentical($this->storageRev->countFieldData($this->fieldTestData->field_storage_2), 1, 'There is 1 entity with field data.');
$entity->{$this->fieldTestData->field_name_2} = array();
$entity->{$this->fieldTestData->field_name_2} = [];
$entity->setNewRevision();
$entity->save();
@ -137,7 +137,7 @@ class FieldDataCountTest extends FieldKernelTestBase {
$storage = $this->container->get('entity.manager')->getStorage($entity_type);
$entity = $storage->loadRevision($first_revision);
$this->assertEqual(count($entity->{$this->fieldTestData->field_name_2}), $cardinality, format_string('Revision %revision_id: expected number of values.', array('%revision_id' => $first_revision)));
$this->assertEqual(count($entity->{$this->fieldTestData->field_name_2}), $cardinality, format_string('Revision %revision_id: expected number of values.', ['%revision_id' => $first_revision]));
}
/**
@ -146,27 +146,27 @@ class FieldDataCountTest extends FieldKernelTestBase {
public function testCountWithIndex0() {
// Create a field that will require dedicated storage.
/** @var \Drupal\field\Entity\FieldStorageConfig $field_storage */
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_int',
'entity_type' => 'user',
'type' => 'integer',
'cardinality' => 2,
));
]);
$field_storage->save();
FieldConfig::create(array(
FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'user',
))->save();
])->save();
// Create an entry for the anonymous user, who has user ID 0.
$user = $this->storageUser
->create(array(
->create([
'uid' => 0,
'name' => 'anonymous',
'mail' => NULL,
'status' => FALSE,
'field_int' => 42,
));
]);
$user->save();
// Test shared table storage.

View file

@ -20,12 +20,12 @@ class FieldImportChangeTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array('field_test_config');
public static $modules = ['field_test_config'];
/**
* Tests importing an updated field.
*/
function testImportChange() {
public function testImportChange() {
$this->installConfig(['field_test_config']);
$field_storage_id = 'field_test_import';
$field_id = "entity_test.entity_test.$field_storage_id";

View file

@ -16,7 +16,7 @@ class FieldImportCreateTest extends FieldKernelTestBase {
/**
* Tests creating field storages and fields during default config import.
*/
function testImportCreateDefault() {
public function testImportCreateDefault() {
$field_name = 'field_test_import';
$field_storage_id = "entity_test.$field_name";
$field_id = "entity_test.entity_test.$field_name";
@ -37,7 +37,7 @@ class FieldImportCreateTest extends FieldKernelTestBase {
// Enable field_test_config module and check that the field and storage
// shipped in the module's default config were created.
\Drupal::service('module_installer')->install(array('field_test_config'));
\Drupal::service('module_installer')->install(['field_test_config']);
// A field storage with one single field.
$field_storage = FieldStorageConfig::load($field_storage_id);
@ -70,7 +70,7 @@ class FieldImportCreateTest extends FieldKernelTestBase {
/**
* Tests creating field storages and fields during config import.
*/
function testImportCreate() {
public function testImportCreate() {
// A field storage with one single field.
$field_name = 'field_test_import_sync';
$field_storage_id = "entity_test.$field_name";

View file

@ -22,7 +22,7 @@ class FieldImportDeleteTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array('field_test_config');
public static $modules = ['field_test_config'];
/**
* Tests deleting field storages and fields as part of config import.
@ -60,11 +60,11 @@ class FieldImportDeleteTest extends FieldKernelTestBase {
$active = $this->container->get('config.storage');
$sync = $this->container->get('config.storage.sync');
$this->copyConfig($active, $sync);
$this->assertTrue($sync->delete($field_storage_config_name), SafeMarkup::format('Deleted field storage: @field_storage', array('@field_storage' => $field_storage_config_name)));
$this->assertTrue($sync->delete($field_storage_config_name_2), SafeMarkup::format('Deleted field storage: @field_storage', array('@field_storage' => $field_storage_config_name_2)));
$this->assertTrue($sync->delete($field_config_name), SafeMarkup::format('Deleted field: @field', array('@field' => $field_config_name)));
$this->assertTrue($sync->delete($field_config_name_2a), SafeMarkup::format('Deleted field: @field', array('@field' => $field_config_name_2a)));
$this->assertTrue($sync->delete($field_config_name_2b), SafeMarkup::format('Deleted field: @field', array('@field' => $field_config_name_2b)));
$this->assertTrue($sync->delete($field_storage_config_name), SafeMarkup::format('Deleted field storage: @field_storage', ['@field_storage' => $field_storage_config_name]));
$this->assertTrue($sync->delete($field_storage_config_name_2), SafeMarkup::format('Deleted field storage: @field_storage', ['@field_storage' => $field_storage_config_name_2]));
$this->assertTrue($sync->delete($field_config_name), SafeMarkup::format('Deleted field: @field', ['@field' => $field_config_name]));
$this->assertTrue($sync->delete($field_config_name_2a), SafeMarkup::format('Deleted field: @field', ['@field' => $field_config_name_2a]));
$this->assertTrue($sync->delete($field_config_name_2b), SafeMarkup::format('Deleted field: @field', ['@field' => $field_config_name_2b]));
$deletes = $this->configImporter()->getUnprocessedConfiguration('delete');
$this->assertEqual(count($deletes), 5, 'Importing configuration will delete 3 fields and 2 field storages.');
@ -73,39 +73,39 @@ class FieldImportDeleteTest extends FieldKernelTestBase {
$this->configImporter()->import();
// Check that the field storages and fields are gone.
\Drupal::entityManager()->getStorage('field_storage_config')->resetCache(array($field_storage_id));
\Drupal::entityManager()->getStorage('field_storage_config')->resetCache([$field_storage_id]);
$field_storage = FieldStorageConfig::load($field_storage_id);
$this->assertFalse($field_storage, 'The field storage was deleted.');
\Drupal::entityManager()->getStorage('field_storage_config')->resetCache(array($field_storage_id_2));
\Drupal::entityManager()->getStorage('field_storage_config')->resetCache([$field_storage_id_2]);
$field_storage_2 = FieldStorageConfig::load($field_storage_id_2);
$this->assertFalse($field_storage_2, 'The second field storage was deleted.');
\Drupal::entityManager()->getStorage('field_config')->resetCache(array($field_id));
\Drupal::entityManager()->getStorage('field_config')->resetCache([$field_id]);
$field = FieldConfig::load($field_id);
$this->assertFalse($field, 'The field was deleted.');
\Drupal::entityManager()->getStorage('field_config')->resetCache(array($field_id_2a));
\Drupal::entityManager()->getStorage('field_config')->resetCache([$field_id_2a]);
$field_2a = FieldConfig::load($field_id_2a);
$this->assertFalse($field_2a, 'The second field on test bundle was deleted.');
\Drupal::entityManager()->getStorage('field_config')->resetCache(array($field_id_2b));
\Drupal::entityManager()->getStorage('field_config')->resetCache([$field_id_2b]);
$field_2b = FieldConfig::load($field_id_2b);
$this->assertFalse($field_2b, 'The second field on test bundle 2 was deleted.');
// Check that all config files are gone.
$active = $this->container->get('config.storage');
$this->assertIdentical($active->listAll($field_storage_config_name), array());
$this->assertIdentical($active->listAll($field_storage_config_name_2), array());
$this->assertIdentical($active->listAll($field_config_name), array());
$this->assertIdentical($active->listAll($field_config_name_2a), array());
$this->assertIdentical($active->listAll($field_config_name_2b), array());
$this->assertIdentical($active->listAll($field_storage_config_name), []);
$this->assertIdentical($active->listAll($field_storage_config_name_2), []);
$this->assertIdentical($active->listAll($field_config_name), []);
$this->assertIdentical($active->listAll($field_config_name_2a), []);
$this->assertIdentical($active->listAll($field_config_name_2b), []);
// Check that the storage definition is preserved in state.
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: array();
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: [];
$this->assertTrue(isset($deleted_storages[$field_storage_uuid]));
$this->assertTrue(isset($deleted_storages[$field_storage_uuid_2]));
// Purge field data, and check that the storage definition has been
// completely removed once the data is purged.
field_purge_batch(10);
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: array();
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: [];
$this->assertTrue(empty($deleted_storages), 'Fields are deleted');
}

View file

@ -21,14 +21,14 @@ class FieldImportDeleteUninstallTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array('telephone');
public static $modules = ['telephone'];
protected function setUp() {
parent::setUp();
// Module uninstall requires users_data tables.
// @see drupal_flush_all_caches()
// @see user_modules_uninstalled()
$this->installSchema('user', array('users_data'));
$this->installSchema('user', ['users_data']);
}
/**
@ -38,11 +38,11 @@ class FieldImportDeleteUninstallTest extends FieldKernelTestBase {
// Create a field to delete to prove that
// \Drupal\field\ConfigImporterFieldPurger does not purge fields that are
// not related to the configuration synchronization.
$unrelated_field_storage = FieldStorageConfig::create(array(
$unrelated_field_storage = FieldStorageConfig::create([
'field_name' => 'field_int',
'entity_type' => 'entity_test',
'type' => 'integer',
));
]);
$unrelated_field_storage->save();
FieldConfig::create([
'field_storage' => $unrelated_field_storage,
@ -50,11 +50,11 @@ class FieldImportDeleteUninstallTest extends FieldKernelTestBase {
])->save();
// Create a telephone field for validation.
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_test',
'entity_type' => 'entity_test',
'type' => 'telephone',
));
]);
$field_storage->save();
FieldConfig::create([
'field_storage' => $field_storage,
@ -93,7 +93,7 @@ class FieldImportDeleteUninstallTest extends FieldKernelTestBase {
$sync->delete('field.field.entity_test.entity_test.field_test');
$steps = $this->configImporter()->initialize();
$this->assertIdentical($steps[0], array('\Drupal\field\ConfigImporterFieldPurger', 'process'), 'The additional process configuration synchronization step has been added.');
$this->assertIdentical($steps[0], ['\Drupal\field\ConfigImporterFieldPurger', 'process'], 'The additional process configuration synchronization step has been added.');
// This will purge all the data, delete the field and uninstall the
// Telephone module.
@ -101,7 +101,7 @@ class FieldImportDeleteUninstallTest extends FieldKernelTestBase {
$this->assertFalse(\Drupal::moduleHandler()->moduleExists('telephone'));
$this->assertFalse(\Drupal::entityManager()->loadEntityByUuid('field_storage_config', $field_storage->uuid()), 'The test field has been deleted by the configuration synchronization');
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: array();
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: [];
$this->assertFalse(isset($deleted_storages[$field_storage->uuid()]), 'Telephone field has been completed removed from the system.');
$this->assertTrue(isset($deleted_storages[$unrelated_field_storage->uuid()]), 'Unrelated field not purged by configuration synchronization.');
}
@ -112,11 +112,11 @@ class FieldImportDeleteUninstallTest extends FieldKernelTestBase {
*/
public function testImportAlreadyDeletedUninstall() {
// Create a telephone field for validation.
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_test',
'entity_type' => 'entity_test',
'type' => 'telephone',
));
]);
$field_storage->save();
$field_storage_uuid = $field_storage->uuid();
FieldConfig::create([
@ -150,18 +150,18 @@ class FieldImportDeleteUninstallTest extends FieldKernelTestBase {
unset($core_extension['module']['telephone']);
$sync->write('core.extension', $core_extension);
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: array();
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: [];
$this->assertTrue(isset($deleted_storages[$field_storage_uuid]), 'Field has been deleted and needs purging before configuration synchronization.');
$steps = $this->configImporter()->initialize();
$this->assertIdentical($steps[0], array('\Drupal\field\ConfigImporterFieldPurger', 'process'), 'The additional process configuration synchronization step has been added.');
$this->assertIdentical($steps[0], ['\Drupal\field\ConfigImporterFieldPurger', 'process'], 'The additional process configuration synchronization step has been added.');
// This will purge all the data, delete the field and uninstall the
// Telephone module.
$this->configImporter()->import();
$this->assertFalse(\Drupal::moduleHandler()->moduleExists('telephone'));
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: array();
$deleted_storages = \Drupal::state()->get('field.storage.deleted') ?: [];
$this->assertFalse(isset($deleted_storages[$field_storage_uuid]), 'Field has been completed removed from the system.');
}

View file

@ -43,24 +43,24 @@ abstract class FieldKernelTestBase extends KernelTestBase {
protected function setUp() {
parent::setUp();
$this->fieldTestData = new \ArrayObject(array(), \ArrayObject::ARRAY_AS_PROPS);
$this->fieldTestData = new \ArrayObject([], \ArrayObject::ARRAY_AS_PROPS);
$this->installEntitySchema('entity_test');
$this->installEntitySchema('user');
$this->installSchema('system', ['sequences', 'key_value']);
// Set default storage backend and configure the theme system.
$this->installConfig(array('field', 'system'));
$this->installConfig(['field', 'system']);
// Create user 1.
$storage = \Drupal::entityManager()->getStorage('user');
$storage
->create(array(
->create([
'uid' => 1,
'name' => 'entity-test',
'mail' => 'entity@localhost',
'status' => TRUE,
))
])
->save();
}
@ -88,33 +88,33 @@ abstract class FieldKernelTestBase extends KernelTestBase {
$field_definition = 'field_definition' . $suffix;
$this->fieldTestData->$field_name = Unicode::strtolower($this->randomMachineName() . '_field_name' . $suffix);
$this->fieldTestData->$field_storage = FieldStorageConfig::create(array(
$this->fieldTestData->$field_storage = FieldStorageConfig::create([
'field_name' => $this->fieldTestData->$field_name,
'entity_type' => $entity_type,
'type' => 'test_field',
'cardinality' => 4,
));
]);
$this->fieldTestData->$field_storage->save();
$this->fieldTestData->$field_storage_uuid = $this->fieldTestData->$field_storage->uuid();
$this->fieldTestData->$field_definition = array(
$this->fieldTestData->$field_definition = [
'field_storage' => $this->fieldTestData->$field_storage,
'bundle' => $bundle,
'label' => $this->randomMachineName() . '_label',
'description' => $this->randomMachineName() . '_description',
'settings' => array(
'settings' => [
'test_field_setting' => $this->randomMachineName(),
),
);
],
];
$this->fieldTestData->$field = FieldConfig::create($this->fieldTestData->$field_definition);
$this->fieldTestData->$field->save();
entity_get_form_display($entity_type, $bundle, 'default')
->setComponent($this->fieldTestData->$field_name, array(
->setComponent($this->fieldTestData->$field_name, [
'type' => 'test_field_widget',
'settings' => array(
'settings' => [
'test_widget_setting' => $this->randomMachineName(),
)
))
]
])
->save();
}
@ -159,7 +159,7 @@ abstract class FieldKernelTestBase extends KernelTestBase {
* An array of random values, in the format expected for field values.
*/
protected function _generateTestFieldValues($cardinality) {
$values = array();
$values = [];
for ($i = 0; $i < $cardinality; $i++) {
// field_test fields treat 0 as 'empty value'.
$values[$i]['value'] = mt_rand(1, 127);
@ -197,7 +197,7 @@ abstract class FieldKernelTestBase extends KernelTestBase {
$values = $field->getValue();
$this->assertEqual(count($values), count($expected_values), 'Expected number of values were saved.');
foreach ($expected_values as $key => $value) {
$this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', array('@value' => $value)));
$this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', ['@value' => $value]));
}
}

View file

@ -21,7 +21,7 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array();
public static $modules = [];
// TODO : test creation with
// - a full fledged $field structure, check that all the values are there
@ -31,12 +31,12 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
/**
* Test the creation of a field storage.
*/
function testCreate() {
$field_storage_definition = array(
public function testCreate() {
$field_storage_definition = [
'field_name' => 'field_2',
'entity_type' => 'entity_test',
'type' => 'test_field',
);
];
field_test_memorize();
$field_storage = FieldStorageConfig::create($field_storage_definition);
$field_storage->save();
@ -86,10 +86,10 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
// Check that field type is required.
try {
$field_storage_definition = array(
$field_storage_definition = [
'field_name' => 'field_1',
'entity_type' => 'entity_type',
);
];
FieldStorageConfig::create($field_storage_definition)->save();
$this->fail(t('Cannot create a field with no type.'));
}
@ -99,10 +99,10 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
// Check that field name is required.
try {
$field_storage_definition = array(
$field_storage_definition = [
'type' => 'test_field',
'entity_type' => 'entity_test',
);
];
FieldStorageConfig::create($field_storage_definition)->save();
$this->fail(t('Cannot create an unnamed field.'));
}
@ -111,10 +111,10 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
}
// Check that entity type is required.
try {
$field_storage_definition = array(
$field_storage_definition = [
'field_name' => 'test_field',
'type' => 'test_field'
);
];
FieldStorageConfig::create($field_storage_definition)->save();
$this->fail('Cannot create a field without an entity type.');
}
@ -124,11 +124,11 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
// Check that field name must start with a letter or _.
try {
$field_storage_definition = array(
$field_storage_definition = [
'field_name' => '2field_2',
'entity_type' => 'entity_test',
'type' => 'test_field',
);
];
FieldStorageConfig::create($field_storage_definition)->save();
$this->fail(t('Cannot create a field with a name starting with a digit.'));
}
@ -138,11 +138,11 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
// Check that field name must only contain lowercase alphanumeric or _.
try {
$field_storage_definition = array(
$field_storage_definition = [
'field_name' => 'field#_3',
'entity_type' => 'entity_test',
'type' => 'test_field',
);
];
FieldStorageConfig::create($field_storage_definition)->save();
$this->fail(t('Cannot create a field with a name containing an illegal character.'));
}
@ -152,11 +152,11 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
// Check that field name cannot be longer than 32 characters long.
try {
$field_storage_definition = array(
$field_storage_definition = [
'field_name' => '_12345678901234567890123456789012',
'entity_type' => 'entity_test',
'type' => 'test_field',
);
];
FieldStorageConfig::create($field_storage_definition)->save();
$this->fail(t('Cannot create a field with a name longer than 32 characters.'));
}
@ -167,11 +167,11 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
// Check that field name can not be an entity key.
// "id" is known as an entity key from the "entity_test" type.
try {
$field_storage_definition = array(
$field_storage_definition = [
'type' => 'test_field',
'field_name' => 'id',
'entity_type' => 'entity_test',
);
];
FieldStorageConfig::create($field_storage_definition)->save();
$this->fail(t('Cannot create a field bearing the name of an entity key.'));
}
@ -186,145 +186,145 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
* This behavior is needed to allow field storage creation within updates,
* since plugin classes (and thus the field type schema) cannot be accessed.
*/
function testCreateWithExplicitSchema() {
$schema = array(
public function testCreateWithExplicitSchema() {
$schema = [
'dummy' => 'foobar'
);
$field_storage = FieldStorageConfig::create(array(
];
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_2',
'entity_type' => 'entity_test',
'type' => 'test_field',
'schema' => $schema,
));
]);
$this->assertEqual($field_storage->getSchema(), $schema);
}
/**
* Tests reading field storage definitions.
*/
function testRead() {
$field_storage_definition = array(
public function testRead() {
$field_storage_definition = [
'field_name' => 'field_1',
'entity_type' => 'entity_test',
'type' => 'test_field',
);
];
$field_storage = FieldStorageConfig::create($field_storage_definition);
$field_storage->save();
$id = $field_storage->id();
// Check that 'single column' criteria works.
$fields = entity_load_multiple_by_properties('field_storage_config', array('field_name' => $field_storage_definition['field_name']));
$fields = entity_load_multiple_by_properties('field_storage_config', ['field_name' => $field_storage_definition['field_name']]);
$this->assertTrue(count($fields) == 1 && isset($fields[$id]), 'The field was properly read.');
// Check that 'multi column' criteria works.
$fields = entity_load_multiple_by_properties('field_storage_config', array('field_name' => $field_storage_definition['field_name'], 'type' => $field_storage_definition['type']));
$fields = entity_load_multiple_by_properties('field_storage_config', ['field_name' => $field_storage_definition['field_name'], 'type' => $field_storage_definition['type']]);
$this->assertTrue(count($fields) == 1 && isset($fields[$id]), 'The field was properly read.');
$fields = entity_load_multiple_by_properties('field_storage_config', array('field_name' => $field_storage_definition['field_name'], 'type' => 'foo'));
$fields = entity_load_multiple_by_properties('field_storage_config', ['field_name' => $field_storage_definition['field_name'], 'type' => 'foo']);
$this->assertTrue(empty($fields), 'No field was found.');
// Create a field from the field storage.
$field_definition = array(
$field_definition = [
'field_name' => $field_storage_definition['field_name'],
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
);
];
FieldConfig::create($field_definition)->save();
}
/**
* Test creation of indexes on data column.
*/
function testIndexes() {
public function testIndexes() {
// Check that indexes specified by the field type are used by default.
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_1',
'entity_type' => 'entity_test',
'type' => 'test_field',
));
]);
$field_storage->save();
$field_storage = FieldStorageConfig::load($field_storage->id());
$schema = $field_storage->getSchema();
$expected_indexes = array('value' => array('value'));
$expected_indexes = ['value' => ['value']];
$this->assertEqual($schema['indexes'], $expected_indexes, 'Field type indexes saved by default');
// Check that indexes specified by the field definition override the field
// type indexes.
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_2',
'entity_type' => 'entity_test',
'type' => 'test_field',
'indexes' => array(
'value' => array(),
),
));
'indexes' => [
'value' => [],
],
]);
$field_storage->save();
$field_storage = FieldStorageConfig::load($field_storage->id());
$schema = $field_storage->getSchema();
$expected_indexes = array('value' => array());
$expected_indexes = ['value' => []];
$this->assertEqual($schema['indexes'], $expected_indexes, 'Field definition indexes override field type indexes');
// Check that indexes specified by the field definition add to the field
// type indexes.
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_3',
'entity_type' => 'entity_test',
'type' => 'test_field',
'indexes' => array(
'value_2' => array('value'),
),
));
'indexes' => [
'value_2' => ['value'],
],
]);
$field_storage->save();
$id = $field_storage->id();
$field_storage = FieldStorageConfig::load($id);
$schema = $field_storage->getSchema();
$expected_indexes = array('value' => array('value'), 'value_2' => array('value'));
$expected_indexes = ['value' => ['value'], 'value_2' => ['value']];
$this->assertEqual($schema['indexes'], $expected_indexes, 'Field definition indexes are merged with field type indexes');
}
/**
* Test the deletion of a field storage.
*/
function testDelete() {
public function testDelete() {
// TODO: Also test deletion of the data stored in the field ?
// Create two fields (so we can test that only one is deleted).
$field_storage_definition = array(
$field_storage_definition = [
'field_name' => 'field_1',
'type' => 'test_field',
'entity_type' => 'entity_test',
);
];
FieldStorageConfig::create($field_storage_definition)->save();
$another_field_storage_definition = array(
$another_field_storage_definition = [
'field_name' => 'field_2',
'type' => 'test_field',
'entity_type' => 'entity_test',
);
];
FieldStorageConfig::create($another_field_storage_definition)->save();
// Create fields for each.
$field_definition = array(
$field_definition = [
'field_name' => $field_storage_definition['field_name'],
'entity_type' => 'entity_test',
'bundle' => 'entity_test',
);
];
FieldConfig::create($field_definition)->save();
$another_field_definition = $field_definition;
$another_field_definition['field_name'] = $another_field_storage_definition['field_name'];
FieldConfig::create($another_field_definition)->save();
// Test that the first field is not deleted, and then delete it.
$field_storage = current(entity_load_multiple_by_properties('field_storage_config', array('field_name' => $field_storage_definition['field_name'], 'include_deleted' => TRUE)));
$field_storage = current(entity_load_multiple_by_properties('field_storage_config', ['field_name' => $field_storage_definition['field_name'], 'include_deleted' => TRUE]));
$this->assertTrue(!empty($field_storage) && !$field_storage->isDeleted(), 'A new storage is not marked for deletion.');
FieldStorageConfig::loadByName('entity_test', $field_storage_definition['field_name'])->delete();
// Make sure that the field is marked as deleted when it is specifically
// loaded.
$field_storage = current(entity_load_multiple_by_properties('field_storage_config', array('field_name' => $field_storage_definition['field_name'], 'include_deleted' => TRUE)));
$field_storage = current(entity_load_multiple_by_properties('field_storage_config', ['field_name' => $field_storage_definition['field_name'], 'include_deleted' => TRUE]));
$this->assertTrue($field_storage->isDeleted(), 'A deleted storage is marked for deletion.');
// Make sure that this field is marked as deleted when it is
// specifically loaded.
$field = current(entity_load_multiple_by_properties('field_config', array('entity_type' => 'entity_test', 'field_name' => $field_definition['field_name'], 'bundle' => $field_definition['bundle'], 'include_deleted' => TRUE)));
$field = current(entity_load_multiple_by_properties('field_config', ['entity_type' => 'entity_test', 'field_name' => $field_definition['field_name'], 'bundle' => $field_definition['bundle'], 'include_deleted' => TRUE]));
$this->assertTrue($field->isDeleted(), 'A field whose storage was deleted is marked for deletion.');
// Try to load the storage normally and make sure it does not show up.
@ -363,12 +363,12 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
}
}
function testUpdateFieldType() {
$field_storage = FieldStorageConfig::create(array(
public function testUpdateFieldType() {
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_type',
'entity_type' => 'entity_test',
'type' => 'decimal',
));
]);
$field_storage->save();
try {
@ -384,17 +384,17 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
/**
* Test updating a field storage.
*/
function testUpdate() {
public function testUpdate() {
// Create a field with a defined cardinality, so that we can ensure it's
// respected. Since cardinality enforcement is consistent across database
// systems, it makes a good test case.
$cardinality = 4;
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => 'field_update',
'entity_type' => 'entity_test',
'type' => 'test_field',
'cardinality' => $cardinality,
));
]);
$field_storage->save();
$field = FieldConfig::create([
'field_storage' => $field_storage,
@ -426,15 +426,15 @@ class FieldStorageCrudTest extends FieldKernelTestBase {
/**
* Test field type modules forbidding an update.
*/
function testUpdateForbid() {
$field_storage = FieldStorageConfig::create(array(
public function testUpdateForbid() {
$field_storage = FieldStorageConfig::create([
'field_name' => 'forbidden',
'entity_type' => 'entity_test',
'type' => 'test_field',
'settings' => array(
'settings' => [
'changeable' => 0,
'unchangeable' => 0
)));
]]);
$field_storage->save();
$field_storage->setSetting('changeable', $field_storage->getSetting('changeable') + 1);
try {

View file

@ -17,12 +17,12 @@ class FieldTypePluginManagerTest extends FieldKernelTestBase {
/**
* Tests the default settings convenience methods.
*/
function testDefaultSettings() {
public function testDefaultSettings() {
$field_type_manager = \Drupal::service('plugin.manager.field.field_type');
foreach (array('test_field', 'shape', 'hidden_test_field') as $type) {
foreach (['test_field', 'shape', 'hidden_test_field'] as $type) {
$definition = $field_type_manager->getDefinition($type);
$this->assertIdentical($field_type_manager->getDefaultStorageSettings($type), $definition['class']::defaultStorageSettings(), format_string("%type storage settings were returned", array('%type' => $type)));
$this->assertIdentical($field_type_manager->getDefaultFieldSettings($type), $definition['class']::defaultFieldSettings(), format_string(" %type field settings were returned", array('%type' => $type)));
$this->assertIdentical($field_type_manager->getDefaultStorageSettings($type), $definition['class']::defaultStorageSettings(), format_string("%type storage settings were returned", ['%type' => $type]));
$this->assertIdentical($field_type_manager->getDefaultFieldSettings($type), $definition['class']::defaultFieldSettings(), format_string(" %type field settings were returned", ['%type' => $type]));
}
}
@ -32,7 +32,7 @@ class FieldTypePluginManagerTest extends FieldKernelTestBase {
public function testCreateInstance() {
/** @var \Drupal\Core\Field\FieldTypePluginManagerInterface $field_type_manager */
$field_type_manager = \Drupal::service('plugin.manager.field.field_type');
foreach (array('test_field', 'shape', 'hidden_test_field') as $type) {
foreach (['test_field', 'shape', 'hidden_test_field'] as $type) {
$definition = $field_type_manager->getDefinition($type);
$class = $definition['class'];
@ -40,16 +40,16 @@ class FieldTypePluginManagerTest extends FieldKernelTestBase {
$field_definition = BaseFieldDefinition::create($type);
$configuration = array(
$configuration = [
'field_definition' => $field_definition,
'name' => $field_name,
'parent' => NULL,
);
];
$instance = $field_type_manager->createInstance($type, $configuration);
$this->assertTrue($instance instanceof $class, SafeMarkup::format('Created a @class instance', array('@class' => $class)));
$this->assertEqual($field_name, $instance->getName(), SafeMarkup::format('Instance name is @name', array('@name' => $field_name)));
$this->assertTrue($instance instanceof $class, SafeMarkup::format('Created a @class instance', ['@class' => $class]));
$this->assertEqual($field_name, $instance->getName(), SafeMarkup::format('Instance name is @name', ['@name' => $field_name]));
}
}
@ -69,18 +69,18 @@ class FieldTypePluginManagerTest extends FieldKernelTestBase {
->setLabel('Jenny')
->setDefaultValue(8675309);
$configuration = array(
$configuration = [
'field_definition' => $field_definition,
'name' => $field_name,
'parent' => NULL,
);
];
$entity = EntityTest::create();
$instance = $field_type_manager->createInstance($type, $configuration);
$this->assertTrue($instance instanceof $class, SafeMarkup::format('Created a @class instance', array('@class' => $class)));
$this->assertEqual($field_name, $instance->getName(), SafeMarkup::format('Instance name is @name', array('@name' => $field_name)));
$this->assertTrue($instance instanceof $class, SafeMarkup::format('Created a @class instance', ['@class' => $class]));
$this->assertEqual($field_name, $instance->getName(), SafeMarkup::format('Instance name is @name', ['@name' => $field_name]));
$this->assertEqual($instance->getFieldDefinition()->getLabel(), 'Jenny', 'Instance label is Jenny');
$this->assertEqual($instance->getFieldDefinition()->getDefaultValue($entity), [['value' => 8675309]], 'Instance default_value is 8675309');
}

View file

@ -34,20 +34,20 @@ class FieldValidationTest extends FieldKernelTestBase {
$this->createFieldWithStorage('', $this->entityType, $this->bundle);
// Create an 'entity_test' entity.
$this->entity = entity_create($this->entityType, array(
$this->entity = entity_create($this->entityType, [
'type' => $this->bundle,
));
]);
}
/**
* Tests that the number of values is validated against the field cardinality.
*/
function testCardinalityConstraint() {
public function testCardinalityConstraint() {
$cardinality = $this->fieldTestData->field_storage->getCardinality();
$entity = $this->entity;
for ($delta = 0; $delta < $cardinality + 1; $delta++) {
$entity->{$this->fieldTestData->field_name}[] = array('value' => 1);
$entity->{$this->fieldTestData->field_name}[] = ['value' => 1];
}
// Validate the field.
@ -56,13 +56,13 @@ class FieldValidationTest extends FieldKernelTestBase {
// Check that the expected constraint violations are reported.
$this->assertEqual(count($violations), 1);
$this->assertEqual($violations[0]->getPropertyPath(), '');
$this->assertEqual($violations[0]->getMessage(), t('%name: this field cannot hold more than @count values.', array('%name' => $this->fieldTestData->field->getLabel(), '@count' => $cardinality)));
$this->assertEqual($violations[0]->getMessage(), t('%name: this field cannot hold more than @count values.', ['%name' => $this->fieldTestData->field->getLabel(), '@count' => $cardinality]));
}
/**
* Tests that constraints defined by the field type are validated.
*/
function testFieldConstraints() {
public function testFieldConstraints() {
$cardinality = $this->fieldTestData->field_storage->getCardinality();
$entity = $this->entity;
@ -70,7 +70,7 @@ class FieldValidationTest extends FieldKernelTestBase {
$this->assertTrue($cardinality >= 2);
// Set up values for the field.
$expected_violations = array();
$expected_violations = [];
for ($delta = 0; $delta < $cardinality; $delta++) {
// All deltas except '1' have incorrect values.
if ($delta == 1) {
@ -78,7 +78,7 @@ class FieldValidationTest extends FieldKernelTestBase {
}
else {
$value = -1;
$expected_violations[$delta . '.value'][] = t('%name does not accept the value -1.', array('%name' => $this->fieldTestData->field->getLabel()));
$expected_violations[$delta . '.value'][] = t('%name does not accept the value -1.', ['%name' => $this->fieldTestData->field->getLabel()]);
}
$entity->{$this->fieldTestData->field_name}[] = $value;
}
@ -87,7 +87,7 @@ class FieldValidationTest extends FieldKernelTestBase {
$violations = $entity->{$this->fieldTestData->field_name}->validate();
// Check that the expected constraint violations are reported.
$violations_by_path = array();
$violations_by_path = [];
foreach ($violations as $violation) {
$violations_by_path[$violation->getPropertyPath()][] = $violation->getMessage();
}

View file

@ -24,13 +24,13 @@ class FormatterPluginManagerTest extends FieldKernelTestBase {
// Set a name that will make isApplicable() return TRUE.
->setName('field_test_field');
$formatter_options = array(
$formatter_options = [
'field_definition' => $base_field_definition,
'view_mode' => 'default',
'configuration' => array(
'configuration' => [
'type' => 'field_test_applicable',
),
);
],
];
$instance = $formatter_plugin_manager->getInstance($formatter_options);
$this->assertEqual($instance->getPluginId(), 'field_test_applicable');

View file

@ -20,19 +20,33 @@ class MigrateFieldFormatterSettingsTest extends MigrateDrupal6TestBase {
$this->migrateFields();
}
/**
* Asserts that a particular component is NOT included in a display.
*
* @param string $display_id
* The display ID.
* @param string $component_id
* The component ID.
*/
protected function assertComponentNotExists($display_id, $component_id) {
$component = EntityViewDisplay::load($display_id)->getComponent($component_id);
$this->assertNull($component);
}
/**
* Test that migrated entity display settings can be loaded using D8 API's.
*/
public function testEntityDisplaySettings() {
// Run tests.
$field_name = "field_test";
$expected = array(
$expected = [
'label' => 'above',
'weight' => 1,
'type' => 'text_trimmed',
'settings' => array('trim_length' => 600),
'third_party_settings' => array(),
);
'settings' => ['trim_length' => 600],
'third_party_settings' => [],
'region' => 'content',
];
// Can we load any entity display.
$display = EntityViewDisplay::load('node.story.teaser');
@ -50,7 +64,7 @@ class MigrateFieldFormatterSettingsTest extends MigrateDrupal6TestBase {
// Test the default format with text_default which comes from a static map.
$expected['type'] = 'text_default';
$expected['settings'] = array();
$expected['settings'] = [];
$display = EntityViewDisplay::load('node.story.default');
$this->assertIdentical($expected, $display->getComponent($field_name));
@ -65,40 +79,40 @@ class MigrateFieldFormatterSettingsTest extends MigrateDrupal6TestBase {
// Test the number field formatter settings are correct.
$expected['weight'] = 1;
$expected['type'] = 'number_integer';
$expected['settings'] = array(
$expected['settings'] = [
'thousand_separator' => ',',
'prefix_suffix' => TRUE,
);
];
$component = $display->getComponent('field_test_two');
$this->assertIdentical($expected, $component);
$expected['weight'] = 2;
$expected['type'] = 'number_decimal';
$expected['settings'] = array(
$expected['settings'] = [
'scale' => 2,
'decimal_separator' => '.',
'thousand_separator' => ',',
'prefix_suffix' => TRUE,
);
];
$component = $display->getComponent('field_test_three');
$this->assertIdentical($expected, $component);
// Test the email field formatter settings are correct.
$expected['weight'] = 6;
$expected['type'] = 'email_mailto';
$expected['settings'] = array();
$expected['settings'] = [];
$component = $display->getComponent('field_test_email');
$this->assertIdentical($expected, $component);
// Test the link field formatter settings.
$expected['weight'] = 7;
$expected['type'] = 'link';
$expected['settings'] = array(
$expected['settings'] = [
'trim_length' => 80,
'url_only' => TRUE,
'url_plain' => TRUE,
'rel' => '0',
'target' => '0',
);
];
$component = $display->getComponent('field_test_link');
$this->assertIdentical($expected, $component);
$expected['settings']['url_only'] = FALSE;
@ -110,7 +124,7 @@ class MigrateFieldFormatterSettingsTest extends MigrateDrupal6TestBase {
// Test the file field formatter settings.
$expected['weight'] = 8;
$expected['type'] = 'file_default';
$expected['settings'] = array();
$expected['settings'] = [];
$component = $display->getComponent('field_test_filefield');
$this->assertIdentical($expected, $component);
$display = EntityViewDisplay::load('node.story.default');
@ -121,7 +135,7 @@ class MigrateFieldFormatterSettingsTest extends MigrateDrupal6TestBase {
// Test the image field formatter settings.
$expected['weight'] = 9;
$expected['type'] = 'image';
$expected['settings'] = array('image_style' => '', 'image_link' => '');
$expected['settings'] = ['image_style' => '', 'image_link' => ''];
$component = $display->getComponent('field_test_imagefield');
$this->assertIdentical($expected, $component);
$display = EntityViewDisplay::load('node.story.teaser');
@ -132,15 +146,15 @@ class MigrateFieldFormatterSettingsTest extends MigrateDrupal6TestBase {
// Test phone field.
$expected['weight'] = 13;
$expected['type'] = 'basic_string';
$expected['settings'] = array();
$expected['settings'] = [];
$component = $display->getComponent('field_test_phone');
$this->assertIdentical($expected, $component);
// Test date field.
$defaults = array('format_type' => 'fallback', 'timezone_override' => '',);
$defaults = ['format_type' => 'fallback', 'timezone_override' => ''];
$expected['weight'] = 10;
$expected['type'] = 'datetime_default';
$expected['settings'] = array('format_type' => 'fallback') + $defaults;
$expected['settings'] = ['format_type' => 'fallback'] + $defaults;
$component = $display->getComponent('field_test_date');
$this->assertIdentical($expected, $component);
$display = EntityViewDisplay::load('node.story.default');
@ -154,13 +168,13 @@ class MigrateFieldFormatterSettingsTest extends MigrateDrupal6TestBase {
$component = $display->getComponent('field_test_datestamp');
$this->assertIdentical($expected, $component);
$display = EntityViewDisplay::load('node.story.teaser');
$expected['settings'] = array('format_type' => 'medium') + $defaults;
$expected['settings'] = ['format_type' => 'medium'] + $defaults;
$component = $display->getComponent('field_test_datestamp');
$this->assertIdentical($expected, $component);
// Test datetime field.
$expected['weight'] = 12;
$expected['settings'] = array('format_type' => 'short') + $defaults;
$expected['settings'] = ['format_type' => 'short'] + $defaults;
$component = $display->getComponent('field_test_datetime');
$this->assertIdentical($expected, $component);
$display = EntityViewDisplay::load('node.story.default');
@ -175,7 +189,10 @@ class MigrateFieldFormatterSettingsTest extends MigrateDrupal6TestBase {
$component = $display->getComponent('field_test_datetime');
$this->assertIdentical($expected, $component);
// Test that our Id map has the correct data.
$this->assertIdentical(array('node', 'story', 'teaser', 'field_test'), $this->getMigration('d6_field_formatter_settings')->getIdMap()->lookupDestinationID(array('story', 'teaser', 'node', 'field_test')));
$this->assertIdentical(['node', 'story', 'teaser', 'field_test'], $this->getMigration('d6_field_formatter_settings')->getIdMap()->lookupDestinationID(['story', 'teaser', 'node', 'field_test']));
// Test hidden field.
$this->assertComponentNotExists('node.test_planet.teaser', 'field_test_text_single_checkbox');
}
}

View file

@ -32,24 +32,24 @@ class MigrateFieldInstanceTest extends MigrateDrupal6TestBase {
// Test a number field.
$field = FieldConfig::load('node.story.field_test_two');
$this->assertIdentical('Integer Field', $field->label());
$expected = array(
$expected = [
'min' => 10,
'max' => 100,
'prefix' => 'pref',
'suffix' => 'suf',
'unsigned' => FALSE,
'size' => 'normal',
);
];
$this->assertIdentical($expected, $field->getSettings());
$field = FieldConfig::load('node.story.field_test_four');
$this->assertIdentical('Float Field', $field->label());
$expected = array(
$expected = [
'min' => 100.0,
'max' => 200.0,
'prefix' => 'id-',
'suffix' => '',
);
];
$this->assertIdentical($expected, $field->getSettings());
// Test email field.
@ -70,7 +70,7 @@ class MigrateFieldInstanceTest extends MigrateDrupal6TestBase {
// Test a filefield.
$field = FieldConfig::load('node.story.field_test_filefield');
$this->assertIdentical('File Field', $field->label());
$expected = array(
$expected = [
'file_extensions' => 'txt pdf doc',
'file_directory' => 'images',
'description_field' => TRUE,
@ -80,8 +80,8 @@ class MigrateFieldInstanceTest extends MigrateDrupal6TestBase {
'display_default' => FALSE,
'uri_scheme' => 'public',
'handler' => 'default:file',
'handler_settings' => array(),
);
'handler_settings' => [],
];
$field_settings = $field->getSettings();
ksort($expected);
ksort($field_settings);
@ -91,7 +91,7 @@ class MigrateFieldInstanceTest extends MigrateDrupal6TestBase {
// Test a link field.
$field = FieldConfig::load('node.story.field_test_link');
$this->assertIdentical('Link Field', $field->label());
$expected = array('title' => 2, 'link_type' => LinkItemInterface::LINK_GENERIC);
$expected = ['title' => 2, 'link_type' => LinkItemInterface::LINK_GENERIC];
$this->assertIdentical($expected, $field->getSettings());
$this->assertIdentical('default link title', $entity->field_test_link->title, 'Field field_test_link default title is correct.');
$this->assertIdentical('https://www.drupal.org', $entity->field_test_link->url, 'Field field_test_link default title is correct.');

View file

@ -33,38 +33,38 @@ class MigrateFieldTest extends MigrateDrupal6TestBase {
// Integer field.
$field_storage = FieldStorageConfig::load('node.field_test_two');
$this->assertIdentical("integer", $field_storage->getType(), t('Field type is @fieldtype. It should be integer.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("integer", $field_storage->getType(), t('Field type is @fieldtype. It should be integer.', ['@fieldtype' => $field_storage->getType()]));
// Float field.
$field_storage = FieldStorageConfig::load('node.field_test_three');
$this->assertIdentical("decimal", $field_storage->getType(), t('Field type is @fieldtype. It should be decimal.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("decimal", $field_storage->getType(), t('Field type is @fieldtype. It should be decimal.', ['@fieldtype' => $field_storage->getType()]));
// Link field.
$field_storage = FieldStorageConfig::load('node.field_test_link');
$this->assertIdentical("link", $field_storage->getType(), t('Field type is @fieldtype. It should be link.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("link", $field_storage->getType(), t('Field type is @fieldtype. It should be link.', ['@fieldtype' => $field_storage->getType()]));
// File field.
$field_storage = FieldStorageConfig::load('node.field_test_filefield');
$this->assertIdentical("file", $field_storage->getType(), t('Field type is @fieldtype. It should be file.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("file", $field_storage->getType(), t('Field type is @fieldtype. It should be file.', ['@fieldtype' => $field_storage->getType()]));
$field_storage = FieldStorageConfig::load('node.field_test_imagefield');
$this->assertIdentical("image", $field_storage->getType(), t('Field type is @fieldtype. It should be image.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("image", $field_storage->getType(), t('Field type is @fieldtype. It should be image.', ['@fieldtype' => $field_storage->getType()]));
$settings = $field_storage->getSettings();
$this->assertIdentical('file', $settings['target_type']);
$this->assertIdentical('public', $settings['uri_scheme']);
$this->assertIdentical(array(), array_filter($settings['default_image']));
$this->assertIdentical([], array_filter($settings['default_image']));
// Phone field.
$field_storage = FieldStorageConfig::load('node.field_test_phone');
$this->assertIdentical("telephone", $field_storage->getType(), t('Field type is @fieldtype. It should be telephone.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("telephone", $field_storage->getType(), t('Field type is @fieldtype. It should be telephone.', ['@fieldtype' => $field_storage->getType()]));
// Date field.
$field_storage = FieldStorageConfig::load('node.field_test_datetime');
$this->assertIdentical("datetime", $field_storage->getType(), t('Field type is @fieldtype. It should be datetime.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("datetime", $field_storage->getType(), t('Field type is @fieldtype. It should be datetime.', ['@fieldtype' => $field_storage->getType()]));
// Decimal field with radio buttons.
$field_storage = FieldStorageConfig::load('node.field_test_decimal_radio_buttons');
$this->assertIdentical("list_float", $field_storage->getType(), t('Field type is @fieldtype. It should be list_float.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("list_float", $field_storage->getType(), t('Field type is @fieldtype. It should be list_float.', ['@fieldtype' => $field_storage->getType()]));
$this->assertNotNull($field_storage->getSetting('allowed_values')['1.2'], t('First allowed value key is set to 1.2'));
$this->assertNotNull($field_storage->getSetting('allowed_values')['2.1'], t('Second allowed value key is set to 2.1'));
$this->assertIdentical('1.2', $field_storage->getSetting('allowed_values')['1.2'], t('First allowed value is set to 1.2'));
@ -72,11 +72,11 @@ class MigrateFieldTest extends MigrateDrupal6TestBase {
// Float field with a single checkbox.
$field_storage = FieldStorageConfig::load('node.field_test_float_single_checkbox');
$this->assertIdentical("boolean", $field_storage->getType(), t('Field type is @fieldtype. It should be boolean.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("boolean", $field_storage->getType(), t('Field type is @fieldtype. It should be boolean.', ['@fieldtype' => $field_storage->getType()]));
// Integer field with a select list.
$field_storage = FieldStorageConfig::load('node.field_test_integer_selectlist');
$this->assertIdentical("list_integer", $field_storage->getType(), t('Field type is @fieldtype. It should be list_integer.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("list_integer", $field_storage->getType(), t('Field type is @fieldtype. It should be list_integer.', ['@fieldtype' => $field_storage->getType()]));
$this->assertNotNull($field_storage->getSetting('allowed_values')['1234'], t('First allowed value key is set to 1234'));
$this->assertNotNull($field_storage->getSetting('allowed_values')['2341'], t('Second allowed value key is set to 2341'));
$this->assertNotNull($field_storage->getSetting('allowed_values')['3412'], t('Third allowed value key is set to 3412'));
@ -88,7 +88,7 @@ class MigrateFieldTest extends MigrateDrupal6TestBase {
// Text field with a single checkbox.
$field_storage = FieldStorageConfig::load('node.field_test_text_single_checkbox');
$this->assertIdentical("boolean", $field_storage->getType(), t('Field type is @fieldtype. It should be boolean.', array('@fieldtype' => $field_storage->getType())));
$this->assertIdentical("boolean", $field_storage->getType(), t('Field type is @fieldtype. It should be boolean.', ['@fieldtype' => $field_storage->getType()]));
// Validate that the source count and processed count match up.
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */

View file

@ -30,16 +30,17 @@ class MigrateFieldWidgetSettingsTest extends MigrateDrupal6TestBase {
// Text field.
$component = $form_display->getComponent('field_test');
$expected = array('weight' => 1, 'type' => 'text_textfield');
$expected['settings'] = array('size' => 60, 'placeholder' => '');
$expected['third_party_settings'] = array();
$expected = ['weight' => 1, 'type' => 'text_textfield'];
$expected['settings'] = ['size' => 60, 'placeholder' => ''];
$expected['third_party_settings'] = [];
$expected['region'] = 'content';
$this->assertIdentical($expected, $component, 'Text field settings are correct.');
// Integer field.
$component = $form_display->getComponent('field_test_two');
$expected['type'] = 'number';
$expected['weight'] = 1;
$expected['settings'] = array('placeholder' => '');
$expected['settings'] = ['placeholder' => ''];
$this->assertIdentical($expected, $component);
// Float field.
@ -51,7 +52,7 @@ class MigrateFieldWidgetSettingsTest extends MigrateDrupal6TestBase {
$component = $form_display->getComponent('field_test_email');
$expected['type'] = 'email_default';
$expected['weight'] = 6;
$expected['settings'] = array('placeholder' => '', 'size' => 60);
$expected['settings'] = ['placeholder' => '', 'size' => 60];
$this->assertIdentical($expected, $component);
// Link field.
@ -64,28 +65,28 @@ class MigrateFieldWidgetSettingsTest extends MigrateDrupal6TestBase {
$component = $form_display->getComponent('field_test_filefield');
$expected['type'] = 'file_generic';
$expected['weight'] = 8;
$expected['settings'] = array('progress_indicator' => 'bar');
$expected['settings'] = ['progress_indicator' => 'bar'];
$this->assertIdentical($expected, $component);
// Image field.
$component = $form_display->getComponent('field_test_imagefield');
$expected['type'] = 'image_image';
$expected['weight'] = 9;
$expected['settings'] = array('progress_indicator' => 'bar', 'preview_image_style' => 'thumbnail');
$expected['settings'] = ['progress_indicator' => 'bar', 'preview_image_style' => 'thumbnail'];
$this->assertIdentical($expected, $component);
// Phone field.
$component = $form_display->getComponent('field_test_phone');
$expected['type'] = 'telephone_default';
$expected['weight'] = 13;
$expected['settings'] = array('placeholder' => '');
$expected['settings'] = ['placeholder' => ''];
$this->assertIdentical($expected, $component);
// Date fields.
$component = $form_display->getComponent('field_test_date');
$expected['type'] = 'datetime_default';
$expected['weight'] = 10;
$expected['settings'] = array();
$expected['settings'] = [];
$this->assertIdentical($expected, $component);
$component = $form_display->getComponent('field_test_datestamp');

View file

@ -96,40 +96,40 @@ class MigrateFieldFormatterSettingsTest extends MigrateDrupal7TestBase {
// an "unsupported operand types" fatal).
Database::getConnection('default', 'migrate')
->update('field_config_instance')
->fields(array(
'data' => serialize(array (
->fields([
'data' => serialize( [
'label' => 'Body',
'widget' =>
array (
[
'type' => 'text_textarea_with_summary',
'settings' =>
array (
[
'rows' => 20,
'summary_rows' => 5,
),
],
'weight' => -4,
'module' => 'text',
),
],
'settings' =>
array (
[
'display_summary' => TRUE,
'text_processing' => 1,
'user_register_form' => FALSE,
),
],
'display' =>
array (
[
'default' =>
array (
[
'label' => 'hidden',
'type' => 'text_default',
'settings' =>
array (
),
[
],
'module' => 'text',
'weight' => 0,
),
],
'teaser' =>
array (
[
'label' => 'hidden',
'type' => 'text_summary_or_trimmed',
// settings is always expected to be an array. Making it NULL
@ -137,12 +137,12 @@ class MigrateFieldFormatterSettingsTest extends MigrateDrupal7TestBase {
'settings' => NULL,
'module' => 'text',
'weight' => 0,
),
),
],
],
'required' => FALSE,
'description' => '',
)),
))
]),
])
->condition('entity_type', 'node')
->condition('bundle', 'article')
->condition('field_name', 'body')

View file

@ -21,7 +21,7 @@ class MigrateFieldInstanceTest extends MigrateDrupal7TestBase {
*
* @var array
*/
public static $modules = array(
public static $modules = [
'comment',
'datetime',
'file',
@ -32,7 +32,7 @@ class MigrateFieldInstanceTest extends MigrateDrupal7TestBase {
'taxonomy',
'telephone',
'text',
);
];
/**
* {@inheritdoc}
@ -57,16 +57,16 @@ class MigrateFieldInstanceTest extends MigrateDrupal7TestBase {
* The node type ID.
*/
protected function createType($id) {
NodeType::create(array(
NodeType::create([
'type' => $id,
'label' => $this->randomString(),
))->save();
])->save();
CommentType::create(array(
CommentType::create([
'id' => 'comment_node_' . $id,
'label' => $this->randomString(),
'target_entity_type_id' => 'node',
))->save();
])->save();
}
/**
@ -80,8 +80,10 @@ class MigrateFieldInstanceTest extends MigrateDrupal7TestBase {
* The expected field type.
* @param bool $is_required
* Whether or not the field is required.
* @param bool $expected_translatable
* Whether or not the field is expected to be translatable.
*/
protected function assertEntity($id, $expected_label, $expected_field_type, $is_required) {
protected function assertEntity($id, $expected_label, $expected_field_type, $is_required, $expected_translatable) {
list ($expected_entity_type, $expected_bundle, $expected_name) = explode('.', $id);
/** @var \Drupal\field\FieldConfigInterface $field */
@ -94,6 +96,7 @@ class MigrateFieldInstanceTest extends MigrateDrupal7TestBase {
$this->assertIdentical($expected_name, $field->getName());
$this->assertEqual($is_required, $field->isRequired());
$this->assertIdentical($expected_entity_type . '.' . $expected_name, $field->getFieldStorageDefinition()->id());
$this->assertSame($expected_translatable, $field->isTranslatable());
}
/**
@ -113,40 +116,38 @@ class MigrateFieldInstanceTest extends MigrateDrupal7TestBase {
* Tests migrating D7 field instances to field_config entities.
*/
public function testFieldInstances() {
$this->assertEntity('comment.comment_node_page.comment_body', 'Comment', 'text_long', TRUE);
$this->assertEntity('node.page.body', 'Body', 'text_with_summary', FALSE);
$this->assertEntity('comment.comment_node_article.comment_body', 'Comment', 'text_long', TRUE);
$this->assertEntity('node.article.body', 'Body', 'text_with_summary', FALSE);
$this->assertEntity('node.article.field_tags', 'Tags', 'entity_reference', FALSE);
$this->assertEntity('node.article.field_image', 'Image', 'image', FALSE);
$this->assertEntity('comment.comment_node_blog.comment_body', 'Comment', 'text_long', TRUE);
$this->assertEntity('node.blog.body', 'Body', 'text_with_summary', FALSE);
$this->assertEntity('comment.comment_node_book.comment_body', 'Comment', 'text_long', TRUE);
$this->assertEntity('node.book.body', 'Body', 'text_with_summary', FALSE);
$this->assertEntity('node.forum.taxonomy_forums', 'Forums', 'entity_reference', TRUE);
$this->assertEntity('comment.comment_node_forum.comment_body', 'Comment', 'text_long', TRUE);
$this->assertEntity('node.forum.body', 'Body', 'text_with_summary', FALSE);
$this->assertEntity('comment.comment_node_test_content_type.comment_body', 'Comment', 'text_long', TRUE);
$this->assertEntity('node.test_content_type.field_boolean', 'Boolean', 'boolean', FALSE);
$this->assertEntity('node.test_content_type.field_email', 'Email', 'email', FALSE);
$this->assertEntity('node.test_content_type.field_phone', 'Phone', 'telephone', TRUE);
$this->assertEntity('node.test_content_type.field_date', 'Date', 'datetime', FALSE);
$this->assertEntity('node.test_content_type.field_date_with_end_time', 'Date With End Time', 'datetime', FALSE);
$this->assertEntity('node.test_content_type.field_file', 'File', 'file', FALSE);
$this->assertEntity('node.test_content_type.field_float', 'Float', 'float', FALSE);
$this->assertEntity('node.test_content_type.field_images', 'Images', 'image', TRUE);
$this->assertEntity('node.test_content_type.field_integer', 'Integer', 'integer', TRUE);
$this->assertEntity('node.test_content_type.field_link', 'Link', 'link', FALSE);
$this->assertEntity('node.test_content_type.field_text_list', 'Text List', 'list_string', FALSE);
$this->assertEntity('node.test_content_type.field_integer_list', 'Integer List', 'list_integer', FALSE);
$this->assertEntity('node.test_content_type.field_long_text', 'Long text', 'text_with_summary', FALSE);
$this->assertEntity('node.test_content_type.field_term_reference', 'Term Reference', 'entity_reference', FALSE);
$this->assertEntity('node.test_content_type.field_node_entityreference', 'Node Entity Reference', 'entity_reference', FALSE);
$this->assertEntity('node.test_content_type.field_user_entityreference', 'User Entity Reference', 'entity_reference', FALSE);
$this->assertEntity('node.test_content_type.field_term_entityreference', 'Term Entity Reference', 'entity_reference', FALSE);
$this->assertEntity('node.test_content_type.field_text', 'Text', 'text', FALSE);
$this->assertEntity('comment.comment_node_test_content_type.field_integer', 'Integer', 'integer', FALSE);
$this->assertEntity('user.user.field_file', 'File', 'file', FALSE);
$this->assertEntity('comment.comment_node_page.comment_body', 'Comment', 'text_long', TRUE, FALSE);
$this->assertEntity('node.page.body', 'Body', 'text_with_summary', FALSE, FALSE);
$this->assertEntity('comment.comment_node_article.comment_body', 'Comment', 'text_long', TRUE, FALSE);
$this->assertEntity('node.article.body', 'Body', 'text_with_summary', FALSE, TRUE);
$this->assertEntity('node.article.field_tags', 'Tags', 'entity_reference', FALSE, TRUE);
$this->assertEntity('node.article.field_image', 'Image', 'image', FALSE, TRUE);
$this->assertEntity('comment.comment_node_blog.comment_body', 'Comment', 'text_long', TRUE, FALSE);
$this->assertEntity('node.blog.body', 'Body', 'text_with_summary', FALSE, TRUE);
$this->assertEntity('comment.comment_node_book.comment_body', 'Comment', 'text_long', TRUE, FALSE);
$this->assertEntity('node.book.body', 'Body', 'text_with_summary', FALSE, FALSE);
$this->assertEntity('node.forum.taxonomy_forums', 'Forums', 'entity_reference', TRUE, FALSE);
$this->assertEntity('comment.comment_node_forum.comment_body', 'Comment', 'text_long', TRUE, FALSE);
$this->assertEntity('node.forum.body', 'Body', 'text_with_summary', FALSE, FALSE);
$this->assertEntity('comment.comment_node_test_content_type.comment_body', 'Comment', 'text_long', TRUE, FALSE);
$this->assertEntity('node.test_content_type.field_boolean', 'Boolean', 'boolean', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_email', 'Email', 'email', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_phone', 'Phone', 'telephone', TRUE, FALSE);
$this->assertEntity('node.test_content_type.field_date', 'Date', 'datetime', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_date_with_end_time', 'Date With End Time', 'datetime', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_file', 'File', 'file', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_float', 'Float', 'float', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_images', 'Images', 'image', TRUE, FALSE);
$this->assertEntity('node.test_content_type.field_integer', 'Integer', 'integer', TRUE, FALSE);
$this->assertEntity('node.test_content_type.field_link', 'Link', 'link', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_text_list', 'Text List', 'list_string', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_integer_list', 'Integer List', 'list_integer', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_long_text', 'Long text', 'text_with_summary', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_term_reference', 'Term Reference', 'entity_reference', FALSE, FALSE);
$this->assertEntity('node.test_content_type.field_text', 'Text', 'text', FALSE, FALSE);
$this->assertEntity('comment.comment_node_test_content_type.field_integer', 'Integer', 'integer', FALSE, FALSE);
$this->assertEntity('user.user.field_file', 'File', 'file', FALSE, FALSE);
$this->assertLinkFields('node.test_content_type.field_link', DRUPAL_OPTIONAL);
$this->assertLinkFields('node.article.field_link', DRUPAL_DISABLED);

View file

@ -18,7 +18,7 @@ class MigrateFieldInstanceWidgetSettingsTest extends MigrateDrupal7TestBase {
*
* @var array
*/
public static $modules = array(
public static $modules = [
'comment',
'datetime',
'field',
@ -29,7 +29,7 @@ class MigrateFieldInstanceWidgetSettingsTest extends MigrateDrupal7TestBase {
'taxonomy',
'telephone',
'text',
);
];
/**
* {@inheritdoc}

View file

@ -18,7 +18,7 @@ class MigrateFieldTest extends MigrateDrupal7TestBase {
*
* @var array
*/
public static $modules = array(
public static $modules = [
'comment',
'datetime',
'file',
@ -29,7 +29,7 @@ class MigrateFieldTest extends MigrateDrupal7TestBase {
'taxonomy',
'telephone',
'text',
);
];
/**
* {@inheritdoc}
@ -60,8 +60,6 @@ class MigrateFieldTest extends MigrateDrupal7TestBase {
$this->assertTrue($field instanceof FieldStorageConfigInterface);
$this->assertIdentical($expected_name, $field->getName());
$this->assertIdentical($expected_type, $field->getType());
// FieldStorageConfig::$translatable is TRUE by default, so it is useful
// to test for FALSE here.
$this->assertEqual($expected_translatable, $field->isTranslatable());
$this->assertIdentical($expected_entity_type, $field->getTargetEntityTypeId());
@ -78,31 +76,31 @@ class MigrateFieldTest extends MigrateDrupal7TestBase {
* Tests migrating D7 fields to field_storage_config entities.
*/
public function testFields() {
$this->assertEntity('node.body', 'text_with_summary', FALSE, 1);
$this->assertEntity('node.field_long_text', 'text_with_summary', FALSE, 1);
$this->assertEntity('comment.comment_body', 'text_long', FALSE, 1);
$this->assertEntity('node.field_file', 'file', FALSE, 1);
$this->assertEntity('user.field_file', 'file', FALSE, 1);
$this->assertEntity('node.field_float', 'float', FALSE, 1);
$this->assertEntity('node.field_image', 'image', FALSE, 1);
$this->assertEntity('node.field_images', 'image', FALSE, 1);
$this->assertEntity('node.field_integer', 'integer', FALSE, 1);
$this->assertEntity('comment.field_integer', 'integer', FALSE, 1);
$this->assertEntity('node.field_integer_list', 'list_integer', FALSE, 1);
$this->assertEntity('node.field_link', 'link', FALSE, 1);
$this->assertEntity('node.field_tags', 'entity_reference', FALSE, -1);
$this->assertEntity('node.field_term_reference', 'entity_reference', FALSE, 1);
$this->assertEntity('node.taxonomy_forums', 'entity_reference', FALSE, 1);
$this->assertEntity('node.field_text', 'text', FALSE, 1);
$this->assertEntity('node.field_text_list', 'list_string', FALSE, 3);
$this->assertEntity('node.field_boolean', 'boolean', FALSE, 1);
$this->assertEntity('node.field_email', 'email', FALSE, -1);
$this->assertEntity('node.field_phone', 'telephone', FALSE, 1);
$this->assertEntity('node.field_date', 'datetime', FALSE, 1);
$this->assertEntity('node.field_date_with_end_time', 'datetime', FALSE, 1);
$this->assertEntity('node.field_node_entityreference', 'entity_reference', FALSE, -1);
$this->assertEntity('node.field_user_entityreference', 'entity_reference', FALSE, 1);
$this->assertEntity('node.field_term_entityreference', 'entity_reference', FALSE, -1);
$this->assertEntity('node.body', 'text_with_summary', TRUE, 1);
$this->assertEntity('node.field_long_text', 'text_with_summary', TRUE, 1);
$this->assertEntity('comment.comment_body', 'text_long', TRUE, 1);
$this->assertEntity('node.field_file', 'file', TRUE, 1);
$this->assertEntity('user.field_file', 'file', TRUE, 1);
$this->assertEntity('node.field_float', 'float', TRUE, 1);
$this->assertEntity('node.field_image', 'image', TRUE, 1);
$this->assertEntity('node.field_images', 'image', TRUE, 1);
$this->assertEntity('node.field_integer', 'integer', TRUE, 1);
$this->assertEntity('comment.field_integer', 'integer', TRUE, 1);
$this->assertEntity('node.field_integer_list', 'list_integer', TRUE, 1);
$this->assertEntity('node.field_link', 'link', TRUE, 1);
$this->assertEntity('node.field_tags', 'entity_reference', TRUE, -1);
$this->assertEntity('node.field_term_reference', 'entity_reference', TRUE, 1);
$this->assertEntity('node.taxonomy_forums', 'entity_reference', TRUE, 1);
$this->assertEntity('node.field_text', 'text', TRUE, 1);
$this->assertEntity('node.field_text_list', 'list_string', TRUE, 3);
$this->assertEntity('node.field_boolean', 'boolean', TRUE, 1);
$this->assertEntity('node.field_email', 'email', TRUE, -1);
$this->assertEntity('node.field_phone', 'telephone', TRUE, 1);
$this->assertEntity('node.field_date', 'datetime', TRUE, 1);
$this->assertEntity('node.field_date_with_end_time', 'datetime', TRUE, 1);
$this->assertEntity('node.field_node_entityreference', 'entity_reference', TRUE, -1);
$this->assertEntity('node.field_user_entityreference', 'entity_reference', TRUE, 1);
$this->assertEntity('node.field_term_entityreference', 'entity_reference', TRUE, -1);
// Assert that the taxonomy term reference fields are referencing the
// correct entity type.
@ -123,7 +121,8 @@ class MigrateFieldTest extends MigrateDrupal7TestBase {
// Validate that the source count and processed count match up.
/** @var \Drupal\migrate\Plugin\MigrationInterface $migration */
$migration = $this->getMigration('d7_field');
$this->assertIdentical($migration->getSourcePlugin()->count(), $migration->getIdMap()->processedCount());
$this->assertSame($migration->getSourcePlugin()
->count(), $migration->getIdMap()->processedCount());
}
}

View file

@ -21,18 +21,18 @@ class NumberItemTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array();
public static $modules = [];
protected function setUp() {
parent::setUp();
// Create number field storages and fields for validation.
foreach (array('integer', 'float', 'decimal') as $type) {
FieldStorageConfig::create(array(
foreach (['integer', 'float', 'decimal'] as $type) {
FieldStorageConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_' . $type,
'type' => $type,
))->save();
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_' . $type,

View file

@ -94,6 +94,7 @@ class FieldInstanceTest extends MigrateSqlSourceTestBase {
],
'description' => '',
'required' => FALSE,
'field_data' => 'a:6:{s:12:"entity_types";a:1:{i:0;s:4:"node";}s:12:"translatable";b:0;s:8:"settings";a:0:{}s:7:"storage";a:4:{s:4:"type";s:17:"field_sql_storage";s:8:"settings";a:0:{}s:6:"module";s:17:"field_sql_storage";s:6:"active";i:1;}s:12:"foreign keys";a:1:{s:6:"format";a:2:{s:5:"table";s:13:"filter_format";s:7:"columns";a:1:{s:6:"format";s:6:"format";}}}s:7:"indexes";a:1:{s:6:"format";a:1:{i:0;s:6:"format";}}}',
],
];

View file

@ -20,7 +20,7 @@ class ShapeItemTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array('field_test');
public static $modules = ['field_test'];
/**
* The name of the field to use in this test.
@ -33,11 +33,11 @@ class ShapeItemTest extends FieldKernelTestBase {
parent::setUp();
// Create a 'shape' field and storage for validation.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $this->fieldName,
'entity_type' => 'entity_test',
'type' => 'shape',
))->save();
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => $this->fieldName,

View file

@ -23,7 +23,7 @@ class RawStringFormatterTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('field', 'text', 'entity_test', 'system', 'filter', 'user');
public static $modules = ['field', 'text', 'entity_test', 'system', 'filter', 'user'];
/**
* @var string
@ -52,7 +52,7 @@ class RawStringFormatterTest extends KernelTestBase {
parent::setUp();
// Configure the theme system.
$this->installConfig(array('system', 'field'));
$this->installConfig(['system', 'field']);
\Drupal::service('router.builder')->rebuild();
$this->installEntitySchema('entity_test');
@ -60,25 +60,25 @@ class RawStringFormatterTest extends KernelTestBase {
$this->bundle = $this->entityType;
$this->fieldName = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => $this->fieldName,
'entity_type' => $this->entityType,
'type' => 'string_long',
));
]);
$field_storage->save();
$instance = FieldConfig::create(array(
$instance = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => $this->bundle,
'label' => $this->randomMachineName(),
));
]);
$instance->save();
$this->display = entity_get_display($this->entityType, $this->bundle, 'default')
->setComponent($this->fieldName, array(
->setComponent($this->fieldName, [
'type' => 'string',
'settings' => array(),
));
'settings' => [],
]);
$this->display->save();
}
@ -107,7 +107,7 @@ class RawStringFormatterTest extends KernelTestBase {
$value .= "\n\n<strong>" . $this->randomString() . '</strong>';
$value .= "\n\n" . $this->randomString();
$entity = EntityTest::create(array());
$entity = EntityTest::create([]);
$entity->{$this->fieldName}->value = $value;
// Verify that all HTML is escaped and newlines are retained.

View file

@ -23,7 +23,7 @@ class StringFormatterTest extends KernelTestBase {
*
* @var array
*/
public static $modules = array('field', 'text', 'entity_test', 'system', 'filter', 'user');
public static $modules = ['field', 'text', 'entity_test', 'system', 'filter', 'user'];
/**
* @var string
@ -52,7 +52,7 @@ class StringFormatterTest extends KernelTestBase {
parent::setUp();
// Configure the theme system.
$this->installConfig(array('system', 'field'));
$this->installConfig(['system', 'field']);
\Drupal::service('router.builder')->rebuild();
$this->installEntitySchema('entity_test_rev');
@ -60,25 +60,25 @@ class StringFormatterTest extends KernelTestBase {
$this->bundle = $this->entityType;
$this->fieldName = Unicode::strtolower($this->randomMachineName());
$field_storage = FieldStorageConfig::create(array(
$field_storage = FieldStorageConfig::create([
'field_name' => $this->fieldName,
'entity_type' => $this->entityType,
'type' => 'string',
));
]);
$field_storage->save();
$instance = FieldConfig::create(array(
$instance = FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => $this->bundle,
'label' => $this->randomMachineName(),
));
]);
$instance->save();
$this->display = entity_get_display($this->entityType, $this->bundle, 'default')
->setComponent($this->fieldName, array(
->setComponent($this->fieldName, [
'type' => 'string',
'settings' => array(),
));
'settings' => [],
]);
$this->display->save();
}
@ -107,7 +107,7 @@ class StringFormatterTest extends KernelTestBase {
$value .= "\n\n<strong>" . $this->randomString() . '</strong>';
$value .= "\n\n" . $this->randomString();
$entity = EntityTestRev::create(array());
$entity = EntityTestRev::create([]);
$entity->{$this->fieldName}->value = $value;
// Verify that all HTML is escaped and newlines are retained.

View file

@ -21,7 +21,7 @@ class TestItemTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array('field_test');
public static $modules = ['field_test'];
/**
* The name of the field to use in this test.
@ -34,11 +34,11 @@ class TestItemTest extends FieldKernelTestBase {
parent::setUp();
// Create a 'test_field' field and storage for validation.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $this->fieldName,
'entity_type' => 'entity_test',
'type' => 'test_field',
))->save();
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => $this->fieldName,
@ -76,19 +76,19 @@ class TestItemTest extends FieldKernelTestBase {
$this->assertEqual($entity->{$this->fieldName}->value, $new_value);
// Test the schema for this field type.
$expected_schema = array(
'columns' => array(
'value' => array(
$expected_schema = [
'columns' => [
'value' => [
'type' => 'int',
'size' => 'medium',
),
),
'unique keys' => array(),
'indexes' => array(
'value' => array('value'),
),
'foreign keys' => array(),
);
],
],
'unique keys' => [],
'indexes' => [
'value' => ['value'],
],
'foreign keys' => [],
];
$field_schema = BaseFieldDefinition::create('test_field')->getSchema();
$this->assertEqual($field_schema, $expected_schema);
}

View file

@ -17,7 +17,7 @@ class TestItemWithDependenciesTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array('field_test');
public static $modules = ['field_test'];
/**
* The name of the field to use in this test.
@ -31,11 +31,11 @@ class TestItemWithDependenciesTest extends FieldKernelTestBase {
*/
public function testTestItemWithDepenencies() {
// Create a 'test_field_with_dependencies' field and storage for validation.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => $this->fieldName,
'entity_type' => 'entity_test',
'type' => 'test_field_with_dependencies',
))->save();
])->save();
$field = FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => $this->fieldName,

View file

@ -18,7 +18,7 @@ class TestObjectItemTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array('field_test');
public static $modules = ['field_test'];
/**
* {@inheritdoc}
@ -27,11 +27,11 @@ class TestObjectItemTest extends FieldKernelTestBase {
parent::setUp();
// Create a 'test_field' field and storage for validation.
FieldStorageConfig::create(array(
FieldStorageConfig::create([
'field_name' => 'field_test',
'entity_type' => 'entity_test',
'type' => 'test_object_field',
))->save();
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test',

View file

@ -140,7 +140,7 @@ class TimestampFormatterTest extends KernelTestBase {
public function testTimestampAgoFormatter() {
$data = [];
foreach (array(1, 2, 3, 4, 5, 6) as $granularity) {
foreach ([1, 2, 3, 4, 5, 6] as $granularity) {
$data[] = [
'future_format' => '@interval hence',
'past_format' => '@interval ago',

View file

@ -23,7 +23,7 @@ class TranslationTest extends FieldKernelTestBase {
*
* @var array
*/
public static $modules = array('language', 'node');
public static $modules = ['language', 'node'];
/**
* The name of the field to use in this test.
@ -73,40 +73,40 @@ class TranslationTest extends FieldKernelTestBase {
protected function setUp() {
parent::setUp();
$this->installConfig(array('language'));
$this->installConfig(['language']);
$this->fieldName = Unicode::strtolower($this->randomMachineName());
$this->entityType = 'entity_test';
$this->fieldStorageDefinition = array(
$this->fieldStorageDefinition = [
'field_name' => $this->fieldName,
'entity_type' => $this->entityType,
'type' => 'test_field',
'cardinality' => 4,
);
];
$this->fieldStorage = FieldStorageConfig::create($this->fieldStorageDefinition);
$this->fieldStorage->save();
$this->fieldDefinition = array(
$this->fieldDefinition = [
'field_storage' => $this->fieldStorage,
'bundle' => 'entity_test',
);
];
$this->field = FieldConfig::create($this->fieldDefinition);
$this->field->save();
for ($i = 0; $i < 3; ++$i) {
ConfigurableLanguage::create(array(
ConfigurableLanguage::create([
'id' => 'l' . $i,
'label' => $this->randomString(),
))->save();
])->save();
}
}
/**
* Test translatable fields storage/retrieval.
*/
function testTranslatableFieldSaveLoad() {
public function testTranslatableFieldSaveLoad() {
// Enable field translations for nodes.
field_test_entity_info_translatable('node', TRUE);
$entity_type = \Drupal::entityManager()->getDefinition('node');
@ -117,8 +117,8 @@ class TranslationTest extends FieldKernelTestBase {
field_test_entity_info_translatable($entity_type_id, TRUE);
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type_id)
->create(array('type' => $this->field->getTargetBundle()));
$field_translations = array();
->create(['type' => $this->field->getTargetBundle()]);
$field_translations = [];
$available_langcodes = array_keys($this->container->get('language_manager')->getLanguages());
$entity->langcode->value = reset($available_langcodes);
foreach ($available_langcodes as $langcode) {
@ -136,7 +136,7 @@ class TranslationTest extends FieldKernelTestBase {
foreach ($items as $delta => $item) {
$result = $result && $item['value'] == $entity->getTranslation($langcode)->{$this->fieldName}[$delta]->value;
}
$this->assertTrue($result, format_string('%language translation correctly handled.', array('%language' => $langcode)));
$this->assertTrue($result, format_string('%language translation correctly handled.', ['%language' => $langcode]));
}
// Test default values.
@ -148,7 +148,7 @@ class TranslationTest extends FieldKernelTestBase {
$field_definition = $this->fieldDefinition;
$field_definition['field_storage'] = $field_storage;
$field_definition['default_value'] = array(array('value' => rand(1, 127)));
$field_definition['default_value'] = [['value' => rand(1, 127)]];
$field = FieldConfig::create($field_definition);
$field->save();
@ -156,7 +156,7 @@ class TranslationTest extends FieldKernelTestBase {
asort($translation_langcodes);
$translation_langcodes = array_values($translation_langcodes);
$values = array('type' => $field->getTargetBundle(), 'langcode' => $translation_langcodes[0]);
$values = ['type' => $field->getTargetBundle(), 'langcode' => $translation_langcodes[0]];
$entity = $this->container->get('entity_type.manager')
->getStorage($entity_type_id)
->create($values);
@ -173,11 +173,11 @@ class TranslationTest extends FieldKernelTestBase {
// @todo Test every translation once the Entity Translation API allows for
// multilingual defaults.
$langcode = $entity->language()->getId();
$this->assertEqual($entity->getTranslation($langcode)->{$field_name_default}->getValue(), $field->getDefaultValueLiteral(), format_string('Default value correctly populated for language %language.', array('%language' => $langcode)));
$this->assertEqual($entity->getTranslation($langcode)->{$field_name_default}->getValue(), $field->getDefaultValueLiteral(), format_string('Default value correctly populated for language %language.', ['%language' => $langcode]));
// Check that explicit empty values are not overridden with default values.
foreach (array(NULL, array()) as $empty_items) {
$values = array('type' => $field->getTargetBundle(), 'langcode' => $translation_langcodes[0]);
foreach ([NULL, []] as $empty_items) {
$values = ['type' => $field->getTargetBundle(), 'langcode' => $translation_langcodes[0]];
$entity = entity_create($entity_type_id, $values);
foreach ($translation_langcodes as $langcode) {
$values[$this->fieldName][$langcode] = $this->_generateTestFieldValues($this->fieldStorage->getCardinality());
@ -188,7 +188,7 @@ class TranslationTest extends FieldKernelTestBase {
}
foreach ($entity->getTranslationLanguages() as $langcode => $language) {
$this->assertEquals([], $entity->getTranslation($langcode)->{$field_name_default}->getValue(), format_string('Empty value correctly populated for language %language.', array('%language' => $langcode)));
$this->assertEquals([], $entity->getTranslation($langcode)->{$field_name_default}->getValue(), format_string('Empty value correctly populated for language %language.', ['%language' => $langcode]));
}
}
}

View file

@ -13,7 +13,7 @@ class WidgetPluginManagerTest extends FieldKernelTestBase {
/**
* Tests that the widget definitions alter hook works.
*/
function testWidgetDefinitionAlter() {
public function testWidgetDefinitionAlter() {
$widget_definition = \Drupal::service('plugin.manager.field.widget')->getDefinition('test_field_widget_multiple');
// Test if hook_field_widget_info_alter is being called.
@ -33,13 +33,13 @@ class WidgetPluginManagerTest extends FieldKernelTestBase {
// Set a name that will make isApplicable() return TRUE.
->setName('field_multiwidgetfield');
$widget_options = array(
$widget_options = [
'field_definition' => $base_field_definition,
'form_mode' => 'default',
'configuration' => array(
'configuration' => [
'type' => 'test_field_widget_multiple',
),
);
],
];
$instance = $widget_plugin_manager->getInstance($widget_options);
$this->assertEqual($instance->getPluginId(), 'test_field_widget_multiple');

View file

@ -100,14 +100,14 @@ class FieldConfigEntityUnitTest extends UnitTestCase {
->will($this->returnValue('field_test'));
$this->fieldStorage->expects($this->any())
->method('getSettings')
->willReturn(array());
->willReturn([]);
// Place the field in the mocked entity manager's field registry.
$this->entityManager->expects($this->any())
->method('getFieldStorageDefinitions')
->with('test_entity_type')
->will($this->returnValue(array(
->will($this->returnValue([
$this->fieldStorage->getName() => $this->fieldStorage,
)));
]));
}
/**
@ -118,7 +118,7 @@ class FieldConfigEntityUnitTest extends UnitTestCase {
$target_entity_type = $this->getMock('\Drupal\Core\Entity\EntityTypeInterface');
$target_entity_type->expects($this->any())
->method('getBundleConfigDependency')
->will($this->returnValue(array('type' => 'config', 'name' => 'test.test_entity_type.id')));
->will($this->returnValue(['type' => 'config', 'name' => 'test.test_entity_type.id']));
$this->entityManager->expects($this->at(0))
->method('getDefinition')
@ -146,12 +146,12 @@ class FieldConfigEntityUnitTest extends UnitTestCase {
->method('getConfigDependencyName')
->will($this->returnValue('field.storage.test_entity_type.test_field'));
$field = new FieldConfig(array(
$field = new FieldConfig([
'field_name' => $this->fieldStorage->getName(),
'entity_type' => 'test_entity_type',
'bundle' => 'test_bundle',
'field_type' => 'test_field',
), $this->entityTypeId);
], $this->entityTypeId);
$dependencies = $field->calculateDependencies()->getDependencies();
$this->assertContains('field.storage.test_entity_type.test_field', $dependencies['config']);
$this->assertContains('test.test_entity_type.id', $dependencies['config']);
@ -160,9 +160,6 @@ class FieldConfigEntityUnitTest extends UnitTestCase {
/**
* Test that invalid bundles are handled.
*
* @expectedException \LogicException
* @expectedExceptionMessage Missing bundle entity, entity type bundle_entity_type, entity id test_bundle_not_exists.
*/
public function testCalculateDependenciesIncorrectBundle() {
$storage = $this->getMock('\Drupal\Core\Config\Entity\ConfigEntityStorageInterface');
@ -176,10 +173,10 @@ class FieldConfigEntityUnitTest extends UnitTestCase {
->with('bundle_entity_type')
->will($this->returnValue($storage));
$target_entity_type = new EntityType(array(
$target_entity_type = new EntityType([
'id' => 'test_entity_type',
'bundle_entity_type' => 'bundle_entity_type',
));
]);
$this->entityManager->expects($this->at(0))
->method('getDefinition')
@ -203,12 +200,13 @@ class FieldConfigEntityUnitTest extends UnitTestCase {
->with('test_field')
->willReturn(['provider' => 'test_module', 'config_dependencies' => ['module' => ['test_module2']], 'class' => '\Drupal\Tests\field\Unit\DependencyFieldItem']);
$field = new FieldConfig(array(
$field = new FieldConfig([
'field_name' => $this->fieldStorage->getName(),
'entity_type' => 'test_entity_type',
'bundle' => 'test_bundle_not_exists',
'field_type' => 'test_field',
), $this->entityTypeId);
], $this->entityTypeId);
$this->setExpectedException(\LogicException::class, 'Missing bundle entity, entity type bundle_entity_type, entity id test_bundle_not_exists.');
$field->calculateDependencies();
}
@ -245,14 +243,14 @@ class FieldConfigEntityUnitTest extends UnitTestCase {
* @covers ::toArray
*/
public function testToArray() {
$field = new FieldConfig(array(
$field = new FieldConfig([
'field_name' => $this->fieldStorage->getName(),
'entity_type' => 'test_entity_type',
'bundle' => 'test_bundle',
'field_type' => 'test_field',
), $this->entityTypeId);
], $this->entityTypeId);
$expected = array(
$expected = [
'id' => 'test_entity_type.test_bundle.field_test',
'uuid' => NULL,
'status' => TRUE,
@ -263,12 +261,12 @@ class FieldConfigEntityUnitTest extends UnitTestCase {
'label' => '',
'description' => '',
'required' => FALSE,
'default_value' => array(),
'default_value' => [],
'default_value_callback' => '',
'settings' => array(),
'dependencies' => array(),
'settings' => [],
'dependencies' => [],
'field_type' => 'test_field',
);
];
$this->entityManager->expects($this->any())
->method('getDefinition')
->with($this->entityTypeId)
@ -279,7 +277,7 @@ class FieldConfigEntityUnitTest extends UnitTestCase {
->will($this->returnValue('id'));
$this->typedConfigManager->expects($this->once())
->method('getDefinition')
->will($this->returnValue(array('mapping' => array_fill_keys(array_keys($expected), ''))));
->will($this->returnValue(['mapping' => array_fill_keys(array_keys($expected), '')]));
$export = $field->toArray();
$this->assertEquals($expected, $export);
@ -296,12 +294,12 @@ class FieldConfigEntityUnitTest extends UnitTestCase {
$this->fieldStorage->expects($this->never())
->method('getType');
$field = new FieldConfig(array(
$field = new FieldConfig([
'field_name' => $this->fieldStorage->getName(),
'entity_type' => 'test_entity_type',
'bundle' => 'test_bundle',
'field_type' => 'test_field',
), $this->entityTypeId);
], $this->entityTypeId);
$this->assertEquals('test_field', $field->getType());
}

View file

@ -36,32 +36,32 @@ class FieldSettingsTest extends UnitTestCase {
* Provides field settings for testGetSettings().
*/
public function getSettingsProvider() {
return array(
array(
return [
[
'list_integer',
array('allowed_values' => "1|One\n2|Two\n3"),
array(
['allowed_values' => "1|One\n2|Two\n3"],
[
'1' => 'One',
'2' => 'Two',
'3' => '3',
),
),
array(
],
],
[
'list_string',
array('allowed_values' => NULL),
array(),
),
array(
['allowed_values' => NULL],
[],
],
[
'list_float',
array('allowed_values' => ""),
array(),
),
array(
['allowed_values' => ""],
[],
],
[
'boolean',
array(),
array(),
),
);
[],
[],
],
];
}
}