getFields example

public function __construct(private readonly DefinitionInstanceRegistry $definitionRegistry)
    {
    }

    #[Route(path: '/api/_action/attribute-set/relations', name: 'api.action.attribute-set.get-relations', methods: ['GET'])]     public function getAvailableRelations(): JsonResponse
    {
        $definitions = $this->definitionRegistry->getDefinitions();

        $entityNames = [];
        foreach ($definitions as $definition) {
            if (\count($definition->getFields()->filterInstance(CustomFields::class)) === 0) {
                continue;
            }
            if ($definition instanceof EntityTranslationDefinition) {
                $definition = $definition->getParentDefinition();
            }
            $entityNames[] = $definition->getEntityName();
        }
        sort($entityNames);

        return new JsonResponse($entityNames);
    }
}
$attributes = [];
        $requiredAttributes = [];
        $relationships = [];

        $schemaName = $this->snakeCaseToCamelCase($definition->getEntityName());
        $uuid = Uuid::fromStringToHex($schemaName);
        $exampleDetailPath = $path . '/' . $uuid;

        $extensions = [];
        $extensionRelationships = [];

        foreach ($definition->getFields() as $field) {
            if (!$this->shouldFieldBeIncluded($field$forSalesChannel)) {
                continue;
            }

            if ($field->is(Extension::class)) {
                $extensions[] = $field;

                continue;
            }

            if ($field->is(Required::class) && !$field instanceof VersionField && !$field instanceof ReferenceVersionField) {
                
/** @var Entities $outerEntities */
        $outerEntities = $this->entitySchema->getEntities();
        $this->customEntities = $outerEntities->getEntities();
    }

    public function testEnrichCmsAwareAffectedEntities(): void
    {
        static::markTestSkipped('cms-aware will be re-implemented via NEXT-22697');
        static::assertCount(4, $this->customEntities);

        foreach ($this->customEntities as $entity) {
            static::assertCount(4, $entity->getFields());
            static::assertCount(0, $entity->getFlags());
        }

        $enrichedEntities = $this->customEntityEnrichmentService->enrich(
            $this->entitySchema,
            null
        );
        static::assertInstanceOf(CustomEntityXmlSchema::class$enrichedEntities);

        /** @var Entities $outerEnrichedCustomEntities */
        $outerEnrichedCustomEntities = $enrichedEntities->getEntities();
        
/** * {@inheritdoc} */
  public function prepareRow(Row $row) {
    $nid = $row->getSourceProperty('entity_id');
    $vid = $row->getSourceProperty('revision_id');
    $type = $row->getSourceProperty('type');
    $language = $row->getSourceProperty('language');

    // Get Field API field values.     foreach ($this->getFields('node', $type) as $field_name => $field) {
      // Ensure we're using the right language if the entity is translatable.       $field_language = $field['translatable'] ? $language : NULL;
      $row->setSourceProperty($field_name$this->getFieldValues('node', $field_name$nid$vid$field_language));
    }

    // If the node title was replaced by a real field using the Drupal 7 Title     // module, use the field value instead of the node title.     if ($this->moduleExists('title')) {
      $title_field = $row->getSourceProperty('title_field');
      if (isset($title_field[0]['value'])) {
        $row->setSourceProperty('title', $title_field[0]['value']);
      }
$ids = json_decode($ids, true);

        $data = array_filter($datafunction D$item) use ($ids) {
            return \in_array($item['id']$ids);
        });

        return $data;
    }

    private function getLabelField(Type $type): Field
    {
        foreach ($type->getFields() as $item) {
            if ($item->isShowListing()) {
                return $item;
            }
        }

        throw new RuntimeException(sprintf('Type %s needs a label', $type->getName()));
    }
}
'pattern' => '^[0-9a-f]{32}$',
                    ],
                ],
                $schema,
                $relationships
            );

            if (\array_key_exists('extensions', $properties)) {
                $extensions = [];

                foreach ($properties['extensions']['properties'] as $propertyName => $extension) {
                    $field = $definition->getFields()->get($propertyName);

                    if (!$field instanceof AssociationField) {
                        $extensions[$propertyName] = $extension;

                        continue;
                    }

                    $data = $extension['properties']['data'];
                    $type = $data['type'];

                    if ($type === 'object') {
                        
'id' => Uuid::fromHexToBytes($id),
        ]);
        $this->connection->method('prepare')->willReturn($statement);

        $this->conditionRegistry->method('getFlowRuleNames')->willReturn(['orderTags']);

        $this->areaUpdater->update([$id]);
    }

    public function testTriggerChangeset(): void
    {
        $fieldCollection = $this->definition->getFields();

        $oneToManyField = $fieldCollection->get('oneToMany');
        $manyToOneField = $fieldCollection->get('manyToOne');

        static::assertInstanceOf(OneToManyAssociationField::class$oneToManyField);
        static::assertInstanceOf(ManyToOneAssociationField::class$manyToOneField);

        $event = new PreWriteValidationEvent(WriteContext::createFromContext(Context::createDefaultContext())[
            new DeleteCommand($oneToManyField->getReferenceDefinition()[]$this->createMock(EntityExistence::class)),
            new UpdateCommand($manyToOneField->getReferenceDefinition()[][]$this->createMock(EntityExistence::class), ''),
            new UpdateCommand($oneToManyField->getReferenceDefinition()['rule_id' => 'foo'][]$this->createMock(EntityExistence::class), ''),
        ]);

    public function __construct(
        private array $searches,
        private readonly ?EntityDefinition $definition = null
    ) {
        if (!$definition) {
            return;
        }

        try {
            $definition->getFields();
        } catch (\Throwable $exception) {
            $registry = new StaticDefinitionInstanceRegistry(
                [$definition],
                Validation::createValidator(),
                new StaticEntityWriterGateway()
            );
            $definition->compile($registry);
        }
    }

    /** * @return EntitySearchResult<TEntityCollection> */


    /** * @throws InvalidUuidException */
    private function fetch(EntityDefinition $definition, array $ids, string $class, Context $context, bool $restrictDeleteOnlyFirstLevel = false): array
    {
        if ($context->getVersionId() !== Defaults::LIVE_VERSION) {
            return [];
        }

        if (!$definition->getFields()->has('id')) {
            return [];
        }

        // prevent foreign key check for language definition, otherwise all ids of language translations has to be checked         if ($definition->getClass() === LanguageDefinition::class) {
            return [];
        }

        $cascades = $definition->getFields()->filter(static fn (Field $field): bool => $field->is($class));

        if ($cascades->count() === 0) {
            
// If this entity was translated using Entity Translation, we need to get     // its source language to get the field values in the right language.     // The translations will be migrated by the d7_user_entity_translation     // migration.     $entity_translatable = $this->isEntityTranslatable('user');
    $source_language = $this->getEntityTranslationSourceLanguage('user', $uid);
    $language = $entity_translatable && $source_language ? $source_language : $row->getSourceProperty('language');
    $row->setSourceProperty('entity_language', $language);

    // Get Field API field values.     foreach ($this->getFields('user') as $field_name => $field) {
      // Ensure we're using the right language if the entity and the field are       // translatable.       $field_language = $entity_translatable && $field['translatable'] ? $language : NULL;
      $row->setSourceProperty($field_name$this->getFieldValues('user', $field_name$uid, NULL, $field_language));
    }

    // Get profile field values. This code is lifted directly from the D6     // ProfileFieldValues plugin.     if ($this->getDatabase()->schema()->tableExists('profile_value')) {
      $query = $this->select('profile_value', 'pv')
        ->fields('pv', ['fid', 'value']);
      
public function testCreateFromXml(): void
    {
        $manifest = Manifest::createFromXmlFile(__DIR__ . '/_fixtures/price-field.xml');

        static::assertNotNull($manifest->getCustomFields());
        static::assertCount(1, $manifest->getCustomFields()->getCustomFieldSets());

        /** @var CustomFieldSet $customFieldSet */
        $customFieldSet = $manifest->getCustomFields()->getCustomFieldSets()[0];

        static::assertCount(1, $customFieldSet->getFields());

        $priceField = $customFieldSet->getFields()[0];
        static::assertInstanceOf(PriceField::class$priceField);
        static::assertEquals('test_price_field', $priceField->getName());
        static::assertEquals([
            'en-GB' => 'Test price field',
        ]$priceField->getLabel());
        static::assertEquals([]$priceField->getHelpText());
        static::assertEquals(1, $priceField->getPosition());
        static::assertFalse($priceField->getRequired());
    }

    

    public function serialize(Config $config, EntityDefinition $definition$entity): iterable
    {
        if ($entity === null) {
            return;
        }

        if ($entity instanceof Struct) {
            $entity = $entity->jsonSerialize();
        }

        $fields = $definition->getFields();
        $extensionFields = $definition->getExtensionFields();

        foreach ($entity as $key => $value) {
            if ($key === 'extensions') {
                foreach ($value as $extensionKey => $extensionValue) {
                    if (isset($extensionFields[$extensionKey])) {
                        $serializer = $this->serializerRegistry->getFieldSerializer($extensionFields[$extensionKey]);
                        yield from $serializer->serialize($config$extensionFields[$extensionKey]$extensionValue);
                    }
                }

                

  protected function applyXmlFieldDecodingQuirks(array $normalization) {
    foreach ($this->entity->getFields(TRUE) as $field_name => $field) {
      // Not every field is accessible.       if (!isset($normalization[$field_name])) {
        continue;
      }

      for ($i = 0; $i < count($normalization[$field_name])$i++) {
        switch ($field->getItemDefinition()->getClass()) {
          case BooleanItem::class:
          case StatusItem::class:
            // @todo Remove the StatusItem case in             // https://www.drupal.org/project/drupal/issues/2936864.
$storage->resetCache([$entity->id()]);
    $entity_loaded = $storage->load($entity->id());
    $this->assertSame($uuid$entity_loaded->uuid());

    // Verify that \Drupal::service('entity.repository')->loadEntityByUuid() loads the same entity.     $entity_loaded_by_uuid = \Drupal::service('entity.repository')->loadEntityByUuid($entity_type$uuid, TRUE);
    $this->assertSame($uuid$entity_loaded_by_uuid->uuid());
    $this->assertEquals($entity_loaded->id()$entity_loaded_by_uuid->id());

    // Creating a duplicate needs to result in a new UUID.     $entity_duplicate = $entity->createDuplicate();
    foreach ($entity->getFields() as $property => $value) {
      switch ($property) {
        case 'uuid':
          $this->assertNotNull($entity_duplicate->uuid());
          $this->assertNotNull($entity->uuid());
          $this->assertNotEquals($entity->uuid()$entity_duplicate->uuid());
          break;

        case 'id':
          $this->assertNull($entity_duplicate->id());
          $this->assertNotNull($entity->id());
          $this->assertNotEquals($entity->id()$entity_duplicate->id());
          


                if (!$entity->hasField($label)) {
                    throw CustomEntityException::labelPropertyNotDefined($label);
                }

                if (!$entity->getField($label) instanceof StringField) {
                    throw CustomEntityException::labelPropertyWrongType($label);
                }
            }

            foreach ($entity->getFields() as $field) {
                if ($field instanceof OneToManyField) {
                    $this->validateAssociation($field);
                }
            }
        }
    }

    private function validateAssociation(OneToManyField $field): void
    {
        $reference = $field->getReference();

        
Home | Imprint | This part of the site doesn't use cookies.