Display all the mapping information for a single Entity.

@param string                 $entityName    Full or partial entity class name
@param EntityManagerInterface $entityManager
@param OutputInterface        $output
480485
private function displayEntity($entityName, EntityManagerInterface $entityManager, OutputInterface $output)
    {
        $table = new Table($output);

        $table->setHeaders(array('Field', 'Value'));

        $metadata = $this->getClassMetadata($entityName, $entityManager);

        array_map(
            array($table, 'addRow'),
            array_merge(
                array(
                    $this->formatField('Name', $metadata->name),
                    $this->formatField('Root entity name', $metadata->rootEntityName),
                    $this->formatField('Custom generator definition', $metadata->customGeneratorDefinition),
                    $this->formatField('Custom repository class', $metadata->customRepositoryClassName),
                    $this->formatField('Mapped super class?', $metadata->isMappedSuperclass),
                    $this->formatField('Embedded class?', $metadata->isEmbeddedClass),
                    $this->formatField('Parent classes', $metadata->parentClasses),
                    $this->formatField('Sub classes', $metadata->subClasses),
                    $this->formatField('Embedded classes', $metadata->subClasses),
                    $this->formatField('Named queries', $metadata->namedQueries),
                    $this->formatField('Named native queries', $metadata->namedNativeQueries),
                    $this->formatField('SQL result set mappings', $metadata->sqlResultSetMappings),
                    $this->formatField('Identifier', $metadata->identifier),
                    $this->formatField('Inheritance type', $metadata->inheritanceType),
                    $this->formatField('Discriminator column', $metadata->discriminatorColumn),
                    $this->formatField('Discriminator value', $metadata->discriminatorValue),
                    $this->formatField('Discriminator map', $metadata->discriminatorMap),
                    $this->formatField('Generator type', $metadata->generatorType),
                    $this->formatField('Table', $metadata->table),
                    $this->formatField('Composite identifier?', $metadata->isIdentifierComposite),
                    $this->formatField('Foreign identifier?', $metadata->containsForeignIdentifier),
                    $this->formatField('Sequence generator definition', $metadata->sequenceGeneratorDefinition),
                    $this->formatField('Table generator definition', $metadata->tableGeneratorDefinition),
                    $this->formatField('Change tracking policy', $metadata->changeTrackingPolicy),
                    $this->formatField('Versioned?', $metadata->isVersioned),
                    $this->formatField('Version field', $metadata->versionField),
                    $this->formatField('Read only?', $metadata->isReadOnly),

                    $this->formatEntityListeners($metadata->entityListeners),
                ),
                array($this->formatField('Association mappings:', '')),
                $this->formatMappings($metadata->associationMappings),
                array($this->formatField('Field mappings:', '')),
                $this->formatMappings($metadata->fieldMappings)
            )
        );

        $table->render();
    }
880640
protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine.orm.entity_manager');

        // disable the CustomFieldLinkedEntityListener during the execution of the command (to prevent loops)
        $listenerInst = null;
        foreach ($em->getEventManager()->getListeners() as $event => $listeners) {
            foreach ($listeners as $hash => $listener) {
                if ($listener instanceof \CubeTools\CubeCustomFieldsBundle\EventListener\CustomFieldLinkedEntityListener) {
                    $listenerInst = $listener;
                    break 2;
                }
            }
        }
        $evm = $em->getEventManager();
        $evm->removeEventListener(array('onFlush'), $listenerInst);

        // datetime custom fields
        $datetimeCf = $em->getRepository('CubeCustomFieldsBundle:DatetimeCustomField')->findAll();
        $this->updateCfEntities($datetimeCf);
        $em->flush();

        // text custom fields
        $textCf = $em->getRepository('CubeCustomFieldsBundle:TextCustomField')->findAll();
        $this->updateCfEntities($textCf);
        $em->flush();

        // textarea custom fields
        $textareaCf = $em->getRepository('CubeCustomFieldsBundle:TextareaCustomField')->findAll();
        $this->updateCfEntities($textareaCf);
        $em->flush();

        // entity custom fields
        $entityCf = $em->getRepository('CubeCustomFieldsBundle:EntityCustomField')->findAll();
        $this->updateCfEntities($entityCf);
        $em->flush();
    }
826618
public function clearEntityManager($managerName = null)
    {
        if (null === $this->doctrine) {
            throw new \Exception('Doctrine is required');
        }

        if (null === $managerName) {
            $managerName = $this->doctrine->getDefaultConnectionName();
        }
        if (!array_key_exists($managerName, $this->snapshots)) {
            throw new \Exception('The snapshot was not done');
        }
        $snapshot = $this->snapshots[$managerName];

        $em = $this->doctrine->getManager($managerName);
        $identityMap = $em->getUnitOfWork()->getIdentityMap();
        foreach ($identityMap as $class => $objects) {
            foreach ($objects as $id => $object) {
                if (!array_key_exists($class, $snapshot) || !array_key_exists($id, $snapshot[$class])) {
                    $em->detach($object);
                }
            }
        }
    }
520829
public function addEntityListener($eventName, $class, $method)
    {
        $class    = $this->fullyQualifiedClassName($class);
        $listener = array(
            'class'  => $class,
            'method' => $method
        );

        if ( ! class_exists($class)) {
            throw MappingException::entityListenerClassNotFound($class, $this->name);
        }

        if ( ! method_exists($class, $method)) {
            throw MappingException::entityListenerMethodNotFound($class, $method, $this->name);
        }

        if (isset($this->entityListeners[$eventName]) && in_array($listener, $this->entityListeners[$eventName])) {
            throw MappingException::duplicateEntityListener($class, $method, $this->name);
        }

        $this->entityListeners[$eventName][] = $listener;
    }
777453
public function entityTo(string $propertyName)
    {
        $idString = implode(':', [$this->definition->getClassName(), __CLASS__, $this->relationCount++]);
        $this->readDefinition->relation($propertyName)
            ->asCustom(new EmbeddedObjectRelation($idString, new EmbeddedMapperProxy($this->mapper)));
    }
353818
protected function convertFields($entityName, &$entityMetadata)
    {
        //List of unmerged fields with default field defenitions in $outputMeta
        $unmergedFields = array(
            'name',
        );

        $outputMeta = array(
            'id' => array(
                'type' => Entity::ID,
                'dbType' => 'varchar'
            ),
            'name' => array(
                'type' => isset($entityMetadata['fields']['name']['type']) ? $entityMetadata['fields']['name']['type'] : Entity::VARCHAR,
                'notStorable' => true
            ),
            'deleted' => array(
                'type' => Entity::BOOL,
                'default' => false
            )
        );

        foreach ($entityMetadata['fields'] as $fieldName => $fieldParams) {
            if (empty($fieldParams['type'])) continue;

            /** check if "fields" option exists in $fieldMeta */
            $fieldTypeMetadata = $this->getMetadataHelper()->getFieldDefsByType($fieldParams);

            $fieldDefs = $this->convertField($entityName, $fieldName, $fieldParams, $fieldTypeMetadata);

            if ($fieldDefs !== false) {
                //push fieldDefs to the ORM metadata array
                if (isset($outputMeta[$fieldName]) && !in_array($fieldName, $unmergedFields)) {
                    $outputMeta[$fieldName] = array_merge($outputMeta[$fieldName], $fieldDefs);
                } else {
                    $outputMeta[$fieldName] = $fieldDefs;
                }
            }

            /** check and set the linkDefs from 'fields' metadata */
            if (isset($fieldTypeMetadata['linkDefs'])) {
                $linkDefs = $this->getMetadataHelper()->getLinkDefsInFieldMeta($entityName, $fieldParams, $fieldTypeMetadata['linkDefs']);
                if (isset($linkDefs)) {
                    if (!isset($entityMetadata['links'])) {
                        $entityMetadata['links'] = array();
                    }
                    $entityMetadata['links'] = Util::merge( array($fieldName => $linkDefs), $entityMetadata['links'] );
                }
            }
        }

        return $outputMeta;
    }
29525
protected function processMetadata(MetadatableInterface $entity, EntityManager $entityManager)
    {
        if (null === $entity->getMetadatas()) {
            return;
        }

        foreach ($entity->getMetadatas() as $metadata) {
            if ($metadata instanceof Metadata) {
                $metadata
                    ->setHash($this->getMetadatableManager()->generateHash($entity))
                    ->setObjectClassName($this->getMetadatableManager()->getObjectClassName($entity))
                    ->setObjectId($this->getMetadatableManager()->getObjectId($entity))
                    ->setObject($entity)
                ;
                $entityManager->persist($metadata);
            }
        }
    }
1265030
public function injectEntityManager(EntityManagerInterface $entityManager, ClassMetadata $classMetadata) : void
    {
        if ($entityManager !== self::$entityManager) {
            throw new RuntimeException(
                'Trying to use PersistentObject with different EntityManager instances. ' .
                'Was PersistentObject::setEntityManager() called?'
            );
        }

        $this->cm = $classMetadata;
    }
623981
private function hasField(EntityManager $em, $fieldName)
    {
        return (Boolean) $em->createNativeQuery(
            "SHOW FIELDS FROM usr WHERE Field = :field",
            (new ResultSetMapping())->addScalarResult('Field', 'Field')
        )->setParameter(':field', $fieldName)->getOneOrNullResult();
    }
560459
public function getRepository(EntityManagerInterface $entityManager, $className) {
		if(!isset($this->repositories[$className])) {
			$this->repositories[$className] = $this->generateRepository($entityManager, $className);
		}
		return $this->repositories[$className];
	}
1256620
protected function execute(InputInterface $input, OutputInterface $output): void
    {
        $output->writeln([
            '----------------',
            'Domain entity generator',
            '----------------',
            ''
        ]);

        $helper      = $this->getHelper('question');
        $questionSet = $this->createQuestionSet();
        $entityName  = $helper->ask($input, $output, $questionSet['entityName']);

        do {
            $propertyNames[] = $helper->ask($input, $output, $questionSet['propertyName']);
            $propertyTypes[] = $helper->ask($input, $output, $questionSet['propertyType']);
        } while ($helper->ask($input, $output, $questionSet['continue']));

        $properties = array_combine($propertyNames, $propertyTypes);

        $configuration   = $this->appConfiguration->getConfiguration();
        $entityNamespace = $configuration['framework']['root_namespace'] . 'Domain\Entity';

        $entityData = [
            'namespace'  => $entityNamespace,
            'class'      => $entityName,
            'properties' => $properties
        ];

        (new EntityGenerator($entityData))->generate();

        $output->writeln('Entity generated successfully!');
    }
193263
public static function generateMap($entities, $entityId, $entityClass)
    {
        $entityMap = [];
        foreach ($entities as $entity) {
            if ($entity instanceof $entityClass) {
                $entityObject = $entity;
            } else {
                $entityObject = new $entityClass;
                foreach ($entity as $key => $value) {
                    $propSetter = 'set'.ucfirst($key);
                    if (method_exists($entityObject, $propSetter)) {
                        $entityObject->$propSetter($value);
                    }
                }
            }

            if (is_null($entityId)) {
                array_push($entityMap, $entityObject);
            } else {
                $propKeyGetter = 'get'.ucfirst($entityId);
                $entityMap[$entityObject->$propKeyGetter()] = $entityObject;
            }
        }

        return $entityMap;
    }
1161332
protected function execute(InputInterface $input, OutputInterface $output)
    {
        if (null === $this->em) {
            $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
        }

        $configRepository = $this->em->getRepository('KunstmaanDashboardBundle:AnalyticsConfig');

        $configId = $input->getArgument('config') ? $input->getArgument('config') : false;

        try {
            $configRepository->flushConfig($configId);
            $output->writeln('<fg=green>Data flushed</fg=green>');
        } catch (\Exception $e) {
            $output->writeln('<fg=red>'.$e->getMessage().'</fg=red>');
        }
    }
900778
public function dumpIdentityMap(EntityManagerInterface $em)
    {
        $uow = $em->getUnitOfWork();
        $identityMap = $uow->getIdentityMap();

        $fh = fopen($this->file, "x+");
        if (count($identityMap) == 0) {
            fwrite($fh, "Flush Operation [".$this->context."] - Empty identity map.\n");
            return;
        }

        fwrite($fh, "Flush Operation [".$this->context."] - Dumping identity map:\n");
        foreach ($identityMap as $className => $map) {
            fwrite($fh, "Class: ". $className . "\n");

            foreach ($map as $entity) {
                fwrite($fh, " Entity: " . $this->getIdString($entity, $uow) . " " . spl_object_hash($entity)."\n");
                fwrite($fh, "  Associations:\n");

                $cm = $em->getClassMetadata($className);

                foreach ($cm->associationMappings as $field => $assoc) {
                    fwrite($fh, "   " . $field . " ");
                    $value = $cm->getFieldValue($entity, $field);

                    if ($assoc['type'] & ClassMetadata::TO_ONE) {
                        if ($value === null) {
                            fwrite($fh, " NULL\n");
                        } else {
                            if ($value instanceof Proxy && !$value->__isInitialized()) {
                                fwrite($fh, "[PROXY] ");
                            }

                            fwrite($fh, $this->getIdString($value, $uow) . " " . spl_object_hash($value) . "\n");
                        }
                    } else {
                        $initialized = !($value instanceof PersistentCollection) || $value->isInitialized();
                        if ($value === null) {
                            fwrite($fh, " NULL\n");
                        } elseif ($initialized) {
                            fwrite($fh, "[INITIALIZED] " . $this->getType($value). " " . count($value) . " elements\n");

                            foreach ($value as $obj) {
                                fwrite($fh, "    " . $this->getIdString($obj, $uow) . " " . spl_object_hash($obj)."\n");
                            }
                        } else {
                            fwrite($fh, "[PROXY] " . $this->getType($value) . " unknown element size\n");
                            foreach ($value->unwrap() as $obj) {
                                fwrite($fh, "    " . $this->getIdString($obj, $uow) . " " . spl_object_hash($obj)."\n");
                            }
                        }
                    }
                }
            }
        }

        fclose($fh);
    }
1269236
public function getRepository(EntityManagerInterface $entityManager, $entityName)
    {
        if (!in_array($entityName, $this->alreadyChecked) && isset($this->customEntyRepository[$entityName])) {
            $repositoryClass = $this->customEntyRepository[$entityName];
            if (!class_exists($repositoryClass)) {
                throw new \InvalidArgumentException(sprintf(
                    'Class %s does not exist. Cannot be used as %s custom repository.',
                    $repositoryClass,
                    $entityName
                ));
            }

            $metadata = $entityManager->getClassMetadata($entityName);
            $metadata->customRepositoryClassName = $repositoryClass;
        }

        $this->alreadyChecked[] = $entityName;

        return parent::getRepository($entityManager, $entityName);
    }
1079557
public function addEntityListener(string $eventName, string $class, string $method) : void
    {
        $listener = [
            'class'  => $class,
            'method' => $method,
        ];

        if (! class_exists($class)) {
            throw MappingException::entityListenerClassNotFound($class, $this->className);
        }

        if (! method_exists($class, $method)) {
            throw MappingException::entityListenerMethodNotFound($class, $method, $this->className);
        }

        if (isset($this->entityListeners[$eventName]) && in_array($listener, $this->entityListeners[$eventName], true)) {
            throw MappingException::duplicateEntityListener($class, $method, $this->className);
        }

        $this->entityListeners[$eventName][] = $listener;
    }
224271
protected function execute(InputInterface $input, OutputInterface $output): void
    {
        try {
            $this->checkOptions($input);
            $entityManager = $this->getEntityManager();

            /**
             * @var ClassMetadata[] $metadatas
             */
            $metadatas = $entityManager->getMetadataFactory()->getAllMetadata();
            $metadatas = MetadataFilter::filter($metadatas, $input->getOption('filter'));
            $this->relationsGenerator
                ->setPathToProjectRoot($input->getOption(AbstractCommand::OPT_PROJECT_ROOT_PATH))
                ->setProjectRootNamespace($input->getOption(AbstractCommand::OPT_PROJECT_ROOT_NAMESPACE));

            $output->writeln(
                '<comment>Starting relations generation for '
                . implode(
                    ' ',
                    $input->getOption('filter')
                ) . '</comment>'
            );
            $progress = new ProgressBar($output, count($metadatas));
            $progress::setFormatDefinition('custom', ' %current%/%max% -- %message%');
            $progress->start();
            foreach ($metadatas as $metadata) {
                $progress->setMessage('<comment>Generating for ' . $metadata->name . '</comment>');
                $this->relationsGenerator->generateRelationCodeForEntity($metadata->name);
                $progress->setMessage('<info>done</info>');
                $progress->advance();
            }
            $progress->finish();
            $output->writeln('completed');
        } catch (\Exception $e) {
            throw new DoctrineStaticMetaException(
                'Exception in ' . __METHOD__ . ': ' . $e->getMessage(),
                $e->getCode(),
                $e
            );
        }
    }