Transform a doctrine2 metadata into generator metadata

@param  ClassMetadataInfo           $metadata Concret metadata
@return MetadataDataObjectDoctrine2
777281
private function hydrateDataObject(ClassMetadata $metadata, array $parentName = array())
    {
        $dataObject = new MetadataDataObjectDoctrine2(
            new MetaDataColumnCollection(),
            new MetaDataRelationCollection()
        );

        $columnDataObject = new MetaDataColumn();

        foreach ($metadata->fieldMappings as $field => $columnMetadata) {
            $column = clone $columnDataObject;
            $column->setName($field)
                   ->setType($columnMetadata['type'])
                   ->setLength(isset($columnMetadata['length']) === true ? $columnMetadata['length'] : null)
                   ->setNullable($columnMetadata['nullable'])
                   ->setPrimaryKey((in_array($field, $metadata->identifier) === true ? true : false));

            $dataObject->appendColumn($column);
        }

        $dataObject = $this->hydrateAssociation($metadata, $dataObject, $parentName);

        $dataObject->setName($metadata->name);

        return $dataObject;
    }
894533
public function generate($namespace, $basePath, ClassMetadata $metadata)
    {
        $entityName = $this->getEntityNameFromMetadata($metadata);
        $fileName = sprintf(
            '%s/Admin/%sAdmin.php',
            $basePath,
            $entityName
        );

        $baseAdminClass = 'Sonata\AdminBundle\Admin\Admin';
        if (class_exists('Sonata\AdminBundle\Admin\AbstractAdmin')) {
            $baseAdminClass = 'Sonata\AdminBundle\Admin\AbstractAdmin';
        }

        $parameters = array(
            'namespace' => $namespace,
            'entityName' => $entityName,
            'metadata' => $metadata,
            'render_associations' => array(ClassMetadata::MANY_TO_ONE),
            'base_admin_class' => $baseAdminClass,
        );

        return $this->renderFile('admin.php.twig', $fileName, $parameters);
    }
654040
public function loadMetadataForClass($className, ClassMetadata $metadata)
    {
        foreach ($this->getJoinEntityConfigCollection() as $targetClassName => $config) {
            if ($this->getAuditObjectManager()
                ->getRepository(Entity\AuditEntity::class)
                ->generateClassName($targetClassName) == $className
            ) {
                $foundClassName = true;
                break;
            }
        }

        // @codeCoverageIgnoreStart
        if (! $foundClassName) {
            return false;
        }
        // @codeCoverageIgnoreEnd

        $metadataFactory = $this->getObjectManager()->getMetadataFactory();
        $builder = new ClassMetadataBuilder($metadata);
        $metadata = $metadataFactory->getMetadataFor($config['ownerEntity']);

        foreach ($metadata->getAssociationMappings() as $mapping) {
            if (isset($mapping['joinTable'])) {
                if ($mapping['joinTable']['name'] == $config['tableName']) {
                    $foundJoinEntity = true;
                    break;
                }
            }
        }

        // @codeCoverageIgnoreStart
        if (! $foundJoinEntity) {
            throw new Exception(
                'joinTable '
                . $targetClassName
                . ' not found by tableName '
                . $config['tableName']
                . ' on ownerEntity: '
                . $config['ownerEntity']
            );
        }
        // @codeCoverageIgnoreEnd

        $fields = [];
        foreach ($mapping['joinTable']['joinColumns'] as $column) {
            $column['dataType'] = $this->getObjectManager()
                ->getClassMetadata($mapping['sourceEntity'])
                ->getTypeOfField($column['referencedColumnName']);
            $fields[] = $column;
        }
        foreach ($mapping['joinTable']['inverseJoinColumns'] as $column) {
            $column['dataType'] = $this->getObjectManager()
                ->getClassMetadata($mapping['targetEntity'])
                ->getTypeOfField($column['referencedColumnName']);
            $fields[] = $column;
        }

        $identifiers = [];
        foreach ($fields as $field) {
            $builder->addField(
                $field['name'],
                $field['dataType'],
                [
                // 'nullable' => $config['nullable'],
                    'columnName' => $field['name'],
                    'id' => true,
                ]
            );
        }

        $association = $builder->createManyToOne('revisionEntity', Entity\RevisionEntity::class);
        $association->makePrimaryKey();
        $association->build();

        $builder->setTable(
            $this->getAuditOptions()->getAuditTableNamePrefix()
            . $config['tableName']
            . $this->getAuditOptions()->getAuditTableNameSuffix()
        );
    }
310687
public function setMetadata(\TechPromux\DynamicQueryBundle\Entity\Metadata $metadata)
    {
        $this->metadata = $metadata;

        return $this;
    }
906678
public function fromData(array $metaData): ModuleConfiguration
    {
        $this->validateParameterFormat($metaData);

        $this->validator->validate(
            $metaData[MetaDataProvider::METADATA_FILEPATH],
            $metaData[MetaDataProvider::METADATA_METADATA_VERSION],
            $metaData[MetaDataProvider::METADATA_MODULE_DATA]
        );

        $mappedData = $this->getMappedData(
            $metaData[MetaDataProvider::METADATA_MODULE_DATA],
            $metaData[MetaDataProvider::METADATA_PATH],
            $metaData[MetaDataProvider::METADATA_CHECKSUM]
        );

        $moduleConfiguration = new ModuleConfiguration();
        $moduleConfiguration
            ->setMetaDataCheckSum($mappedData[MetaDataProvider::METADATA_CHECKSUM])
            ->setId($mappedData[MetaDataProvider::METADATA_ID])
            ->setTitle($mappedData[MetaDataProvider::METADATA_TITLE])
            ->setDescription($mappedData[MetaDataProvider::METADATA_DESCRIPTION])
            ->setLang($mappedData[MetaDataProvider::METADATA_LANG])
            ->setThumbnail($mappedData[MetaDataProvider::METADATA_THUMBNAIL])
            ->setAuthor($mappedData[MetaDataProvider::METADATA_AUTHOR])
            ->setUrl($mappedData[MetaDataProvider::METADATA_URL])
            ->setEmail($mappedData[MetaDataProvider::METADATA_EMAIL])
            ->setSettings($mappedData[MetaDataProvider::METADATA_SETTINGS]);

        return $moduleConfiguration;
    }
598848
private function mapTranslatable(ClassMetadata $metadata)
    {
        // In the case A -> B -> TranslatableInterface, B might not have mapping defined as it
        // is probably defined in A, so in that case, we just return.
        if (!isset($this->configs[$metadata->name])) {
            return;
        }

        $metadata->mapOneToMany([
            'fieldName'     => 'translations',
            'targetEntity'  => $this->configs[$metadata->name],
            'mappedBy'      => 'translatable',
            'fetch'         => ClassMetadataInfo::FETCH_EXTRA_LAZY,
            'indexBy'       => 'locale',
            'cascade'       => ['persist', 'merge', 'refresh', 'remove'],
            'orphanRemoval' => true,
        ]);
    }
1229593
private function getFieldsFromMetadata(ClassMetadataInfo $metadata)
    {
        $fields = (array) $metadata->getFieldNames();

        // Remove the primary key field if it's not managed manually
        if ($metadata->isIdGeneratorAuto()) {
            $fields = array_diff($fields, array($metadata->identifier));
        }

        return $fields;
    }
806756
protected function generateAssociationMappingPropertyDocBlock(array $associationMapping, ClassMetadataInfo $metadata)
    {
        $lines = array();
        $lines[] = $this->spaces . '/**';

        if ($associationMapping['type'] & ClassMetadataInfo::TO_MANY) {
            $lines[] = $this->spaces . ' * @var \Doctrine\Common\Collections\Collection';
        } else {
            $lines[] = $this->spaces . ' * @var \\' . ltrim($associationMapping['targetEntity'], '\\');
        }

        if ($this->generateAnnotations) {
            $lines[] = $this->spaces . ' *';

            if (isset($associationMapping['id']) && $associationMapping['id']) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'Id';

                if ($generatorType = $this->getIdGeneratorTypeString($metadata->generatorType)) {
                    $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'GeneratedValue(strategy="' . $generatorType . '")';
                }
            }

            $type = null;
            switch ($associationMapping['type']) {
                case ClassMetadataInfo::ONE_TO_ONE:
                    $type = 'OneToOne';
                    break;
                case ClassMetadataInfo::MANY_TO_ONE:
                    $type = 'ManyToOne';
                    break;
                case ClassMetadataInfo::ONE_TO_MANY:
                    $type = 'OneToMany';
                    break;
                case ClassMetadataInfo::MANY_TO_MANY:
                    $type = 'ManyToMany';
                    break;
            }
            $typeOptions = array();

            if (isset($associationMapping['targetEntity'])) {
                $typeOptions[] = 'targetEntity="' . $associationMapping['targetEntity'] . '"';
            }

            if (isset($associationMapping['inversedBy'])) {
                $typeOptions[] = 'inversedBy="' . $associationMapping['inversedBy'] . '"';
            }

            if (isset($associationMapping['mappedBy'])) {
                $typeOptions[] = 'mappedBy="' . $associationMapping['mappedBy'] . '"';
            }

            if ($associationMapping['cascade']) {
                $cascades = array();

                if ($associationMapping['isCascadePersist']) $cascades[] = '"persist"';
                if ($associationMapping['isCascadeRemove']) $cascades[] = '"remove"';
                if ($associationMapping['isCascadeDetach']) $cascades[] = '"detach"';
                if ($associationMapping['isCascadeMerge']) $cascades[] = '"merge"';
                if ($associationMapping['isCascadeRefresh']) $cascades[] = '"refresh"';

                if (count($cascades) === 5) {
                    $cascades = array('"all"');
                }

                $typeOptions[] = 'cascade={' . implode(',', $cascades) . '}';
            }

            if (isset($associationMapping['orphanRemoval']) && $associationMapping['orphanRemoval']) {
                $typeOptions[] = 'orphanRemoval=' . ($associationMapping['orphanRemoval'] ? 'true' : 'false');
            }

            if (isset($associationMapping['fetch']) && $associationMapping['fetch'] !== ClassMetadataInfo::FETCH_LAZY) {
                $fetchMap = array(
                    ClassMetadataInfo::FETCH_EXTRA_LAZY => 'EXTRA_LAZY',
                    ClassMetadataInfo::FETCH_EAGER      => 'EAGER',
                );

                $typeOptions[] = 'fetch="' . $fetchMap[$associationMapping['fetch']] . '"';
            }

            $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . '' . $type . '(' . implode(', ', $typeOptions) . ')';

            if (isset($associationMapping['joinColumns']) && $associationMapping['joinColumns']) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinColumns({';

                $joinColumnsLines = array();

                foreach ($associationMapping['joinColumns'] as $joinColumn) {
                    if ($joinColumnAnnot = $this->generateJoinColumnAnnotation($joinColumn)) {
                        $joinColumnsLines[] = $this->spaces . ' *   ' . $joinColumnAnnot;
                    }
                }

                $lines[] = implode(",\n", $joinColumnsLines);
                $lines[] = $this->spaces . ' * })';
            }

            if (isset($associationMapping['joinTable']) && $associationMapping['joinTable']) {
                $joinTable = array();
                $joinTable[] = 'name="' . $associationMapping['joinTable']['name'] . '"';

                if (isset($associationMapping['joinTable']['schema'])) {
                    $joinTable[] = 'schema="' . $associationMapping['joinTable']['schema'] . '"';
                }

                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'JoinTable(' . implode(', ', $joinTable) . ',';
                $lines[] = $this->spaces . ' *   joinColumns={';

                $joinColumnsLines = array();

                foreach ($associationMapping['joinTable']['joinColumns'] as $joinColumn) {
                    $joinColumnsLines[] = $this->spaces . ' *     ' . $this->generateJoinColumnAnnotation($joinColumn);
                }

                $lines[] = implode(",". PHP_EOL, $joinColumnsLines);
                $lines[] = $this->spaces . ' *   },';
                $lines[] = $this->spaces . ' *   inverseJoinColumns={';

                $inverseJoinColumnsLines = array();

                foreach ($associationMapping['joinTable']['inverseJoinColumns'] as $joinColumn) {
                    $inverseJoinColumnsLines[] = $this->spaces . ' *     ' . $this->generateJoinColumnAnnotation($joinColumn);
                }

                $lines[] = implode(",". PHP_EOL, $inverseJoinColumnsLines);
                $lines[] = $this->spaces . ' *   }';
                $lines[] = $this->spaces . ' * )';
            }

            if (isset($associationMapping['orderBy'])) {
                $lines[] = $this->spaces . ' * @' . $this->annotationsPrefix . 'OrderBy({';

                foreach ($associationMapping['orderBy'] as $name => $direction) {
                    $lines[] = $this->spaces . ' *     "' . $name . '"="' . $direction . '",';
                }

                $lines[count($lines) - 1] = substr($lines[count($lines) - 1], 0, strlen($lines[count($lines) - 1]) - 1);
                $lines[] = $this->spaces . ' * })';
            }
        }

        $lines[] = $this->spaces . ' */';

        return implode("\n", $lines);
    }
593587
public function getMetadataFor($className)
    {
        if (!$this->hasMetadataFor($className)) {
            $metadata = new ClassMetadata($className);
            $this->populateMetadata($metadata);
            $this->setMetadataFor($className, $metadata);
        }

        return $this->metadata[$className];
    }
332421
public function getMetadataFor($className)
    {
        if (!isset($this->metadata[$className])) {
            $reflectionClass = ClassUtils::newReflectionClass($className);
            $this->metadata[$className] = $this->getClassMetadata($reflectionClass);
        }

        return $this->metadata[$className];
    }
822922
private function convertColumns($className, array $model, ClassMetadataInfo $metadata)
    {
        $id = false;

        if (isset($model['columns']) && $model['columns']) {
            foreach ($model['columns'] as $name => $column) {
                $fieldMapping = $this->convertColumn($className, $name, $column, $metadata);

                if (isset($fieldMapping['id']) && $fieldMapping['id']) {
                    $id = true;
                }
            }
        }

        if ( ! $id) {
            $fieldMapping = array(
                'fieldName' => 'id',
                'columnName' => 'id',
                'type' => 'integer',
                'id' => true
            );
            $metadata->mapField($fieldMapping);
            $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO);
        }
    }
189686
private function doctrine2MetadataToGeneratorMetadata(array $metadataCollection)
    {
        $metaDataCollection = new MetaDataCollection();

        foreach ($metadataCollection as $metadata) {
            $metaDataCollection->append(
                $this->hydrateDataObject($metadata)
            );
        }

        return $metaDataCollection;
    }
962435
protected function generateEntityAssociationMappingProperties(ClassMetadataInfo $metadata)
    {
        $lines = array();

        foreach ($metadata->associationMappings as $associationMapping) {
            if ($this->hasProperty($associationMapping['fieldName'], $metadata)) {
                continue;
            }

            $lines[] = $this->generateAssociationMappingPropertyDocBlock($associationMapping, $metadata);
            $lines[] = $this->spaces . $this->fieldVisibility . ' $' . $associationMapping['fieldName']
                     . ($associationMapping['type'] == 'manyToMany' ? ' = array()' : null) . ";\n";
        }

        return implode("\n", $lines);
    }
113136
public function getMetadataFor($className)
    {
        if (isset($this->transformMetadata[$className])) {
            return $this->transformMetadata[$className];
        }

        $class = $this->wrapped->getMetadataFor($className);

        if (in_array($className, $this->classNames)) {
            $class = $this->transformMetadata($class);
            $this->transformMetadata[$className] = $class;
        }

        return $class;
    }
1241414
private function generateDocumentBody(array $metadata)
    {
        $lines = [];

        if ($properties = $this->generateDocumentProperties($metadata)) {
            $lines[] = $properties;
        }

        if ($this->hasMultipleEmbedded($metadata)) {
            $lines[] = $this->generateDocumentConstructor($metadata);
        }

        if ($methods = $this->generateDocumentMethods($metadata)) {
            $lines[] = $methods;
        }

        return rtrim(implode("\n", $lines));
    }
474131
private function getFieldsFromEntityMetadata(ClassMetadataInfo $metadata)
    {
        $fields = (array) $metadata->fieldNames;

        // Remove the primary key field if it's not managed manually
        if (!$metadata->isIdentifierNatural()) {
            $fields = array_diff($fields, $metadata->identifier);
        }

        return $fields;
    }
570115
protected function generateEntityDocBlock(ClassMetadataInfo $metadata)
    {
        $lines = array();
        $lines[] = '/**';
        $lines[] = ' * ' . $this->getClassName($metadata);

        if ($this->generateAnnotations) {
            $lines[] = ' *';

            $methods = array(
                'generateTableAnnotation',
                'generateInheritanceAnnotation',
                'generateDiscriminatorColumnAnnotation',
                'generateDiscriminatorMapAnnotation',
                'generateEntityAnnotation',
            );

            foreach ($methods as $method) {
                if ($code = $this->$method($metadata)) {
                    $lines[] = ' * ' . $code;
                }
            }

            if (isset($metadata->lifecycleCallbacks) && $metadata->lifecycleCallbacks) {
                $lines[] = ' * @' . $this->annotationsPrefix . 'HasLifecycleCallbacks';
            }
        }

        $lines[] = ' */';

        return implode("\n", $lines);
    }