diff --git a/core/lib/Drupal/Core/Entity/ContentEntityBase.php b/core/lib/Drupal/Core/Entity/ContentEntityBase.php index afddb228b9..9f711efa13 100644 --- a/core/lib/Drupal/Core/Entity/ContentEntityBase.php +++ b/core/lib/Drupal/Core/Entity/ContentEntityBase.php @@ -486,7 +486,7 @@ public function hasField($field_name) { * {@inheritdoc} */ public function get($field_name) { - if (!isset($this->fields[$field_name][$this->activeLangcode])) { + if (!isset($this->fields[$field_name][$this->activeLangcode]) || $this->fields[$field_name][$this->activeLangcode]->isComputed()) { return $this->getTranslatedField($field_name, $this->activeLangcode); } return $this->fields[$field_name][$this->activeLangcode]; @@ -503,7 +503,9 @@ protected function getTranslatedField($name, $langcode) { } // Populate $this->fields to speed-up further look-ups and to keep track of // fields objects, possibly holding changes to field values. - if (!isset($this->fields[$name][$langcode])) { + // Computed fields are always computed as their value might be subject to + // changes in the entities' lifecycle. + if (!isset($this->fields[$name][$langcode]) || $this->fields[$name][$langcode]->isComputed()) { $definition = $this->getFieldDefinition($name); if (!$definition) { throw new \InvalidArgumentException("Field $name is unknown."); diff --git a/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php b/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php index 9d6b8d64f5..2596cf3dc4 100644 --- a/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php +++ b/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php @@ -108,7 +108,7 @@ protected function initFieldValues(ContentEntityInterface $entity, array $values if (isset($values[$name])) { $entity->$name = $values[$name]; } - elseif (!array_key_exists($name, $values)) { + elseif (!array_key_exists($name, $values) && !$field->isComputed()) { $entity->get($name)->applyDefaultValue(); } } diff --git a/core/lib/Drupal/Core/Field/FieldItemList.php b/core/lib/Drupal/Core/Field/FieldItemList.php index a1a1ebdb9e..ea3e727e37 100644 --- a/core/lib/Drupal/Core/Field/FieldItemList.php +++ b/core/lib/Drupal/Core/Field/FieldItemList.php @@ -7,7 +7,9 @@ use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Language\LanguageInterface; use Drupal\Core\Session\AccountInterface; +use Drupal\Core\TypedData\DataDefinitionInterface; use Drupal\Core\TypedData\Plugin\DataType\ItemList; +use Drupal\Core\TypedData\TypedDataInterface; /** * Represents an entity field; that is, a list of field item objects. @@ -160,6 +162,24 @@ public function __unset($property_name) { /** * {@inheritdoc} */ + public function isComputed() { + return $this instanceof FieldItemListComputedInterface; + } + + /** + * {@inheritdoc} + */ + public function setComputedValues() { + $this->list = $this->computeValues(); + $errors = $this->validate()->getIterator(); + if ($errors->current()) { + throw new FieldException($errors->current()->getMessage()); + } + } + + /** + * {@inheritdoc} + */ public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) { $access_control_handler = \Drupal::entityManager()->getAccessControlHandler($this->getEntity()->getEntityTypeId()); return $access_control_handler->fieldAccess($operation, $this->getFieldDefinition(), $account, $this, $return_as_object); diff --git a/core/lib/Drupal/Core/Field/FieldItemListComputedInterface.php b/core/lib/Drupal/Core/Field/FieldItemListComputedInterface.php new file mode 100644 index 0000000000..cb8cd21f13 --- /dev/null +++ b/core/lib/Drupal/Core/Field/FieldItemListComputedInterface.php @@ -0,0 +1,20 @@ +setValue($value, FALSE); } + elseif ($property instanceof FieldItemListComputedInterface) { + // Populate the computed list with values as there are no initial values + // to set. + $property->setComputedValues(); + } return $property; } diff --git a/core/modules/field/tests/modules/field_computed_test/field_computed_test.info.yml b/core/modules/field/tests/modules/field_computed_test/field_computed_test.info.yml new file mode 100644 index 0000000000..42f6216f07 --- /dev/null +++ b/core/modules/field/tests/modules/field_computed_test/field_computed_test.info.yml @@ -0,0 +1,6 @@ +name: 'Field Computed Test' +type: module +description: 'Support module for the computed field tests.' +core: 8.x +package: Testing +version: VERSION diff --git a/core/modules/field/tests/modules/field_computed_test/field_computed_test.module b/core/modules/field/tests/modules/field_computed_test/field_computed_test.module new file mode 100644 index 0000000000..03bc47b4fc --- /dev/null +++ b/core/modules/field/tests/modules/field_computed_test/field_computed_test.module @@ -0,0 +1,57 @@ +id() === 'entity_test') { + + // Add fields to separate bundles so we can test them individually. + switch ($bundle) { + case 'valid_computed_timestamp': + $fields['valid_computed_timestamp'] = BaseFieldDefinition::create('timestamp') + ->setComputed(TRUE) + ->setClass(ComputedValuesItemList::class) + ->setSetting('field', 'valid_computed_timestamp') + ->setLabel(t('Request Time')); + case 'valid_computed_entity_reference': + $fields['valid_computed_entity_reference'] = BaseFieldDefinition::create('entity_reference') + ->setComputed(TRUE) + ->setSetting('target_type', 'entity_test') + ->setClass(ComputedValuesItemList::class) + ->setSetting('field', 'valid_computed_entity_reference') + ->setLabel(t('Valid Computed Entity Reference')); + break; + case 'non_valid_computed_timestamp': + $fields['non_valid_computed_timestamp'] = BaseFieldDefinition::create('timestamp') + ->setComputed(TRUE) + ->setClass(ComputedValuesItemList::class) + ->setSetting('field', 'non_valid_computed_timestamp') + ->setLabel(t('Non valid computed integer')); + break; + case 'non_valid_computed_entity_reference': + $fields['non_valid_computed_entity_reference'] = BaseFieldDefinition::create('entity_reference') + ->setComputed(TRUE) + ->setSetting('target_type', 'entity_test') + ->setClass(ComputedValuesItemList::class) + ->setSetting('field', 'non_valid_computed_entity_reference') + ->setLabel(t('Valid Computed Entity Reference')); + break; + } + } + return $fields; +} diff --git a/core/modules/field/tests/modules/field_computed_test/src/Plugin/Field/FieldType/ComputedValuesItemList.php b/core/modules/field/tests/modules/field_computed_test/src/Plugin/Field/FieldType/ComputedValuesItemList.php new file mode 100644 index 0000000000..5e182cea75 --- /dev/null +++ b/core/modules/field/tests/modules/field_computed_test/src/Plugin/Field/FieldType/ComputedValuesItemList.php @@ -0,0 +1,55 @@ +getSetting('field')) { + case 'valid_computed_timestamp': + $items = []; + $items[] = $this->createItem(0, [ + 'value' => \Drupal::time()->getRequestTime(), + ]); + return $items; + + case 'valid_computed_entity_reference': + $items = []; + $parent = $this->getEntity(); + if (!$parent->isNew()) { + $items[] = $this->createItem(0, [ + 'target_id' => $parent->id() === 1 ? 2 : 1, + ]); + } + return $items; + + case 'non_valid_computed_entity_reference': + $items = []; + $parent = $this->getEntity(); + if (!$parent->isNew()) { + $items[] = $this->createItem(0, [ + 'target_id' => '3', + ]); + } + return $items; + + case 'non_valid_computed_timestamp': + $items = []; + $items[] = $this->createItem(0, [ + 'value' => 'A', + ]); + return $items; + } + return []; + } + +} diff --git a/core/modules/field/tests/src/Kernel/FieldComputedTest.php b/core/modules/field/tests/src/Kernel/FieldComputedTest.php new file mode 100644 index 0000000000..703a4da071 --- /dev/null +++ b/core/modules/field/tests/src/Kernel/FieldComputedTest.php @@ -0,0 +1,159 @@ +getRequestTime(); + $value = $this->entities[0]->get('valid_computed_timestamp')->getValue(); + $this->assertEquals([0 => ['value' => $request_time]], $value); + } + + /** + * Test a valid computed entityreference field. + */ + public function testValidComputedEntityReference() { + /** @var \Drupal\Core\Entity\EntityInterface $referenced_entity */ + $referenced_entity = $this->entities[0]->get('valid_computed_entity_reference')->entity; + $this->assertInstanceOf(EntityTest::class, $referenced_entity); + $this->assertEquals($this->entities[1]->id(), $referenced_entity->id()); + } + + /** + * Test that a non existing entity reference returns NULL. + */ + public function testNonValidComputedEntityReference() { + $referenced_entity = $this->entities[0]->get('non_valid_computed_entity_reference')->entity; + $this->assertNull($referenced_entity); + } + + /** + * Test that a non valid computed timestamp returns throws an exception. + */ + public function testNonValidComputedTimestamp() { + $this->setExpectedException(FieldException::class, 'This value should be a valid number.'); + $entities_data = [ + [ + 'type' => 'non_valid_computed_timestamp', + 'title' => 'Entity with a non valid computed timestamp', + ], + ]; + $this->createTestEntities($entities_data); + } + + /** + * {@inheritdoc} + */ + protected function setUp() { + parent::setUp(); + $this->installSchema('system', ['sequences', 'key_value']); + $this->installConfig(['field', 'system']); + $this->installEntitySchema('entity_test'); + $this->installEntitySchema('user'); + + $entities_data = $this->getTestDataForEntities($this->getName()); + $this->createTestEntities($entities_data); + } + + /** + * Get an array of test data for the creation of entities. + * + * @param string $method_name + * The name of the method to test. + * + * @return array + * Data for creation of test entities. + */ + protected function getTestDataForEntities($method_name) { + $data = []; + switch ($method_name) { + case 'testValidComputedTimestamp': + $data = [ + [ + 'type' => 'valid_computed_timestamp', + 'title' => 'Entity with valid computed timestamp', + ], + ]; + break; + + case 'testNonValidComputedEntityReference': + $data = [ + [ + 'type' => 'non_valid_computed_entity_reference', + 'title' => 'Entity A', + ], + [ + 'type' => 'non_valid_computed_entity_reference', + 'title' => 'Entity B', + ], + ]; + break; + + case 'testValidComputedEntityReference': + $data = [ + [ + 'type' => 'valid_computed_entity_reference', + 'title' => 'Entity A', + ], + [ + 'type' => 'valid_computed_entity_reference', + 'title' => 'Entity B', + ], + ]; + break; + } + return $data; + } + + /** + * Create some test entities based on an array of data. + * + * @param array $entities_data + * An array containing the data to create entities from. + */ + protected function createTestEntities(array $entities_data) { + foreach ($entities_data as $item) { + $entity = EntityTest::create([ + 'type' => $item['type'], + 'title' => $item['title'], + ]); + $entity->save(); + $this->entities[] = $entity; + } + } + +} diff --git a/core/modules/views/tests/src/Unit/Plugin/field/FieldTest.php b/core/modules/views/tests/src/Unit/Plugin/field/FieldTest.php index 2b929f3608..1f4bfa48fc 100644 --- a/core/modules/views/tests/src/Unit/Plugin/field/FieldTest.php +++ b/core/modules/views/tests/src/Unit/Plugin/field/FieldTest.php @@ -83,6 +83,13 @@ protected function setUp() { ->method('getDefaultFieldSettings') ->willReturn([]); + $typed_data_manager = $this->getMock('Drupal\Component\Plugin\PluginManagerInterface'); + // @todo: maybe use a reasonable argument + $typed_data_manager->expects($this->any()) + ->method('getDefinition') + ->with($this->anything()) + ->will($this->returnValue(['list_class' => '\Drupal\Core\Field\FieldItemList'])); + $this->languageManager = $this->getMock('Drupal\Core\Language\LanguageManagerInterface'); $this->renderer = $this->getMock('Drupal\Core\Render\RendererInterface'); @@ -94,6 +101,7 @@ protected function setUp() { $this->container = new ContainerBuilder(); $this->container->set('plugin.manager.field.field_type', $this->fieldTypePluginManager); + $this->container->set('typed_data_manager', $typed_data_manager); \Drupal::setContainer($this->container); } diff --git a/core/tests/Drupal/Tests/Core/Entity/BaseFieldDefinitionTest.php b/core/tests/Drupal/Tests/Core/Entity/BaseFieldDefinitionTest.php index 616f6ba0a3..1f2cab173c 100644 --- a/core/tests/Drupal/Tests/Core/Entity/BaseFieldDefinitionTest.php +++ b/core/tests/Drupal/Tests/Core/Entity/BaseFieldDefinitionTest.php @@ -64,8 +64,16 @@ protected function setUp() { ->with($this->fieldType) ->will($this->returnValue($this->fieldTypeDefinition['field_settings'])); + $typed_data_manager = $this->getMock('Drupal\Component\Plugin\PluginManagerInterface'); + // @todo: maybe use a reasonable argument + $typed_data_manager->expects($this->any()) + ->method('getDefinition') + ->with($this->anything()) + ->will($this->returnValue(['list_class' => '\Drupal\Core\Field\FieldItemList'])); + $container = new ContainerBuilder(); $container->set('plugin.manager.field.field_type', $field_type_manager); + $container->set('typed_data_manager', $typed_data_manager); \Drupal::setContainer($container); } diff --git a/core/tests/Drupal/Tests/Core/Entity/ContentEntityBaseUnitTest.php b/core/tests/Drupal/Tests/Core/Entity/ContentEntityBaseUnitTest.php index 541ec88e2a..5a511cde9d 100644 --- a/core/tests/Drupal/Tests/Core/Entity/ContentEntityBaseUnitTest.php +++ b/core/tests/Drupal/Tests/Core/Entity/ContentEntityBaseUnitTest.php @@ -472,9 +472,12 @@ public function testLabel() { * - Fields array for $fields. */ public function providerGet() { + $items = $this->getMockBuilder('Drupal\Core\Field\FieldItemList') + ->disableOriginalConstructor() + ->getMock(); return [ // Populated fields array. - ['result', 'field_name', 'langcode', ['field_name' => ['langcode' => 'result']]], + [$items, 'field_name', 'langcode', ['field_name' => ['langcode' => $items]]], // Incomplete fields array. ['getTranslatedField_result', 'field_name', 'langcode', ['field_name' => 'no_langcode']], // Empty fields array. diff --git a/core/tests/Drupal/Tests/Core/Entity/TypedData/EntityAdapterUnitTest.php b/core/tests/Drupal/Tests/Core/Entity/TypedData/EntityAdapterUnitTest.php index 953daac887..d5832d7fbd 100644 --- a/core/tests/Drupal/Tests/Core/Entity/TypedData/EntityAdapterUnitTest.php +++ b/core/tests/Drupal/Tests/Core/Entity/TypedData/EntityAdapterUnitTest.php @@ -141,8 +141,15 @@ protected function setUp() { $this->typedDataManager = $this->getMock(TypedDataManagerInterface::class); $this->typedDataManager->expects($this->any()) ->method('getDefinition') - ->with('entity') - ->will($this->returnValue(['class' => '\Drupal\Core\Entity\Plugin\DataType\EntityAdapter'])); + ->will($this->returnCallback(function($plugin_id){ + switch ($plugin_id) { + case 'entity': + return ['class' => '\Drupal\Core\Entity\Plugin\DataType\EntityAdapter']; + default: + // @todo: maybe use a reasonable argument value + return ['list_class' => '\Drupal\Core\Field\FieldItemList']; + } + })); $this->typedDataManager->expects($this->any()) ->method('getDefaultConstraints') ->willReturn([]);