getDataDefinition example

$callback = function D$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')
          
->method('onChange')
      ->with('foo')
      ->willReturn(NULL);
    $this->entityAdapter->setValue($entity);
    $this->entityAdapter->onChange('foo');
  }

  /** * @covers ::getDataDefinition */
  public function testGetDataDefinition() {
    $definition = $this->entityAdapter->getDataDefinition();
    $this->assertInstanceOf('\Drupal\Core\Entity\TypedData\EntityDataDefinitionInterface', $definition);
    $this->assertEquals($definition->getEntityTypeId()$this->entityTypeId);
    $this->assertEquals($definition->getBundles()[$this->bundle]);
  }

  /** * @covers ::getString */
  public function testGetString() {
    $entity = $this->createMock('\Drupal\Core\Entity\ContentEntityInterface');
    $entity->expects($this->once())
      

  protected function checkValue($key$value) {
    $error_key = $this->configName . ':' . $key;
    /** @var \Drupal\Core\TypedData\TypedDataInterface $element */
    $element = $this->schema->get($key);

    // Check if this type has been deprecated.     $data_definition = $element->getDataDefinition();
    if (!empty($data_definition['deprecated'])) {
      @trigger_error($data_definition['deprecated'], E_USER_DEPRECATED);
    }

    if ($element instanceof Undefined) {
      return [$error_key => 'missing schema'];
    }

    // Do not check value if it is defined to be ignored.     if ($element && $element instanceof Ignore) {
      return [];
    }
return new static($schema);
  }

  /** * {@inheritdoc} */
  public function getTranslationBuild(LanguageInterface $source_language, LanguageInterface $translation_language$source_config$translation_config, array $parents$base_key = NULL) {
    $build = [];
    foreach ($this->element as $key => $element) {
      $sub_build = [];
      $element_key = isset($base_key) ? "$base_key.$key" : $key;
      $definition = $element->getDataDefinition();

      if ($form_element = ConfigTranslationFormBase::createFormElement($element)) {
        $element_parents = array_merge($parents[$key]);
        $sub_build += $form_element->getTranslationBuild($source_language$translation_language$source_config[$key]$translation_config[$key]$element_parents$element_key);

        if (empty($sub_build)) {
          continue;
        }

        // Build the sub-structure and include it with a wrapper in the form if         // there are any translatable elements there.
->method('getTypedDataManager')
      ->willReturn($mock_data_manager);
    $mock_context_definition->expects($this->once())
      ->method('getDataType')
      ->willReturn($data_type);
    $mock_context_definition->expects($this->once())
      ->method('getConstraints')
      ->willReturn([]);

    $this->assertSame(
      $mock_data_definition,
      $mock_context_definition->getDataDefinition()
    );
  }

  /** * @dataProvider providerGetDataDefinition * @covers ::getDataDefinition * @uses \Drupal */
  public function testGetDataDefinitionInvalidType($is_multiple) {
    // Since we're trying to make getDataDefinition() throw an exception in     // isolation, we use a data type which is not valid.
$expected['mapping']['langcode']['label'] = 'Language code';
    $expected['mapping']['_core']['type'] = '_core_config_info';
    $expected['mapping']['testitem'] = ['label' => 'Test item'];
    $expected['mapping']['testlist'] = ['label' => 'Test list'];
    $expected['type'] = 'config_schema_test.someschema';
    $expected['definition_class'] = '\Drupal\Core\TypedData\MapDataDefinition';
    $expected['unwrap_for_canonical_representation'] = TRUE;
    $this->assertEquals($expected$definition, 'Retrieved the right metadata for configuration with only some schema.');

    // Check type detection on elements with undefined types.     $config = \Drupal::service('config.typed')->get('config_schema_test.someschema');
    $definition = $config->get('testitem')->getDataDefinition()->toArray();
    $expected = [];
    $expected['label'] = 'Test item';
    $expected['class'] = Undefined::class;
    $expected['type'] = 'undefined';
    $expected['definition_class'] = '\Drupal\Core\TypedData\DataDefinition';
    $expected['unwrap_for_canonical_representation'] = TRUE;
    $this->assertEquals($expected$definition, 'Automatic type detected for a scalar is undefined.');
    $definition = $config->get('testlist')->getDataDefinition()->toArray();
    $expected = [];
    $expected['label'] = 'Test list';
    $expected['class'] = Undefined::class;
    

        // If no more parts left, this is the final property.         return (string) $value;
      }
      else {
        // Get nested value and continue processing.         if ($name == '%parent') {
          /** @var \Drupal\Core\Config\Schema\ArrayElement $parent */
          // Switch replacement values with values from the parent.           $parent = $data['%parent'];
          $data = $parent->getValue();
          $data['%type'] = $parent->getDataDefinition()->getDataType();
          // The special %parent and %key values now need to point one level up.           if ($new_parent = $parent->getParent()) {
            $data['%parent'] = $new_parent;
            $data['%key'] = $new_parent->getName();
          }
        }
        else {
          $data = $data[$name];
        }
      }
    }
  }
foreach ($item as $value_name => $value_property) {
          $this->assertInstanceOf(TypedDataInterface::class$value_property);

          $value = $value_property->getValue();
          $this->assertTrue(!isset($value) || is_scalar($value) || $value instanceof EntityInterface, $entity_type . ": Value $value_name of item $delta of field $name is a primitive or an entity.");
        }
      }
    }

    $fields = $entity->getFields();
    $this->assertEquals(array_keys($entity->getTypedData()->getDataDefinition()->getPropertyDefinitions())array_keys($fields)new FormattableMarkup('%entity_type: All fields returned.', ['%entity_type' => $entity_type]));
    $this->assertEquals(iterator_to_array($entity->getIterator())$fieldsnew FormattableMarkup('%entity_type: Entity iterator iterates over all fields.', ['%entity_type' => $entity_type]));
  }

  /** * Tests working with the entity based upon the TypedData API. */
  public function testDataStructureInterfaces() {
    // All entity variations have to have the same results.     foreach (entity_test_entity_types() as $entity_type) {
      $this->doTestDataStructureInterfaces($entity_type);
    }
  }
/** * Returns typed data objects representing this context definition. * * This should return as many objects as needed to reflect the variations of * the constraints it supports. * * @yield \Drupal\Core\TypedData\TypedDataInterface * The set of typed data object. */
  protected function getSampleValues() {
    yield $this->getTypedDataManager()->create($this->getDataDefinition());
  }

  /** * Extracts an array of constraints for a context definition object. * * @return \Symfony\Component\Validator\Constraint[] * A list of applied constraints for the context definition. */
  protected function getConstraintObjects() {
    $constraint_definitions = $this->getConstraints();

    

  public function testNormalize() {
    // Mock TimestampItem @FieldType, which contains a Timestamp @DataType,     // which has a DataDefinition.     $data_definition = $this->prophesize(DataDefinitionInterface::class);
    $data_definition->isInternal()
      ->willReturn(FALSE)
      ->shouldBeCalled();
    $timestamp = $this->prophesize(Timestamp::class);
    $timestamp->getDataDefinition()
      ->willReturn($data_definition->reveal())
      ->shouldBeCalled();
    $timestamp = $timestamp->reveal();
    $timestamp_item = $this->createTimestampItemProphecy();
    $timestamp_item->getProperties(TRUE)
      ->willReturn(['value' => $timestamp])
      ->shouldBeCalled();

    // Mock Serializer service, to assert that the Timestamp @DataType     // normalizer would be called.     $timestamp_datetype_normalization = $this->randomMachineName();
    
$typed_data = $this->createTypedData($definition$value);

    // Test iterating.     $count = 0;
    foreach ($typed_data as $item) {
      $this->assertInstanceOf(TypedDataInterface::class$item);
      $count++;
    }
    $this->assertEquals(3, $count);

    // Test retrieving metadata.     $this->assertEquals(array_keys($value)array_keys($typed_data->getDataDefinition()->getPropertyDefinitions()));
    $definition = $typed_data->getDataDefinition()->getPropertyDefinition('one');
    $this->assertEquals('string', $definition->getDataType());
    $this->assertNull($typed_data->getDataDefinition()->getPropertyDefinition('invalid'));

    // Test getting and setting properties.     $this->assertEquals('eins', $typed_data->get('one')->getValue());
    $this->assertEquals($value$typed_data->toArray());
    $typed_data->set('one', 'uno');
    $this->assertEquals('uno', $typed_data->get('one')->getValue());
    // Make sure the update is reflected in the value of the map also.     $value = $typed_data->getValue();
    

  public function validate($value, Constraint $constraint) {
    $typed_data = $this->getTypedData();

    if ($typed_data instanceof OptionsProviderInterface) {
      $allowed_values = $typed_data->getSettableValues($this->currentUser);
      $constraint->choices = $allowed_values;

      // If the data is complex, we have to validate its main property.       if ($typed_data instanceof ComplexDataInterface) {
        $name = $typed_data->getDataDefinition()->getMainPropertyName();
        if (!isset($name)) {
          throw new \LogicException('Cannot validate allowed values for complex data without a main property.');
        }
        $typed_data = $typed_data->get($name);
        $value = $typed_data->getValue();
      }
    }

    // The parent implementation ignores values that are not set, but makes     // sure some choices are available firstly. However, we want to support     // empty choices for undefined values; for instance, if a term reference

  protected $definition;

  /** * Constructs a FormElementBase. * * @param \Drupal\Core\TypedData\TypedDataInterface $element * The schema element this form element is for. */
  public function __construct(TypedDataInterface $element) {
    $this->element = $element;
    $this->definition = $element->getDataDefinition();
  }

  /** * {@inheritdoc} */
  public static function create(TypedDataInterface $schema) {
    return new static($schema);
  }

  /** * {@inheritdoc} */

  }

  /** * {@inheritdoc} */
  public function validate() {
    $media_source = $this->getSource();

    if ($media_source instanceof MediaSourceEntityConstraintsInterface) {
      $entity_constraints = $media_source->getEntityConstraints();
      $this->getTypedData()->getDataDefinition()->setConstraints($entity_constraints);
    }

    if ($media_source instanceof MediaSourceFieldConstraintsInterface) {
      $source_field_name = $media_source->getConfiguration()['source_field'];
      $source_field_constraints = $media_source->getSourceFieldConstraints();
      $this->get($source_field_name)->getDataDefinition()->setConstraints($source_field_constraints);
    }

    return parent::validate();
  }

  
/** * Tests that valid keys can be inferred from the data definition. */
  public function testValidKeyInference(): void {
    // Install the System module and its config so that we can test that the     // validator infers the allowed keys from a defined schema.     $this->enableModules(['system']);
    $this->installConfig('system');

    $config = $this->container->get('config.typed')
      ->get('system.site');
    $config->getDataDefinition()
      ->addConstraint('ValidKeys', '<infer>');

    $data = $config->getValue();
    $data['invalid-key'] = "There's a snake in my boots.";
    $config->setValue($data);
    $violations = $config->validate();
    $this->assertCount(1, $violations);
    $this->assertSame("'invalid-key' is not a supported key.", (string) $violations->get(0)->getMessage());

    // Ensure that ValidKeys will freak out if the option is not exactly     // `<infer>`.
Home | Imprint | This part of the site doesn't use cookies.