/** * {@inheritdoc} */ public function filterPluginDefinitionsByContexts(array $contexts, array $definitions) { return array_filter($definitions, function ($plugin_definition) use($contexts) { // If this plugin doesn't need any context, it is available to use. if (!isset($plugin_definition['context'])) { return TRUE; } // Build an array of requirements out of the contexts specified by the // plugin definition. $requirements = array(); /** @var $plugin_context \Drupal\Core\Plugin\Context\ContextDefinitionInterface */ foreach ($plugin_definition['context'] as $context_id => $plugin_context) { $definition = $this->typedDataManager->getDefinition($plugin_context->getDataType()); $definition['type'] = $plugin_context->getDataType(); // If the plugin specifies additional constraints, add them to the // constraints defined by the plugin type. if ($plugin_constraints = $plugin_context->getConstraints()) { // Ensure the array exists before adding in constraints. if (!isset($definition['constraints'])) { $definition['constraints'] = array(); } $definition['constraints'] += $plugin_constraints; } // Assume the requirement is required if unspecified. if (!isset($definition['required'])) { $definition['required'] = TRUE; } // @todo Use context definition objects after // https://drupal.org/node/2281635. $requirements[$context_id] = new DataDefinition($definition); } // Check the set of contexts against the requirements. return $this->checkRequirements($contexts, $requirements); }); }
/** * Tests the ComplexData validation constraint validator. * * For testing a map including a constraint on one of its keys is defined. */ public function testValidation() { // Create a definition that specifies some ComplexData constraint. $definition = MapDataDefinition::create()->setPropertyDefinition('key', DataDefinition::create('integer'))->addConstraint('ComplexData', array('key' => array('AllowedValues' => array(1, 2, 3)))); // Test the validation. $typed_data = $this->typedData->create($definition, array('key' => 1)); $violations = $typed_data->validate(); $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.'); // Test the validation when an invalid value is passed. $typed_data = $this->typedData->create($definition, array('key' => 4)); $violations = $typed_data->validate(); $this->assertEqual($violations->count(), 1, 'Validation failed for incorrect value.'); // Make sure the information provided by a violation is correct. $violation = $violations[0]; $this->assertEqual($violation->getMessage(), t('The value you selected is not a valid choice.'), 'The message for invalid value is correct.'); $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.'); $this->assertEqual($violation->getInvalidValue(), 4, 'The invalid value is set correctly in the violation.'); // Test using the constraint with a map without the specified key. This // should be ignored as long as there is no NotNull or NotBlank constraint. $typed_data = $this->typedData->create($definition, array('foo' => 'bar')); $violations = $typed_data->validate(); $this->assertEqual($violations->count(), 0, 'Constraint on non-existing key is ignored.'); $definition = MapDataDefinition::create()->setPropertyDefinition('key', DataDefinition::create('integer'))->addConstraint('ComplexData', array('key' => array('NotNull' => array()))); $typed_data = $this->typedData->create($definition, array('foo' => 'bar')); $violations = $typed_data->validate(); $this->assertEqual($violations->count(), 1, 'Key is required.'); }
/** * Tests deriving metadata from data references. */ public function testDataReferences() { $language_reference_definition = DataReferenceDefinition::create('language'); $this->assertTrue($language_reference_definition instanceof DataReferenceDefinitionInterface); // Test retrieving metadata about the referenced data. $this->assertEqual($language_reference_definition->getTargetDefinition()->getDataType(), 'language'); // Test using the definition factory. $language_reference_definition2 = $this->typedDataManager->createDataDefinition('language_reference'); $this->assertTrue($language_reference_definition2 instanceof DataReferenceDefinitionInterface); $this->assertEqual($language_reference_definition, $language_reference_definition2); }
/** * {@inheritdoc} */ public function setUp() { parent::setUp(); $mock_data_definition = $this->getMock('Drupal\\Core\\TypedData\\DataDefinitionInterface'); $this->contextDefinition = $this->getMockBuilder('Drupal\\Core\\Plugin\\Context\\ContextDefinitionInterface')->setMethods(array('getDefaultValue', 'getDataDefinition'))->getMockForAbstractClass(); $this->contextDefinition->expects($this->once())->method('getDefaultValue')->willReturn('test'); $this->contextDefinition->expects($this->once())->method('getDataDefinition')->willReturn($mock_data_definition); $this->typedData = $this->getMock('Drupal\\Core\\TypedData\\TypedDataInterface'); $this->typedDataManager = $this->getMockBuilder('Drupal\\Core\\TypedData\\TypedDataManager')->disableOriginalConstructor()->setMethods(array('create'))->getMock(); $this->typedDataManager->expects($this->once())->method('create')->with($mock_data_definition, 'test')->willReturn($this->typedData); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->typedDataManager = $this->prophesize(TypedDataManager::class); $container = new ContainerBuilder(); $container->set('string_translation', $this->getStringTranslationStub()); $container->set('typed_data_manager', $this->typedDataManager->reveal()); \Drupal::setContainer($container); $this->page = $this->prophesize(PageInterface::class); $this->event = new PageManagerContextEvent($this->page->reveal()); }
/** * {@inheritdoc} */ protected function setUp() { parent::setUp(); $this->typedDataManager = $this->prophesize(TypedDataManager::class); $container = new ContainerBuilder(); $container->set('string_translation', $this->getStringTranslationStub()); $container->set('typed_data_manager', $this->typedDataManager->reveal()); \Drupal::setContainer($container); $this->executable = $this->getMockBuilder(PageExecutable::class)->disableOriginalConstructor()->setMethods(['getPage', 'addContext'])->getMock(); $this->event = new PageManagerContextEvent($this->executable); }
/** * @covers ::getContextValues */ public function testGetContextValuesContext() { $data_definition = DataDefinition::createFromDataType('integer'); $typed_data = IntegerData::createInstance($data_definition); $this->typedDataManager->createDataDefinition('integer')->willReturn($data_definition); $this->typedDataManager->getDefaultConstraints($data_definition)->willReturn([]); $this->typedDataManager->create($data_definition, 5)->willReturn($typed_data); $input = ['foo' => ['label' => 'Foo', 'type' => 'integer', 'value' => 5]]; $expected = new Context(new ContextDefinition('integer', 'Foo'), 5); $actual = $this->staticContext->getContextValues($input)['foo']; $this->assertEquals($expected, $actual); }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $cached_values = $form_state->getTemporaryValue('wizard'); $this->machine_name = $cached_values['id']; $form['#attached']['library'][] = 'core/drupal.dialog.ajax'; $options = []; foreach ($this->typedDataManager->getDefinitions() as $plugin_id => $definition) { $options[$plugin_id] = (string) $definition['label']; } $form['items'] = array('#type' => 'markup', '#prefix' => '<div id="configured-contexts">', '#suffix' => '</div>', '#theme' => 'table', '#header' => array($this->t('Information'), $this->t('Description'), $this->t('Operations')), '#rows' => $this->renderContexts($cached_values), '#empty' => t('No required contexts have been configured.')); $form['contexts'] = ['#type' => 'select', '#options' => $options]; $form['add'] = ['#type' => 'submit', '#name' => 'add', '#value' => t('Add required context'), '#ajax' => ['callback' => [$this, 'add'], 'event' => 'click'], '#submit' => ['callback' => [$this, 'submitform']]]; return $form; }
/** * Tests the clearCachedFieldDefinitions() method. * * @covers ::clearCachedFieldDefinitions() */ public function testClearCachedFieldDefinitions() { $this->setUpEntityManager(); $this->cache->expects($this->once())->method('deleteTags')->with(array('entity_field_info' => TRUE)); $this->typedDataManager->expects($this->once())->method('clearCachedDefinitions'); $this->entityManager->clearCachedFieldDefinitions(); }
/** * Returns a typed data object. * * This helper for quick creation of typed data objects. * * @param string $data_type * The data type to create an object for. * @param mixed[] $value * The value to set. * * @return \Drupal\Core\TypedData\TypedDataInterface * The created object. */ protected function getTypedData($data_type, $value) { $definition = $this->typedDataManager->createDataDefinition($data_type); $data = $this->typedDataManager->create($definition); $data->setValue($value); return $data; }
/** * Tests required validation. * * @covers ::validate * @covers ::isValidationRequired * @covers ::setValidationRequired * @covers ::save * @covers ::preSave * * @expectedException \LogicException * @expectedExceptionMessage Entity validation was skipped. */ public function testRequiredValidation() { $validator = $this->getMock('\\Symfony\\Component\\Validator\\ValidatorInterface'); /** @var \Symfony\Component\Validator\ConstraintViolationList|\PHPUnit_Framework_MockObject_MockObject $empty_violation_list */ $empty_violation_list = $this->getMockBuilder('\\Symfony\\Component\\Validator\\ConstraintViolationList')->setMethods(NULL)->getMock(); $validator->expects($this->at(0))->method('validate')->with($this->entity->getTypedData())->will($this->returnValue($empty_violation_list)); $this->typedDataManager->expects($this->any())->method('getValidator')->will($this->returnValue($validator)); /** @var \Drupal\Core\Entity\EntityStorageInterface|\PHPUnit_Framework_MockObject_MockObject $storage */ $storage = $this->getMock('\\Drupal\\Core\\Entity\\EntityStorageInterface'); $storage->expects($this->any())->method('save')->willReturnCallback(function (ContentEntityInterface $entity) use($storage) { $entity->preSave($storage); }); $this->entityManager->expects($this->any())->method('getStorage')->with($this->entityTypeId)->will($this->returnValue($storage)); // Check that entities can be saved normally when validation is not // required. $this->assertFalse($this->entity->isValidationRequired()); $this->entity->save(); // Make validation required and check that if the entity is validated, it // can be saved normally. $this->entity->setValidationRequired(TRUE); $this->assertTrue($this->entity->isValidationRequired()); $this->entity->validate(); $this->entity->save(); // Check that the "validated" status is reset after saving the entity and // that trying to save a non-validated entity when validation is required // results in an exception. $this->assertTrue($this->entity->isValidationRequired()); $this->entity->save(); }
/** * Tests the AllowedValues validation constraint validator. * * For testing we define an integer with a set of allowed values. */ public function testValidation() { // Create a definition that specifies some AllowedValues. $definition = DataDefinition::create('integer')->addConstraint('AllowedValues', array(1, 2, 3)); // Test the validation. $typed_data = $this->typedData->create($definition, 1); $violations = $typed_data->validate(); $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.'); // Test the validation when an invalid value is passed. $typed_data = $this->typedData->create($definition, 4); $violations = $typed_data->validate(); $this->assertEqual($violations->count(), 1, 'Validation failed for incorrect value.'); // Make sure the information provided by a violation is correct. $violation = $violations[0]; $this->assertEqual($violation->getMessage(), t('The value you selected is not a valid choice.'), 'The message for invalid value is correct.'); $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.'); $this->assertEqual($violation->getInvalidValue(), 4, 'The invalid value is set correctly in the violation.'); }
/** * Set up mocks for the getDefaultValue() method call. * * @param mixed $default_value * The default value to assign to the mock context definition. */ protected function setUpDefaultValue($default_value = NULL) { $mock_data_definition = $this->getMock('Drupal\\Core\\TypedData\\DataDefinitionInterface'); $this->contextDefinition = $this->getMockBuilder('Drupal\\Core\\Plugin\\Context\\ContextDefinitionInterface')->setMethods(array('getDefaultValue', 'getDataDefinition'))->getMockForAbstractClass(); $this->contextDefinition->expects($this->once())->method('getDefaultValue')->willReturn($default_value); $this->contextDefinition->expects($this->once())->method('getDataDefinition')->willReturn($mock_data_definition); $this->typedData = $this->getMock('Drupal\\Core\\TypedData\\TypedDataInterface'); $this->typedDataManager->expects($this->once())->method('create')->with($mock_data_definition, $default_value)->willReturn($this->typedData); }
/** * Executes the BundleConstraintValidator test for a given bundle. * * @param string|array $bundle * Bundle/bundles to use as constraint option. */ protected function assertValidation($bundle) { // Create a typed data definition with a Bundle constraint. $definition = DataDefinition::create('entity_reference')->addConstraint('Bundle', $bundle); // Test the validation. $node = $this->container->get('entity.manager')->getStorage('node')->create(array('type' => 'foo')); $typed_data = $this->typedData->create($definition, $node); $violations = $typed_data->validate(); $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.'); // Test the validation when an invalid value is passed. $page_node = $this->container->get('entity.manager')->getStorage('node')->create(array('type' => 'baz')); $typed_data = $this->typedData->create($definition, $page_node); $violations = $typed_data->validate(); $this->assertEqual($violations->count(), 1, 'Validation failed for incorrect value.'); // Make sure the information provided by a violation is correct. $violation = $violations[0]; $this->assertEqual($violation->getMessage(), t('The entity must be of bundle %bundle.', array('%bundle' => implode(', ', (array) $bundle))), 'The message for invalid value is correct.'); $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.'); $this->assertEqual($violation->getInvalidValue(), $page_node, 'The invalid value is set correctly in the violation.'); }
/** * Tests deriving metadata from entity references. */ public function testEntityReferences() { $reference_definition = DataReferenceDefinition::create('entity'); $this->assertTrue($reference_definition instanceof DataReferenceDefinitionInterface); // Test retrieving metadata about the referenced data. $this->assertEqual($reference_definition->getTargetDefinition()->getDataType(), 'entity'); $this->assertTrue($reference_definition->getTargetDefinition() instanceof EntityDataDefinitionInterface); // Test that the definition factory creates the right definition object. $reference_definition2 = $this->typedDataManager->createDataDefinition('entity_reference'); $this->assertTrue($reference_definition2 instanceof DataReferenceDefinitionInterface); $this->assertEqual($reference_definition2, $reference_definition); }
/** * Tests the EntityTypeConstraintValidator. */ public function testValidation() { // Create a typed data definition with an EntityType constraint. $entity_type = 'node'; $definition = DataDefinition::create('entity_reference')->setConstraints(array('EntityType' => $entity_type)); // Test the validation. $node = $this->container->get('entity.manager')->getStorage('node')->create(array('type' => 'page')); $typed_data = $this->typedData->create($definition, $node); $violations = $typed_data->validate(); $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.'); // Test the validation when an invalid value (in this case a user entity) // is passed. $account = $this->createUser(); $typed_data = $this->typedData->create($definition, $account); $violations = $typed_data->validate(); $this->assertEqual($violations->count(), 1, 'Validation failed for incorrect value.'); // Make sure the information provided by a violation is correct. $violation = $violations[0]; $this->assertEqual($violation->getMessage(), t('The entity must be of type %type.', array('%type' => $entity_type)), 'The message for invalid value is correct.'); $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.'); $this->assertEqual($violation->getInvalidValue(), $account, 'The invalid value is set correctly in the violation.'); }
/** * @covers ::validate */ public function testValidate() { $validator = $this->getMock('\\Symfony\\Component\\Validator\\ValidatorInterface'); /** @var \Symfony\Component\Validator\ConstraintViolationList|\PHPUnit_Framework_MockObject_MockObject $empty_violation_list */ $empty_violation_list = $this->getMockBuilder('\\Symfony\\Component\\Validator\\ConstraintViolationList')->setMethods(NULL)->getMock(); $non_empty_violation_list = clone $empty_violation_list; $violation = $this->getMock('\\Symfony\\Component\\Validator\\ConstraintViolationInterface'); $non_empty_violation_list->add($violation); $validator->expects($this->at(0))->method('validate')->with($this->entity->getTypedData())->will($this->returnValue($empty_violation_list)); $validator->expects($this->at(1))->method('validate')->with($this->entity->getTypedData())->will($this->returnValue($non_empty_violation_list)); $this->typedDataManager->expects($this->exactly(2))->method('getValidator')->will($this->returnValue($validator)); $this->assertSame(0, count($this->entity->validate())); $this->assertSame(1, count($this->entity->validate())); }
/** * Tests the ValidReferenceConstraintValidator. */ public function testValidation() { // Create a test entity to be referenced. $entity = $this->createUser(); // By default entity references already have the ValidReference constraint. $definition = BaseFieldDefinition::create('entity_reference')->setSettings(array('target_type' => 'user')); $typed_data = $this->typedData->create($definition, array('target_id' => $entity->id())); $violations = $typed_data->validate(); $this->assertFalse($violations->count(), 'Validation passed for correct value.'); // NULL is also considered a valid reference. $typed_data = $this->typedData->create($definition, array('target_id' => NULL)); $violations = $typed_data->validate(); $this->assertFalse($violations->count(), 'Validation passed for correct value.'); $typed_data = $this->typedData->create($definition, array('target_id' => $entity->id())); // Delete the referenced entity. $entity->delete(); $violations = $typed_data->validate(); $this->assertTrue($violations->count(), 'Validation failed for incorrect value.'); // Make sure the information provided by a violation is correct. $violation = $violations[0]; $this->assertEqual($violation->getMessage(), t('The referenced entity (%type: %id) does not exist.', array('%type' => 'user', '%id' => $entity->id())), 'The message for invalid value is correct.'); $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.'); }
/** * @covers ::filterPluginDefinitionsByContexts * * @dataProvider providerTestFilterPluginDefinitionsByContexts */ public function testFilterPluginDefinitionsByContexts($has_context, $definitions, $expected, $typed_data_definition = NULL) { if ($has_context) { $context = $this->getMock('Drupal\\Core\\Plugin\\Context\\ContextInterface'); $expected_context_definition = (new ContextDefinition('expected_data_type'))->setConstraints(array('expected_constraint_name' => 'expected_constraint_value')); $context->expects($this->atLeastOnce())->method('getContextDefinition')->will($this->returnValue($expected_context_definition)); $contexts = array($context); } else { $contexts = array(); } if ($typed_data_definition) { $this->typedDataManager->expects($this->atLeastOnce())->method('getDefinition')->will($this->returnValueMap($typed_data_definition)); } $this->assertSame($expected, $this->contextHandler->filterPluginDefinitionsByContexts($contexts, $definitions)); }
/** * Setups a typed data object used for test purposes. * * @param array $tree * An array of value, constraints and properties. * * @return \Drupal\Core\TypedData\TypedDataInterface|\PHPUnit_Framework_MockObject_MockObject */ protected function setupTypedData(array $tree, $name = '') { $callback = function ($value, ExecutionContextInterface $context) { $context->addViolation('violation: ' . (is_array($value) ? count($value) : $value)); }; $tree += ['constraints' => []]; if (isset($tree['properties'])) { $map_data_definition = MapDataDefinition::create(); $map_data_definition->addConstraint('Callback', ['callback' => $callback]); foreach ($tree['properties'] as $property_name => $property) { $sub_typed_data = $this->setupTypedData($property, $property_name); $map_data_definition->setPropertyDefinition($property_name, $sub_typed_data->getDataDefinition()); } $typed_data = $this->typedDataManager->create($map_data_definition, $tree['value'], $name); } else { /** @var \Drupal\Core\TypedData\TypedDataInterface $typed_data */ $typed_data = $this->typedDataManager->create(DataDefinition::create('string')->addConstraint('Callback', ['callback' => $callback]), $tree['value'], $name); } return $typed_data; }
/** * {@inheritdoc} */ public function build() { // Create a temporary node object to which our fake field value can be // added. $node = Node::create(array('type' => '_entity_embed')); $definition = $this->getFieldDefinition(); /* @var \Drupal\Core\Field\FieldItemListInterface $items $items */ // Create a field item list object, 1 is the value, array('target_id' => 1) // would work too, or multiple values. 1 is passed down from the list to the // field item, which knows that an integer is the ID. $items = $this->typedDataManager->create($definition, $this->getFieldValue($definition), $definition->getName(), $node->getTypedData()); // Prepare, expects an array of items, keyed by parent entity ID. $formatter = $this->getFieldFormatter(); $formatter->prepareView(array($node->id() => $items)); $build = $formatter->viewElements($items, $this->getLangcode()); // For some reason $build[0]['#printed'] is TRUE, which means it will fail // to render later. So for now we manually fix that. // @todo Investigate why this is needed. show($build[0]); return $build[0]; }
/** * {@inheritdoc} */ protected function setUp() { $this->id = 1; $values = array('id' => $this->id, 'uuid' => '3bb9ee60-bea5-4622-b89b-a63319d10b3a', 'defaultLangcode' => array(LanguageInterface::LANGCODE_DEFAULT => 'en')); $this->entityTypeId = $this->randomMachineName(); $this->bundle = $this->randomMachineName(); $this->entityType = $this->getMock('\\Drupal\\Core\\Entity\\EntityTypeInterface'); $this->entityType->expects($this->any())->method('getKeys')->will($this->returnValue(array('id' => 'id', 'uuid' => 'uuid'))); $this->entityManager = $this->getMock('\\Drupal\\Core\\Entity\\EntityManagerInterface'); $this->entityManager->expects($this->any())->method('getDefinition')->with($this->entityTypeId)->will($this->returnValue($this->entityType)); $this->uuid = $this->getMock('\\Drupal\\Component\\Uuid\\UuidInterface'); $this->typedDataManager = $this->getMockBuilder('\\Drupal\\Core\\TypedData\\TypedDataManager')->disableOriginalConstructor()->getMock(); $this->typedDataManager->expects($this->any())->method('getDefinition')->with('entity')->will($this->returnValue(['class' => '\\Drupal\\Core\\Entity\\Plugin\\DataType\\EntityAdapter'])); $this->typedDataManager->expects($this->any())->method('getDefaultConstraints')->willReturn([]); $validation_constraint_manager = $this->getMockBuilder('\\Drupal\\Core\\Validation\\ConstraintManager')->disableOriginalConstructor()->getMock(); $validation_constraint_manager->expects($this->any())->method('create')->willReturn([]); $this->typedDataManager->expects($this->any())->method('getValidationConstraintManager')->willReturn($validation_constraint_manager); $not_specified = new Language(array('id' => LanguageInterface::LANGCODE_NOT_SPECIFIED, 'locked' => TRUE)); $this->languageManager = $this->getMock('\\Drupal\\Core\\Language\\LanguageManagerInterface'); $this->languageManager->expects($this->any())->method('getLanguages')->will($this->returnValue(array(LanguageInterface::LANGCODE_NOT_SPECIFIED => $not_specified))); $this->languageManager->expects($this->any())->method('getLanguage')->with(LanguageInterface::LANGCODE_NOT_SPECIFIED)->will($this->returnValue($not_specified)); $this->fieldTypePluginManager = $this->getMockBuilder('\\Drupal\\Core\\Field\\FieldTypePluginManager')->disableOriginalConstructor()->getMock(); $this->fieldTypePluginManager->expects($this->any())->method('getDefaultStorageSettings')->will($this->returnValue(array())); $this->fieldTypePluginManager->expects($this->any())->method('getDefaultFieldSettings')->will($this->returnValue(array())); $this->fieldItemList = $this->getMock('\\Drupal\\Core\\Field\\FieldItemListInterface'); $this->fieldTypePluginManager->expects($this->any())->method('createFieldItemList')->willReturn($this->fieldItemList); $container = new ContainerBuilder(); $container->set('entity.manager', $this->entityManager); $container->set('uuid', $this->uuid); $container->set('typed_data_manager', $this->typedDataManager); $container->set('language_manager', $this->languageManager); $container->set('plugin.manager.field.field_type', $this->fieldTypePluginManager); \Drupal::setContainer($container); $this->fieldDefinitions = array('id' => BaseFieldDefinition::create('integer'), 'revision_id' => BaseFieldDefinition::create('integer')); $this->entityManager->expects($this->any())->method('getFieldDefinitions')->with($this->entityTypeId, $this->bundle)->will($this->returnValue($this->fieldDefinitions)); $this->entity = $this->getMockForAbstractClass('\\Drupal\\Core\\Entity\\ContentEntityBase', array($values, $this->entityTypeId, $this->bundle)); $this->entityAdapter = EntityAdapter::createFromEntity($this->entity); }
/** * Tests typed data validation. */ public function testTypedDataValidation() { $definition = DataDefinition::create('integer')->setConstraints(array('Range' => array('min' => 5))); $violations = $this->typedDataManager->create($definition, 10)->validate(); $this->assertEqual($violations->count(), 0); $integer = $this->typedDataManager->create($definition, 1); $violations = $integer->validate(); $this->assertEqual($violations->count(), 1); // Test translating violation messages. $message = t('This value should be %limit or more.', array('%limit' => 5)); $this->assertEqual($violations[0]->getMessage(), $message, 'Translated violation message retrieved.'); $this->assertEqual($violations[0]->getPropertyPath(), ''); $this->assertIdentical($violations[0]->getRoot(), $integer, 'Root object returned.'); // Test translating violation messages when pluralization is used. $definition = DataDefinition::create('string')->setConstraints(array('Length' => array('min' => 10))); $violations = $this->typedDataManager->create($definition, "short")->validate(); $this->assertEqual($violations->count(), 1); $message = t('This value is too short. It should have %limit characters or more.', array('%limit' => 10)); $this->assertEqual($violations[0]->getMessage(), $message, 'Translated violation message retrieved.'); // Test having multiple violations. $definition = DataDefinition::create('integer')->setConstraints(array('Range' => array('min' => 5), 'Null' => array())); $violations = $this->typedDataManager->create($definition, 10)->validate(); $this->assertEqual($violations->count(), 1); $violations = $this->typedDataManager->create($definition, 1)->validate(); $this->assertEqual($violations->count(), 2); // Test validating property containers and make sure the NotNull and Null // constraints work with typed data containers. $definition = BaseFieldDefinition::create('integer')->setConstraints(array('NotNull' => array())); $field_item = $this->typedDataManager->create($definition, array('value' => 10)); $violations = $field_item->validate(); $this->assertEqual($violations->count(), 0); $field_item = $this->typedDataManager->create($definition, array('value' => 'no integer')); $violations = $field_item->validate(); $this->assertEqual($violations->count(), 1); $this->assertEqual($violations[0]->getPropertyPath(), '0.value'); // Test that the field item may not be empty. $field_item = $this->typedDataManager->create($definition); $violations = $field_item->validate(); $this->assertEqual($violations->count(), 1); // Test the Null constraint with typed data containers. $definition = BaseFieldDefinition::create('float')->setConstraints(array('Null' => array())); $field_item = $this->typedDataManager->create($definition, array('value' => 11.5)); $violations = $field_item->validate(); $this->assertEqual($violations->count(), 1); $field_item = $this->typedDataManager->create($definition); $violations = $field_item->validate(); $this->assertEqual($violations->count(), 0); // Test getting constraint definitions by type. $definitions = $this->typedDataManager->getValidationConstraintManager()->getDefinitionsByType('entity'); $this->assertTrue(isset($definitions['EntityType']), 'Constraint plugin found for type entity.'); $this->assertTrue(isset($definitions['Null']), 'Constraint plugin found for type entity.'); $this->assertTrue(isset($definitions['NotNull']), 'Constraint plugin found for type entity.'); $definitions = $this->typedDataManager->getValidationConstraintManager()->getDefinitionsByType('string'); $this->assertFalse(isset($definitions['EntityType']), 'Constraint plugin not found for type string.'); $this->assertTrue(isset($definitions['Null']), 'Constraint plugin found for type string.'); $this->assertTrue(isset($definitions['NotNull']), 'Constraint plugin found for type string.'); // Test automatic 'required' validation. $definition = DataDefinition::create('integer')->setRequired(TRUE); $violations = $this->typedDataManager->create($definition)->validate(); $this->assertEqual($violations->count(), 1); $violations = $this->typedDataManager->create($definition, 0)->validate(); $this->assertEqual($violations->count(), 0); // Test validating a list of a values and make sure property paths starting // with "0" are created. $definition = BaseFieldDefinition::create('integer'); $violations = $this->typedDataManager->create($definition, array(array('value' => 10)))->validate(); $this->assertEqual($violations->count(), 0); $violations = $this->typedDataManager->create($definition, array(array('value' => 'string')))->validate(); $this->assertEqual($violations->count(), 1); $this->assertEqual($violations[0]->getInvalidValue(), 'string'); $this->assertIdentical($violations[0]->getPropertyPath(), '0.value'); }
/** * {@inheritdoc} */ public function clearCachedBundles() { $this->bundleInfo = array(); Cache::invalidateTags(array('entity_bundles')); // Entity bundles are exposed as data types, clear that cache too. $this->typedDataManager->clearCachedDefinitions(); }
/** * {@inheritdoc} */ public function clearCachedDefinitions() { $this->schemaStorage->reset(); parent::clearCachedDefinitions(); }
/** * Extracts the value of the property from the given container. * * @param mixed $container The container to extract the property value from. * * @return mixed The value of the property. */ public function getPropertyValue($container) { return $this->typedDataManager->getCanonicalRepresentation($this->typedData); }
/** * {@inheritdoc} */ public function createFieldItem(FieldItemListInterface $items, $index, $values = NULL) { // Leverage prototyping of the Typed Data API for fast instantiation. return $this->typedDataManager->getPropertyInstance($items, $index, $values); }
/** * Tests the getAllBundleInfo() method. * * @covers ::getAllBundleInfo */ public function testGetAllBundleInfo() { $this->moduleHandler->invokeAll('entity_bundle_info')->willReturn([]); $this->moduleHandler->alter('entity_bundle_info', Argument::type('array'))->willReturn(NULL); $apple = $this->prophesize(EntityTypeInterface::class); $apple->getLabel()->willReturn('Apple'); $apple->getBundleOf()->willReturn(NULL); $banana = $this->prophesize(EntityTypeInterface::class); $banana->getLabel()->willReturn('Banana'); $banana->getBundleOf()->willReturn(NULL); $this->setUpEntityManager(array('apple' => $apple, 'banana' => $banana)); $this->cacheBackend->get('entity_bundle_info:en')->willReturn(FALSE); $this->cacheBackend->get('entity_type')->willReturn(FALSE); $this->cacheBackend->set('entity_type', Argument::any(), Cache::PERMANENT, ['entity_types'])->shouldBeCalled(); $this->cacheBackend->set('entity_bundle_info:en', Argument::any(), Cache::PERMANENT, ['entity_types', 'entity_bundles'])->will(function () { $this->get('entity_bundle_info:en')->willReturn((object) ['data' => 'cached data'])->shouldBeCalled(); })->shouldBeCalled(); $this->cacheTagsInvalidator->invalidateTags(['entity_types'])->shouldBeCalled(); $this->cacheTagsInvalidator->invalidateTags(['entity_bundles'])->shouldBeCalled(); $this->cacheTagsInvalidator->invalidateTags(['entity_field_info'])->shouldBeCalled(); $this->typedDataManager->clearCachedDefinitions()->shouldBeCalled(); $expected = array('apple' => array('apple' => array('label' => 'Apple')), 'banana' => array('banana' => array('label' => 'Banana'))); $bundle_info = $this->entityManager->getAllBundleInfo(); $this->assertSame($expected, $bundle_info); $bundle_info = $this->entityManager->getAllBundleInfo(); $this->assertSame($expected, $bundle_info); $this->entityManager->clearCachedDefinitions(); $bundle_info = $this->entityManager->getAllBundleInfo(); $this->assertSame('cached data', $bundle_info); }
/** * {@inheritdoc} */ public function createInstance($data_type, array $configuration = array()) { $instance = parent::createInstance($data_type, $configuration); // Enable elements to construct their own definitions using the typed config // manager. if ($instance instanceof ArrayElement) { $instance->setTypedConfig($this); } return $instance; }
/** * {@inheritdoc} */ protected function alterDefinitions(&$definitions) { $discovered_schema = array_keys($definitions); parent::alterDefinitions($definitions); $altered_schema = array_keys($definitions); if ($discovered_schema != $altered_schema) { $added_keys = implode(',', array_diff($altered_schema, $discovered_schema)); $removed_keys = implode(',', array_diff($discovered_schema, $altered_schema)); if (!empty($added_keys) && !empty($removed_keys)) { $message = "Invoking hook_config_schema_info_alter() has added ({$added_keys}) and removed ({$removed_keys}) schema definitions"; } elseif (!empty($added_keys)) { $message = "Invoking hook_config_schema_info_alter() has added ({$added_keys}) schema definitions"; } else { $message = "Invoking hook_config_schema_info_alter() has removed ({$removed_keys}) schema definitions"; } throw new ConfigSchemaAlterException($message); } }