getTypedData example


  public function validate($value, Constraint $constraint) {

    if (!isset($value)) {
      return;
    }

    $typed_data = $this->getTypedData();
    $valid = TRUE;
    if ($typed_data instanceof BinaryInterface && !is_resource($value)) {
      $valid = FALSE;
    }
    if ($typed_data instanceof BooleanInterface && !(is_bool($value) || $value === 0 || $value === '0' || $value === 1 || $value == '1')) {
      $valid = FALSE;
    }
    if ($typed_data instanceof FloatInterface && filter_var($value, FILTER_VALIDATE_FLOAT) === FALSE) {
      $valid = FALSE;
    }
    if ($typed_data instanceof IntegerInterface && filter_var($value, FILTER_VALIDATE_INT) === FALSE) {
      

  public function createInstance($field_type, array $configuration = []) {
    $configuration['data_definition'] = $configuration['field_definition']->getItemDefinition();
    return $this->typedDataManager->createInstance("field_item:$field_type", $configuration);
  }

  /** * {@inheritdoc} */
  public function createFieldItemList(FieldableEntityInterface $entity$field_name$values = NULL) {
    // Leverage prototyping of the Typed Data API for fast instantiation.     return $this->typedDataManager->getPropertyInstance($entity->getTypedData()$field_name$values);
  }

  /** * {@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);
  }

  /** * {@inheritdoc} */
class NotNullConstraintValidator extends NotNullValidator {

  use TypedDataAwareValidatorTrait;

  /** * {@inheritdoc} * * phpcs:ignore Drupal.Commenting.FunctionComment.VoidReturn * @return void */
  public function validate($value, Constraint $constraint) {
    $typed_data = $this->getTypedData();
    if (($typed_data instanceof ListInterface || $typed_data instanceof ComplexDataInterface) && $typed_data->isEmpty()) {
      $value = NULL;
    }
    parent::validate($value$constraint);
  }

}
'#default_value' => $this->entity->isRequired(),
      '#weight' => -5,
    ];

    // Create an arbitrary entity object (used by the 'default value' widget).     $ids = (object) [
      'entity_type' => $this->entity->getTargetEntityTypeId(),
      'bundle' => $this->entity->getTargetBundle(),
      'entity_id' => NULL,
    ];
    $form['#entity'] = _field_create_entity_from_ids($ids);
    $items = $this->getTypedData($form['#entity']);
    $item = $items->first() ?: $items->appendItem();

    // Add field settings for the field type and a container for third party     // settings that modules can add to via hook_form_FORM_ID_alter().     $form['settings'] = [
      '#tree' => TRUE,
      '#weight' => 10,
    ];
    $form['settings'] += $item->fieldSettingsForm($form$form_state);
    $form['third_party_settings'] = [
      '#tree' => TRUE,
      

  }

  /** * {@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();
  }

  
$controller = $this->entityTypeManager->getStorage($entity_type);
    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    $entity = $controller->create($values[$default_langcode]);

    foreach ($this->langcodes as $langcode) {
      $values[$langcode] = ['name' => $this->randomString()];
      $entity->addTranslation($langcode$values[$langcode]);
    }

    $langcodes = array_merge([$default_langcode]$this->langcodes);
    foreach ($langcodes as $langcode) {
      $adapter = $entity->getTranslation($langcode)->getTypedData();
      $name = $adapter->get('name')->value;
      $this->assertEquals($values[$langcode]['name']$namenew FormattableMarkup('Name correctly retrieved from "@langcode" adapter', ['@langcode' => $langcode]));
    }
  }

  /** * Tests if entity references are correct after adding a new translation. */
  public function testFieldEntityReference() {
    $entity_type = 'entity_test_mul';
    $controller = $this->entityTypeManager->getStorage($entity_type);
    
$userref_properties = $entity->user_id->getFieldDefinition()->getPropertyDefinitions();
    $this->assertEquals('integer', $userref_properties['target_id']->getDataType()$entity_type . ': Entity id property of the user found.');
    $this->assertEquals('entity_reference', $userref_properties['entity']->getDataType()$entity_type . ': Entity reference property of the user found.');

    $textfield_properties = $entity->field_test_text->getFieldDefinition()->getFieldStorageDefinition()->getPropertyDefinitions();
    $this->assertEquals('string', $textfield_properties['value']->getDataType()$entity_type . ': String value property of the test-text field found.');
    $this->assertEquals('filter_format', $textfield_properties['format']->getDataType()$entity_type . ': String format field of the test-text field found.');
    $this->assertEquals('string', $textfield_properties['processed']->getDataType()$entity_type . ': String processed property of the test-text field found.');

    // Make sure provided contextual information is right.     $entity_adapter = $entity->getTypedData();
    $this->assertSame($entity_adapter->getRoot()$entity_adapter, 'Entity is root object.');
    $this->assertEquals('', $entity_adapter->getPropertyPath());
    $this->assertEquals('', $entity_adapter->getName());
    $this->assertNull($entity_adapter->getParent());

    $field = $entity->user_id;
    $this->assertSame($field->getRoot()->getValue()$entity, 'Entity is root object.');
    $this->assertSame($field->getEntity()$entity, 'getEntity() returns the entity.');
    $this->assertEquals('user_id', $field->getPropertyPath());
    $this->assertEquals('user_id', $field->getName());
    $this->assertSame($field->getParent()->getValue()$entity, 'Parent object matches.');

    

  public function __construct(AccountInterface $current_user) {
    $this->currentUser = $current_user;
  }

  /** * {@inheritdoc} */
  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.');
        }
        
    $this->newRevision = FALSE;

    // Reset the enforcement of the revision translation affected flag.     $this->enforceRevisionTranslationAffected = [];
  }

  /** * {@inheritdoc} */
  public function validate() {
    $this->validated = TRUE;
    $violations = $this->getTypedData()->validate();
    return new EntityConstraintViolationList($thisiterator_to_array($violations));
  }

  /** * {@inheritdoc} */
  public function isValidationRequired() {
    return (bool) $this->validationRequired;
  }

  /** * {@inheritdoc} */

class IsNullConstraintValidator extends IsNullValidator {

  use TypedDataAwareValidatorTrait;

  /** * {@inheritdoc} */
  public function validate($value, Constraint $constraint) {
    $typed_data = $this->getTypedData();
    if (($typed_data instanceof ListInterface || $typed_data instanceof ComplexDataInterface) && $typed_data->isEmpty()) {
      $value = NULL;
    }
    parent::validate($value$constraint);
  }

}
$bundle = EntityTestBundle::create([
      'id' => $this->randomMachineName(),
    ]);
    $bundle->save();

    $entity = EntityTestWithBundle::create([
      'type' => $bundle->id(),
      'name' => $this->randomString(),
    ]);
    $entity->save();

    $this->assertInstanceOf(ConfigEntityAdapter::class$bundle->getTypedData());
    $this->assertInstanceOf(EntityAdapter::class$entity->getTypedData());
  }

}
$container->set('typed_data_manager', $typedDataManager);
    \Drupal::setContainer($container);

    // Create a mock entity used to retrieve typed data.     $entity = $this->getMockForAbstractClass(ContentEntityBase::class[
      [],
      $this->entityTypeId,
      $this->bundle,
    ], '', TRUE, TRUE, TRUE, ['isNew']);

    // Assert that the returned data type is an instance of EntityAdapter.     $this->assertInstanceOf($expected$entity->getTypedData());
  }

  /** * @covers ::validate */
  public function testValidate() {
    $validator = $this->createMock(ValidatorInterface::class);
    /** @var \Symfony\Component\Validator\ConstraintViolationList $empty_violation_list */
    $empty_violation_list = new ConstraintViolationList();
    $non_empty_violation_list = clone $empty_violation_list;
    $violation = $this->createMock('\Symfony\Component\Validator\ConstraintViolationInterface');
    
/** * {@inheritdoc} */
  public function getCacheMaxAge() {
    return $this->storage->getCacheMaxAge();
  }

  /** * {@inheritdoc} */
  public function getTypedData() {
    $this->storage->getTypedData();
  }

  /** * {@inheritdoc} */
  public function addDisplay($plugin_id = 'page', $title = NULL, $id = NULL) {
    return $this->storage->addDisplay($plugin_id$title$id);
  }

  /** * {@inheritdoc} */

  protected static function extractContentEntityFields(ResourceType $resource_type, ContentEntityInterface $entity) {
    $output = [];
    $fields = TypedDataInternalPropertiesHelper::getNonInternalProperties($entity->getTypedData());
    // Filter the array based on the field names.     $enabled_field_names = array_filter(
      array_keys($fields),
      [$resource_type, 'isFieldEnabled']
    );

    // Special handling for user entities that allows a JSON:API user agent to     // access the display name of a user. For example, this is useful when     // displaying the name of a node's author.     // @todo: eliminate this special casing in https://www.drupal.org/project/drupal/issues/3079254.     $entity_type = $entity->getEntityType();
    


  /** * {@inheritdoc} */
  public function getTarget() {
    if (!isset($this->target) && isset($this->id)) {
      // If we have a valid reference, return the entity's TypedData adapter.       $entity = \Drupal::entityTypeManager()
        ->getStorage($this->getTargetDefinition()->getEntityTypeId())
        ->load($this->id);
      $this->target = isset($entity) ? $entity->getTypedData() : NULL;
    }
    return $this->target;
  }

  /** * {@inheritdoc} */
  public function getTargetIdentifier() {
    if (isset($this->id)) {
      return $this->id;
    }
    
Home | Imprint | This part of the site doesn't use cookies.