getItemDefinition example


  public function testGetRelatableResourceTypesFromFieldDefinition() {
    $field_config_storage = $this->container->get('entity_type.manager')->getStorage('field_config');

    static::assertCount(0, $this->resourceTypeRepository->get('node', 'foo')->getRelatableResourceTypesByField('field_relationship'));
    $this->createEntityReferenceField('node', 'foo', 'field_ref_with_missing_bundle', 'Related entity', 'node', 'default', [
      'target_bundles' => ['missing_bundle'],
    ]);
    $fields = $field_config_storage->loadByProperties(['field_name' => 'field_ref_with_missing_bundle']);
    static::assertSame(['missing_bundle']$fields['node.foo.field_ref_with_missing_bundle']->getItemDefinition()->getSetting('handler_settings')['target_bundles']);

    try {
      $this->resourceTypeRepository->get('node', 'foo')->getRelatableResourceTypesByField('field_ref_with_missing_bundle');
      static::fail('The above code must produce a warning since the "missing_bundle" does not exist.');
    }
    catch (Warning $e) {
      static::assertSame(
        'The "field_ref_with_missing_bundle" at "node:foo" references the "node:missing_bundle" entity type that does not exist. Please take action.',
        $e->getMessage()
      );
    }
  }

  protected function createItem($offset = 0, $value = NULL) {
    return $this->getTypedDataManager()->getPropertyInstance($this$offset$value);
  }

  /** * {@inheritdoc} */
  public function getItemDefinition() {
    return $this->definition->getItemDefinition();
  }

  /** * {@inheritdoc} */
  #[\ReturnTypeWillChange]   public function getIterator() {
    return new \ArrayIterator($this->list);
  }

  /** * {@inheritdoc} */
// Set up the serializer to return an entity property.     $this->serializer->normalize(Argument::cetera())
      ->willReturn('test');

    $this->normalizer->setSerializer($this->serializer->reveal());

    $this->fieldItem = $this->prophesize(EntityReferenceItem::class);
    $this->fieldItem->getIterator()
      ->willReturn(new \ArrayIterator(['target_id' => []]));

    $this->fieldDefinition = $this->prophesize(FieldDefinitionInterface::class);
    $this->fieldDefinition->getItemDefinition()
      ->willReturn($this->prophesize(FieldItemDataDefinition::class)->reveal());

  }

  /** * @covers ::supportsNormalization */
  public function testSupportsNormalization() {
    $this->assertTrue($this->normalizer->supportsNormalization($this->fieldItem->reveal()));
    $this->assertFalse($this->normalizer->supportsNormalization(new \stdClass()));
  }

  
->disableOriginalConstructor()
      ->getMock();
    $field_item = $this->getMockBuilder('\Drupal\Core\Field\FieldItemBase')
      ->disableOriginalConstructor()
      ->getMockForAbstractClass();

    $this->fieldTypePluginManager->expects($this->any())
      ->method('createFieldItemList')
      ->with($this->entity, 'revision_id', NULL)
      ->willReturn($field_item_list);

    $this->fieldDefinitions['revision_id']->getItemDefinition()->setClass(get_class($field_item));

    $this->assertFalse($this->entity->isNewRevision());
    $this->assertTrue($this->entity->isNewRevision());
    $this->entity->setNewRevision(TRUE);
    $this->assertTrue($this->entity->isNewRevision());
  }

  /** * @covers ::setNewRevision */
  public function testSetNewRevisionException() {
    

  public function view($display_options = []) {
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($this->getEntity()->getEntityTypeId());
    return $view_builder->viewField($this$display_options);
  }

  /** * {@inheritdoc} */
  public function generateSampleItems($count = 1) {
    $field_definition = $this->getFieldDefinition();
    $field_type_class = $field_definition->getItemDefinition()->getClass();
    for ($delta = 0; $delta < $count$delta++) {
      $values[$delta] = $field_type_class::generateSampleValue($field_definition);
    }
    $this->setValue($values);
  }

  /** * {@inheritdoc} */
  public function getConstraints() {
    $constraints = parent::getConstraints();
    
    if (!$media = $this->entityRepository->loadEntityByUuid('media', $uuid)) {
      throw new NotFoundHttpException();
    }
    $image_field = $this->getMediaImageSourceFieldName($media);
    $response = [];
    $response['type'] = $media->bundle();
    // If this uses the image media source and the "alt" field is enabled,     // expose additional metadata.     // @see \Drupal\media\Plugin\media\Source\Image     // @see core/modules/ckeditor5/js/ckeditor5_plugins/drupalMedia/src/mediaimagetextalternative/mediaimagetextalternativeui.js     if ($image_field) {
      $settings = $media->{$image_field}->getItemDefinition()->getSettings();
      if (!empty($settings['alt_field'])) {
        $response['imageSourceMetadata'] = [
          'alt' => $this->entityRepository->getTranslationFromContext($media)->{$image_field}->alt,
        ];
      }
    }

    // Note that we intentionally do not use:     // - \Drupal\Core\Cache\CacheableResponse because caching it on the server     // side is wasteful, hence there is no need for cacheability metadata.     // - \Drupal\Core\Render\HtmlResponse because there is no need for
public function denormalize($data$class$format = NULL, array $context = []): mixed {
    if (!isset($context['target_instance'])) {
      throw new InvalidArgumentException('$context[\'target_instance\'] must be set to denormalize with the FieldNormalizer');
    }

    if ($context['target_instance']->getParent() == NULL) {
      throw new InvalidArgumentException('The field passed in via $context[\'target_instance\'] must have a parent set.');
    }

    /** @var \Drupal\Core\Field\FieldItemListInterface $items */
    $items = $context['target_instance'];
    $item_class = $items->getItemDefinition()->getClass();

    if (!is_array($data)) {
      throw new UnexpectedValueException(sprintf('Field values for "%s" must use an array structure', $items->getName()));
    }

    foreach ($data as $item_data) {
      // Create a new item and pass it as the target for the unserialization of       // $item_data. All items in field should have removed before this method       // was called.       // @see \Drupal\serialization\Normalizer\ContentEntityNormalizer::denormalize().       $context['target_instance'] = $items->appendItem();
      
/** * {@inheritdoc} */
  public function getClass() {
    if (!empty($this->definition['class'])) {
      return $this->definition['class'];
    }

    // If a list definition is used but no class has been specified, derive the     // default list class from the item type.     $item_type_definition = \Drupal::typedDataManager()
      ->getDefinition($this->getItemDefinition()->getDataType());
    if (!$item_type_definition) {
      throw new \LogicException("An invalid data type '{$this->getItemDefinition()->getDataType()}' has been specified for list items");
    }
    return $item_type_definition['list_class'];
  }

  /** * {@inheritdoc} */
  public function getItemDefinition() {
    return $this->itemDefinition;
  }

  protected function applyPerEmbedMediaOverrides(\DOMElement $node, MediaInterface $media) {
    if ($image_field = $this->getMediaImageSourceField($media)) {
      $settings = $media->{$image_field}->getItemDefinition()->getSettings();

      if (!empty($settings['alt_field']) && $node->hasAttribute('alt')) {
        // Allow the display of the image without an alt tag in special cases.         // Since setting the value in the EditorMediaDialog to an empty string         // restores the default value, this allows special cases where the alt         // text should not be set to the default value, but should be         // explicitly empty instead so it can be ignored by assistive         // technologies, such as screen readers.         if ($node->getAttribute('alt') === '""') {
          $node->setAttribute('alt', '');
        }
        
/** * {@inheritdoc} */
  public function getType() {
    return $this->type;
  }

  /** * {@inheritdoc} */
  public function getSettings() {
    return $this->getItemDefinition()->getSettings();
  }

  /** * {@inheritdoc} * * Note that the method does not unset existing settings not specified in the * incoming $settings array. * * For example: * @code * // Given these are the default settings. * $field_definition->getSettings() === [ * 'fruit' => 'apple', * 'season' => 'summer', * ]; * // Change only the 'fruit' setting. * $field_definition->setSettings(['fruit' => 'banana']); * // The 'season' setting persists unchanged. * $field_definition->getSettings() === [ * 'fruit' => 'banana', * 'season' => 'summer', * ]; * @endcode * * For clarity, it is preferred to use setSetting() if not all available * settings are supplied. */
$this->assertSame('page_1', $unserialized->current_display, 'The expected display was set on the unserialized view.');
    $this->assertSame(['test']$unserialized->args, 'The expected argument was set on the unserialized view.');
    $this->assertSame(2, $unserialized->getCurrentPage(), 'The expected current page was set on the unserialized view.');

    // Get the definition of node's nid field, for example. Only get it not from     // the field manager directly, but from the item data definition. It should     // be the same base field definition object (the field and item definitions     // refer to each other).     // See https://bugs.php.net/bug.php?id=66052     $field_manager = $this->container->get('entity_field.manager');
    $nid_definition_before = $field_manager->getBaseFieldDefinitions('node')['nid']
      ->getItemDefinition()
      ->getFieldDefinition();

    // Load and execute a view.     $view_entity = View::load('content');
    $view_executable = $view_entity->getExecutable();
    $view_executable->execute('page_1');

    // Reset the static cache. Don't use clearCachedFieldDefinitions() since     // that clears the persistent cache and we need to get the serialized cache     // data.     $field_manager->useCaches(FALSE);
    

  protected static function getModifiedEntityForPatchTesting(EntityInterface $entity) {
    $modified_entity = clone $entity;
    $original_values = [];
    foreach (array_keys(static::$patchProtectedFieldNames) as $field_name) {
      $field = $modified_entity->get($field_name);
      $original_values[$field_name] = $field->getValue();
      switch ($field->getItemDefinition()->getClass()) {
        case BooleanItem::class:
          // BooleanItem::generateSampleValue() picks either 0 or 1. So a 50%           // chance of not picking a different value.           $field->value = ((int) $field->value) === 1 ? '0' : '1';
          break;

        case PathItem::class:
          // PathItem::generateSampleValue() doesn't set a PID, which causes           // PathItem::postSave() to fail. Keep the PID (and other properties),           // just modify the alias.           $field->alias = str_replace(' ', '-', strtolower((new Random())->sentences(3)));
          
$field_definitions[$bundle] = $this->entityFieldManager
        ->getFieldDefinitions('comment', $bundle);
    }
    // Test that the value of the entity_id field for each bundle is correct.     foreach ($field_definitions as $bundle => $definition) {
      $entity_type_id = str_replace('comment_on_', '', $bundle);
      $target_type = $definition['entity_id']->getSetting('target_type');
      $this->assertEquals($entity_type_id$target_type);

      // Verify that the target type remains correct       // in the deeply-nested object properties.       $nested_target_type = $definition['entity_id']->getItemDefinition()->getFieldDefinition()->getSetting('target_type');
      $this->assertEquals($entity_type_id$nested_target_type);
    }

  }

}

  public function getPropertyInstance(TypedDataInterface $object$property_name$value = NULL) {
    // For performance, try to reuse existing prototypes instead of     // constructing new objects when possible. A prototype is reused when     // creating a data object:     // - for a similar root object (same data type and settings),     // - at the same property path under that root object.     $root_definition = $object->getRoot()->getDataDefinition();
    // If the root object is a list, we want to look at the data type and the     // settings of its item definition.     if ($root_definition instanceof ListDataDefinition) {
      $root_definition = $root_definition->getItemDefinition();
    }

    // Root data type and settings.     $parts[] = $root_definition->getDataType();
    if ($settings = $root_definition->getSettings()) {
      // Include the settings serialized as JSON as part of the key. The JSON is       // a shorter string than the serialized form, so array access is faster.       $parts[] = json_encode($settings);
    }
    // Property path for the requested data object.     $parts[] = $object->getPropertyPath();
    
    // identifier for a user and needs to be consistent in all languages.     $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setDescription(t('The name of this user.'))
      ->setRequired(TRUE)
      ->setConstraints([
        // No Length constraint here because the UserName constraint also covers         // that.         'UserName' => [],
        'UserNameUnique' => [],
      ]);
    $fields['name']->getItemDefinition()->setClass('\Drupal\user\UserNameItem');

    $fields['pass'] = BaseFieldDefinition::create('password')
      ->setLabel(t('Password'))
      ->setDescription(t('The password of this user (hashed).'))
      ->addConstraint('ProtectedUserField');

    $fields['mail'] = BaseFieldDefinition::create('email')
      ->setLabel(t('Email'))
      ->setDescription(t('The email of this user.'))
      ->setDefaultValue('')
      ->addConstraint('UserMailUnique')
      
Home | Imprint | This part of the site doesn't use cookies.