getEntityClass example

$container->get('language_manager'),
      $container->get('entity.memory_cache')
    );
  }

  /** * {@inheritdoc} */
  public function doCreate(array $values = []) {
    // Set default language to site default if not provided.     $values += [$this->getEntityType()->getKey('langcode') => $this->languageManager->getDefaultLanguage()->getId()];
    $entity_class = $this->getEntityClass();
    $entity = new $entity_class($values$this->entityTypeId);

    // @todo This is handled by ContentEntityStorageBase, which assumes     // FieldableEntityInterface. The current approach in     // https://www.drupal.org/node/1867228 improves this but does not solve it     // completely.     if ($entity instanceof FieldableEntityInterface) {
      foreach ($entity as $name => $field) {
        if (isset($values[$name])) {
          $entity->$name = $values[$name];
        }
        
EOF;

        $entity = explode('\\', (string) $definition->getEntityClass());
        $entity = array_pop($entity);

        $callTemplate = '';
        if (!empty($calls)) {
            $callTemplate = "\n " . implode("\n ", $calls);
        }

        $vars = [
            '#namespace#' => $namespace,
            '#class#' => $class,
            '#entity#' => $entity,
            
private function generateProperty(EntityDefinition $definition, Field $field): ?array
    {
        $nullable = '|null';
        if ($field->is(Required::class)) {
            $nullable = '';
        }

        $uses = [];

        switch (true) {
            case $field instanceof ParentAssociationField:
                $uses[] = $this->getUsage($definition->getEntityClass());
                $type = $this->getClassTypeHint($definition->getEntityClass());

                break;
            case $field instanceof ChildrenAssociationField:
                $uses[] = $this->getUsage($definition->getCollectionClass());
                $type = $this->getClassTypeHint($definition->getCollectionClass());

                break;
            case $field instanceof OneToOneAssociationField:
            case $field instanceof ManyToOneAssociationField:
                $uses[] = $this->getUsage($field->getReferenceDefinition()->getEntityClass());
                
// Start deleting entities using the bundle class.     $entity->delete();
    $this->assertEquals(1, EntityTestBundleClass::$preDeleteCount);
    $this->assertEquals(1, EntityTestBundleClass::$postDeleteCount);
    $entity_2->delete();
    $this->assertEquals(2, EntityTestBundleClass::$preDeleteCount);
    $this->assertEquals(2, EntityTestBundleClass::$postDeleteCount);

    // Verify that getEntityClass without bundle returns the default entity     // class.     $entity_class = $this->storage->getEntityClass(NULL);
    $this->assertEquals(EntityTest::class$entity_class);

    // Verify that getEntityClass with a bundle returns the proper class.     $entity_class = $this->storage->getEntityClass('bundle_class');
    $this->assertEquals(EntityTestBundleClass::class$entity_class);

    // Verify that getEntityClass with a non-existing bundle returns the entity     // class.     $entity_class = $this->storage->getEntityClass('custom');
    $this->assertEquals(EntityTest::class$entity_class);
  }

  
// Initialize translations array.     $translations = array_fill_keys(array_keys($values)[]);

    // Load values from shared and dedicated tables.     $this->loadFromSharedTables($values$translations$load_from_revision);
    $this->loadFromDedicatedTables($values$load_from_revision);

    $entities = [];
    foreach ($values as $id => $entity_values) {
      $bundle = $this->bundleKey ? $entity_values[$this->bundleKey][LanguageInterface::LANGCODE_DEFAULT] : NULL;
      // Turn the record into an entity class.       $entity_class = $this->getEntityClass($bundle);
      $entities[$id] = new $entity_class($entity_values$this->entityTypeId, $bundlearray_keys($translations[$id]));
    }

    return $entities;
  }

  /** * Loads values for fields stored in the shared data tables. * * @param array &$values * Associative array of entities values, keyed on the entity ID or the * revision ID. * @param array &$translations * List of translations, keyed on the entity ID. * @param bool $load_from_revision * Flag to indicate whether revisions should be loaded or not. */


        // always add the criteria fields to the collection, otherwise we have conflicts between criteria.fields and criteria.association logic         $fields = $this->addAssociationFieldsToCriteria($criteria$definition$fields);

        if ($definition->isInheritanceAware() && $criteria->hasAssociation('parent')) {
            throw new ParentAssociationCanNotBeFetched();
        }

        $rows = $this->fetch($criteria$definition$context$fields$partial);

        $collection = $this->hydrator->hydrate($collection$definition->getEntityClass()$definition$rows$definition->getEntityName()$context$partial);

        $collection = $this->fetchAssociations($criteria$definition$context$collection$fields$partial);

        $hasIds = !empty($criteria->getIds());
        if ($hasIds && empty($criteria->getSorting())) {
            $collection->sortByIdArray($criteria->getIds());
        }

        return $collection;
    }

    

            $violations[$definition->getClass()] = [];

            $violations = array_merge_recursive($violations$this->validateSchema($definition));

            $violations = array_merge_recursive($violations$this->validateColumn($definition));

            $violations = array_merge_recursive($violations$this->checkEntityNameConstant($definition));

            $struct = ArrayEntity::class;
            if (!$definition instanceof MappingEntityDefinition) {
                $struct = $definition->getEntityClass();
            }

            if ($struct !== ArrayEntity::class) {
                $violations[$definition->getClass()] = array_merge(
                    $violations[$definition->getClass()],
                    $this->validateStruct($struct$definition)
                );

                $violations[$definition->getClass()] = array_merge(
                    $violations[$definition->getClass()],
                    $this->findEntityNotices($struct$definition)
                );
public function testInternalFieldsAreNotVisibleInTwig(): void
    {
        $definitionRegistry = $this->getContainer()->get(DefinitionInstanceRegistry::class);

        foreach ($definitionRegistry->getDefinitions() as $definition) {
            /** @var CompiledFieldCollection $internalFields */
            $internalFields = $definition->getFields()
                ->filter(fn (Field $field): bool => !$field->is(ApiAware::class));

            foreach ($internalFields as $field) {
                $this->testAccessibilityForField($definition$field->getPropertyName()$definition->getEntityClass());
                $this->testAccessibilityForField($definition$field->getPropertyName(), PartialEntity::class);
            }
        }
    }

    private function testAccessibilityForField(EntityDefinition $definition, string $propertyName, string $entityClass): void
    {
        $entity = new $entityClass();
        $entity->internalSetEntityData($definition->getEntityName()$definition->getFieldVisibility());

        $twig = $this->initTwig($propertyName);

        
$extended = Uuid::randomBytes();

        $rows = [
            [
                'test.id' => $id,
                'test.name' => 'test',
                'test.normalFk' => $normal,
                'test.extendedFk' => $extended,
            ],
        ];

        $structs = $this->hydrator->hydrate(new EntityCollection()$definition->getEntityClass()$definition$rows, 'test', Context::createDefaultContext());
        static::assertCount(1, $structs);

        /** @var ArrayEntity|null $first */
        $first = $structs->first();

        static::assertInstanceOf(ArrayEntity::class$first);

        static::assertSame('test', $first->get('name'));

        static::assertSame(Uuid::fromBytesToHex($id)$first->get('id'));
        static::assertSame(Uuid::fromBytesToHex($normal)$first->get('normalFk'));

        
protected function invokeHook($hook, EntityInterface $entity) {
    // Invoke the hook.     $this->moduleHandler()->invokeAll($this->entityTypeId . '_' . $hook[$entity]);
    // Invoke the respective entity-level hook.     $this->moduleHandler()->invokeAll('entity_' . $hook[$entity]);
  }

  /** * {@inheritdoc} */
  public function create(array $values = []) {
    $entity_class = $this->getEntityClass();
    $entity_class::preCreate($this$values);

    // Assign a new UUID if there is none yet.     if ($this->uuidKey && $this->uuidService && !isset($values[$this->uuidKey])) {
      $values[$this->uuidKey] = $this->uuidService->generate();
    }

    $entity = $this->doCreate($values);
    $entity->enforceIsNew();

    $entity->postCreate($this);

    
public function register(EntityDefinition $definition, ?string $serviceId = null): void
    {
        if (!$serviceId) {
            $serviceId = $definition::class;
        }

        if (!$this->container->has($serviceId)) {
            $this->container->set($serviceId$definition);
        }

        if ($this->entityClassMapping !== null) {
            $this->entityClassMapping[$definition->getEntityClass()] = $definition;
        }

        $this->definitions[$definition->getEntityName()] = $serviceId;

        $this->repositoryMap[$definition->getEntityName()] = $definition->getEntityName() . '.repository';

        $definition->compile($this);
    }

    /** * @return array<class-string<Entity>, EntityDefinition> */
// Mock the base field definition override.     $override_entity_type = $this->prophesize(EntityTypeInterface::class);

    $this->entityType = $this->prophesize(EntityTypeInterface::class);
    $this->setUpEntityTypeDefinitions(['test_entity_type' => $this->entityType, 'base_field_override' => $override_entity_type]);

    $storage = $this->prophesize(EntityStorageInterface::class);
    $storage->loadMultiple(Argument::type('array'))->willReturn([]);

    // By default, make the storage entity class lookup return the     // EntityTypeManagerTestEntity class     $storage->getEntityClass(NULL)->willReturn(EntityTypeManagerTestEntity::class);
    $storage->getEntityClass(Argument::type('string'))->willReturn(EntityTypeManagerTestEntity::class);
    // When using the "test_entity_bundle_class" bundle, return the     // EntityTypeManagerTestEntityBundle class     $storage->getEntityClass('test_entity_bundle_class')->willReturn(EntityTypeManagerTestEntityBundle::class);

    $this->entityTypeManager->getStorage('test_entity_type')->willReturn($storage->reveal());
    $this->entityTypeManager->getStorage('base_field_override')->willReturn($storage->reveal());

    $this->entityType->getClass()->willReturn($entity_class);
    $this->entityType->getKeys()->willReturn($entity_keys + ['default_langcode' => 'default_langcode']);
    $this->entityType->entityClassImplements(FieldableEntityInterface::class)->willReturn(TRUE);
    


    return $entities;
  }

  /** * {@inheritdoc} */
  protected function doCreate(array $values) {
    // Set default language to current language if not provided.     $values += [$this->langcodeKey => $this->languageManager->getCurrentLanguage()->getId()];
    $entity_class = $this->getEntityClass();
    $entity = new $entity_class($values$this->entityTypeId);

    return $entity;
  }

  /** * {@inheritdoc} */
  protected function doDelete($entities) {
    foreach ($entities as $entity) {
      $this->configFactory->getEditable($this->getPrefix() . $entity->id())->delete();
    }
$this->bundleKey = $this->entityType->getKey('bundle');
    $this->entityFieldManager = $entity_field_manager;
    $this->cacheBackend = $cache;
    $this->entityTypeBundleInfo = $entity_type_bundle_info;
  }

  /** * {@inheritdoc} */
  public function create(array $values = []) {
    $bundle = $this->getBundleFromValues($values);
    $entity_class = $this->getEntityClass($bundle);
    // @todo Decide what to do if preCreate() tries to change the bundle.     // @see https://www.drupal.org/project/drupal/issues/3230792     $entity_class::preCreate($this$values);

    // Assign a new UUID if there is none yet.     if ($this->uuidKey && $this->uuidService && !isset($values[$this->uuidKey])) {
      $values[$this->uuidKey] = $this->uuidService->generate();
    }

    $entity = $this->doCreate($values);
    $entity->enforceIsNew();

    

  protected function buildBundleFieldDefinitions($entity_type_id$bundle, array $base_field_definitions) {
    $entity_type = $this->entityTypeManager->getDefinition($entity_type_id);

    // Use a bundle specific class if one is defined.     $class = $this->entityTypeManager->getStorage($entity_type_id)->getEntityClass($bundle);

    // Allow the entity class to provide bundle fields and bundle-specific     // overrides of base fields.     $bundle_field_definitions = $class::bundleFieldDefinitions($entity_type$bundle$base_field_definitions);

    // Load base field overrides from configuration. These take precedence over     // base field overrides returned above.     $base_field_override_ids = array_map(function D$field_name) use ($entity_type_id$bundle) {
      return $entity_type_id . '.' . $bundle . '.' . $field_name;
    }array_keys($base_field_definitions));
    $base_field_overrides = $this->entityTypeManager->getStorage('base_field_override')->loadMultiple($base_field_override_ids);
    
Home | Imprint | This part of the site doesn't use cookies.