getClassMetadata example

// Get the entity for the attribute, e.g. Shopware\Models\Article\Detail         $entity = $this->getDqlHelper()->getEntityForAttribute($attribute);
        // Get the prefixed column, e.g. detail.number         $column = $this->getDqlHelper()->getColumnForAttribute($attribute);

        // Alias for the entity, e.g. details         $alias = $this->getDqlHelper()->getPrefixForEntity($entity);

        // Get column name without prefix         list($prefix$plainColumn) = explode('.', $column);
        // Column type might be needed for additional formatting         $columnType = $this->getDqlHelper()->getEntityManager()->getClassMetadata($entity)->fieldMappings[$plainColumn]['type'];

        // Query         $builder = $this->getDqlHelper()->getEntityManager()->createQueryBuilder()
            // Using distinct instead of groupBy is waaay faster - but will result in some pages having only one result             ->select("DISTINCT {$column}")
            ->from($entity$alias);
        // Limit to results matching the filter string         if ($queryConfig['filter']) {
            $builder->where("{$column} LIKE ?1")
                ->setParameter(1, '%' . $queryConfig['filter'] . '%');
        }
        
/** * Creates a new choice loader. * * Optionally, an implementation of {@link EntityLoaderInterface} can be * passed which optimizes the object loading for one of the Doctrine * mapper implementations. * * @param string $class The class name of the loaded objects */
    public function __construct(ObjectManager $manager, string $class, IdReader $idReader = null, EntityLoaderInterface $objectLoader = null)
    {
        $classMetadata = $manager->getClassMetadata($class);

        if ($idReader && !$idReader->isSingleId()) {
            throw new \InvalidArgumentException(sprintf('The second argument "$idReader" of "%s" must be null when the query cannot be optimized because of composite id fields.', __METHOD__));
        }

        $this->manager = $manager;
        $this->class = $classMetadata->getName();
        $this->idReader = $idReader;
        $this->objectLoader = $objectLoader;
    }

    
throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_debug_type($user)));
        }

        $repository = $this->getRepository();
        if ($repository instanceof UserProviderInterface) {
            $refreshedUser = $repository->refreshUser($user);
        } else {
            // The user must be reloaded via the primary key as all other data             // might have changed without proper persistence in the database.             // That's the case when the user has been changed by a form with             // validation errors.             if (!$id = $this->getClassMetadata()->getIdentifierValues($user)) {
                throw new \InvalidArgumentException('You cannot refresh a user from the EntityUserProvider that does not contain an identifier. The user object has to be serialized with its own identifier mapped by Doctrine.');
            }

            $refreshedUser = $repository->find($id);
            if (null === $refreshedUser) {
                $e = new UserNotFoundException('User with id '.json_encode($id).' not found.');
                $e->setUserIdentifier(json_encode($id));

                throw $e;
            }
        }

        
$em->expects($this->any())
            ->method('getRepository')
            ->willReturn($repository);

        return $em;
    }

    private function createSchema($em)
    {
        $schemaTool = new SchemaTool($em);
        $schemaTool->createSchema([
            $em->getClassMetadata('Symfony\Bridge\Doctrine\Tests\Fixtures\User'),
        ]);
    }
}

abstract class UserLoaderRepository implements ObjectRepository, UserLoaderInterface
{
    abstract public function loadUserByIdentifier(string $identifier): ?UserInterface;
}

abstract class PasswordUpgraderRepository implements ObjectRepository, PasswordUpgraderInterface
{
    


        if ($entity instanceof Proxy) {
            $entity->__load();
            $className = get_parent_class($entity);
        } else {
            $className = \get_class($entity);
        }
        if (!\is_string($className)) {
            throw new RuntimeException('Could not get class name');
        }
        $metadata = $this->getClassMetadata($className);
        $data = [];
        $inflector = new Inflector(new NoopWordInflector()new NoopWordInflector());

        foreach ($metadata->fieldMappings as $field => $mapping) {
            if (!($metadata->reflFields[$field] instanceof ReflectionProperty)) {
                throw new InvalidArgumentException(sprintf('Expected an instance of %s', ReflectionProperty::class));
            }

            $data[$field] = $metadata->reflFields[$field]->getValue($entity);
        }

        

        $resolver->setDefaults(['allow_extra_fields' => true]);
    }

    /** * @param array{data_class: class-string<ModelEntity>} $options * * @return void */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $metaData = $this->entityManager->getClassMetadata($options['data_class']);

        $attributes = $this->attributeService->getList($metaData->getTableName());

        foreach ($attributes as $attribute) {
            if ($attribute->isIdentifier()) {
                continue;
            }

            $field = $metaData->getFieldForColumn($attribute->getColumnName());
            $builder->add($field);
        }

        
public function __construct(EntityManagerInterface $entityManager, string $classValidatorRegexp = null)
    {
        $this->entityManager = $entityManager;
        $this->classValidatorRegexp = $classValidatorRegexp;
    }

    public function loadClassMetadata(ClassMetadata $metadata): bool
    {
        $className = $metadata->getClassName();
        try {
            $doctrineMetadata = $this->entityManager->getClassMetadata($className);
        } catch (MappingException|OrmMappingException) {
            return false;
        }

        if (!$doctrineMetadata instanceof ClassMetadataInfo) {
            return false;
        }

        $loaded = false;
        $enabledForClass = $this->isAutoMappingEnabledForClass($metadata$this->classValidatorRegexp);

        


    public function setRepository(EntityManagerInterface $entityManager, string $entityName, ObjectRepository $repository): void
    {
        $repositoryHash = $this->getRepositoryHash($entityManager$entityName);

        $this->repositoryList[$repositoryHash] = $repository;
    }

    private function createRepository(EntityManagerInterface $entityManager, string $entityName): ObjectRepository
    {
        $metadata = $entityManager->getClassMetadata($entityName);
        $repositoryClassName = $metadata->customRepositoryClassName ?: $entityManager->getConfiguration()->getDefaultRepositoryClassName();

        return new $repositoryClassName($entityManager$metadata);
    }

    private function getRepositoryHash(EntityManagerInterface $entityManager, string $entityName): string
    {
        return $entityManager->getClassMetadata($entityName)->getName().spl_object_hash($entityManager);
    }
}
if ($entity === Category::class) {
            $data = $this->resolveCategoryPath($data);
        }

        return $data;
    }

    private function getEntitySearchFields(string $entity): array
    {
        $entityManager = $this->get(ModelManager::class);
        $metaData = $entityManager->getClassMetadata($entity);

        $fields = array_filter(
            $metaData->getFieldNames(),
            static function D$field) use ($metaData) {
                $type = $metaData->getTypeOfField($field);

                return \in_array($type['string', 'text', 'decimal', 'float']);
            }
        );

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

            $params[] = $identifier[$idField];
            $where[]  = $this->quoteStrategy->getJoinColumnName(
                $this->class->associationMappings[$idField]['joinColumns'][0],
                $this->class,
                $this->platform
            );

            $targetMapping = $this->em->getClassMetadata($this->class->associationMappings[$idField]['targetEntity']);
            $targetType    = PersisterHelper::getTypeOfField($targetMapping->identifier[0]$targetMapping$this->em);

            if ($targetType === []) {
                throw UnrecognizedField::byFullyQualifiedName($this->class->name, $targetMapping->identifier[0]);
            }

            $types[] = reset($targetType);
        }

        if ($versioned) {
            $versionField = $this->class->versionField;
            

    public function generateAttributesFromColumns()
    {
        $columns = $this->getDqlHelper()->getAttributes();
        $columnInfo = [];

        foreach ($this->getDqlHelper()->getEntities() as $entity) {
            [$entity$prefix] = $entity;
            $newMapping = [];
            $mappings = $this->getDqlHelper()->getEntityManager()->getClassMetadata($entity)->fieldMappings;
            foreach ($mappings as $key => $value) {
                $newMapping[strtoupper($prefix . '.' . $key)] = $value;
            }
            $columnInfo = array_merge($columnInfo$newMapping);
        }

        $attributes = [];

        foreach ($columns as $column) {
            $mapping = $columnInfo[$column];
            $type = $mapping['type'];
            
if (!$mapping) {
            return [];
        }

        // if a specific id has been defined in the options and there is no corresponding attribute         // return false in order to avoid a fallback to the id which might be of another object         if (\is_string($options->id) && null === $request->attributes->get($options->id)) {
            return [];
        }

        $criteria = [];
        $metadata = $manager->getClassMetadata($options->class);

        foreach ($mapping as $attribute => $field) {
            if (!$metadata->hasField($field) && (!$metadata->hasAssociation($field) || !$metadata->isSingleValuedAssociation($field))) {
                continue;
            }

            $criteria[$field] = $request->attributes->get($attribute);
        }

        if ($options->stripNull) {
            $criteria = array_filter($criteriastatic fn ($value) => null !== $value);
        }

        }

        // Entity Insertions         foreach ($uow->getScheduledEntityInsertions() as $category) {
            if (!($category instanceof Category)) {
                continue;
            }

            $category = $this->setPathForCategory($category);

            $md = $em->getClassMetadata(\get_class($category));
            $uow->recomputeSingleEntityChangeSet($md$category);
        }

        // Entity updates         foreach ($uow->getScheduledEntityUpdates() as $category) {
            if (!($category instanceof Category)) {
                continue;
            }

            $changeSet = $uow->getEntityChangeSet($category);

            
public function getEntities(): array
    {
        return $this->queryBuilder->getQuery()->execute();
    }

    public function getEntitiesByIds(string $identifier, array $values): array
    {
        if (null !== $this->queryBuilder->getMaxResults() || 0 < (int) $this->queryBuilder->getFirstResult()) {
            // an offset or a limit would apply on results including the where clause with submitted id values             // that could make invalid choices valid             $choices = [];
            $metadata = $this->queryBuilder->getEntityManager()->getClassMetadata(current($this->queryBuilder->getRootEntities()));

            foreach ($this->getEntities() as $entity) {
                if (\in_array((string) current($metadata->getIdentifierValues($entity))$values, true)) {
                    $choices[] = $entity;
                }
            }

            return $choices;
        }

        $qb = clone $this->queryBuilder;
        
$ids = $classMetadata->getIdentifierFieldNames();
        $idType = $classMetadata->getTypeOfField(current($ids));

        $this->om = $om;
        $this->classMetadata = $classMetadata;
        $this->singleId = 1 === \count($ids);
        $this->intId = $this->singleId && \in_array($idType['integer', 'smallint', 'bigint']);
        $this->idField = current($ids);

        // single field association are resolved, since the schema column could be an int         if ($this->singleId && $classMetadata->hasAssociation($this->idField)) {
            $this->associationIdReader = new self($om$om->getClassMetadata(
                $classMetadata->getAssociationTargetClass($this->idField)
            ));

            $this->singleId = $this->associationIdReader->isSingleId();
            $this->intId = $this->associationIdReader->isIntId();
        }
    }

    /** * Returns whether the class has a single-column ID. */
    
Home | Imprint | This part of the site doesn't use cookies.