BundleConstraintValidatorTest.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace Drupal\KernelTests\Core\Entity;
  3. use Drupal\Core\TypedData\DataDefinition;
  4. use Drupal\KernelTests\KernelTestBase;
  5. /**
  6. * Tests validation constraints for BundleConstraintValidator.
  7. *
  8. * @group Entity
  9. */
  10. class BundleConstraintValidatorTest extends KernelTestBase {
  11. /**
  12. * The typed data manager to use.
  13. *
  14. * @var \Drupal\Core\TypedData\TypedDataManager
  15. */
  16. protected $typedData;
  17. public static $modules = ['node', 'field', 'text', 'user'];
  18. protected function setUp() {
  19. parent::setUp();
  20. $this->installEntitySchema('user');
  21. $this->typedData = $this->container->get('typed_data_manager');
  22. }
  23. /**
  24. * Tests bundle constraint validation.
  25. */
  26. public function testValidation() {
  27. // Test with multiple values.
  28. $this->assertValidation(['foo', 'bar']);
  29. // Test with a single string value as well.
  30. $this->assertValidation('foo');
  31. }
  32. /**
  33. * Executes the BundleConstraintValidator test for a given bundle.
  34. *
  35. * @param string|array $bundle
  36. * Bundle/bundles to use as constraint option.
  37. */
  38. protected function assertValidation($bundle) {
  39. // Create a typed data definition with a Bundle constraint.
  40. $definition = DataDefinition::create('entity_reference')
  41. ->addConstraint('Bundle', $bundle);
  42. // Test the validation.
  43. $node = $this->container->get('entity.manager')->getStorage('node')->create(['type' => 'foo']);
  44. $typed_data = $this->typedData->create($definition, $node);
  45. $violations = $typed_data->validate();
  46. $this->assertEqual($violations->count(), 0, 'Validation passed for correct value.');
  47. // Test the validation when an invalid value is passed.
  48. $page_node = $this->container->get('entity.manager')->getStorage('node')->create(['type' => 'baz']);
  49. $typed_data = $this->typedData->create($definition, $page_node);
  50. $violations = $typed_data->validate();
  51. $this->assertEqual($violations->count(), 1, 'Validation failed for incorrect value.');
  52. // Make sure the information provided by a violation is correct.
  53. $violation = $violations[0];
  54. $this->assertEqual($violation->getMessage(), t('The entity must be of bundle %bundle.', ['%bundle' => implode(', ', (array) $bundle)]), 'The message for invalid value is correct.');
  55. $this->assertEqual($violation->getRoot(), $typed_data, 'Violation root is correct.');
  56. $this->assertEqual($violation->getInvalidValue(), $page_node, 'The invalid value is set correctly in the violation.');
  57. }
  58. }