public function testPrefixAddedToSequence() { $this->metadata->setSequenceGeneratorDefinition(['sequenceName' => 'bar']); $this->metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); $tablePrefix = new TablePrefixListener('someprefix_'); $tablePrefix->loadClassMetadata($this->args); $this->assertEquals('someprefix_foo', $this->metadata->getTableName()); }
/** * @throws \InvalidArgumentException When the bundle doesn't end with Bundle (Example: "Bundle\MySampleBundle") */ protected function execute(InputInterface $input, OutputInterface $output) { $bundle = $this->getApplication()->getKernel()->getBundle($input->getArgument('bundle')); $entity = str_replace('/', '\\', $input->getArgument('entity')); $fullEntityClassName = $bundle->getNamespace() . '\\Entity\\' . $entity; $mappingType = $input->getOption('mapping-type'); $class = new ClassMetadataInfo($fullEntityClassName); $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); // Map the specified fields $fields = $input->getOption('fields'); if ($fields) { $e = explode(' ', $fields); foreach ($e as $value) { $e = explode(':', $value); $name = $e[0]; if (strlen($name)) { $type = isset($e[1]) ? $e[1] : 'string'; preg_match_all('/(.*)\\((.*)\\)/', $type, $matches); $type = isset($matches[1][0]) ? $matches[1][0] : $type; $length = isset($matches[2][0]) ? $matches[2][0] : null; $class->mapField(array('fieldName' => $name, 'type' => $type, 'length' => $length)); } } } // Setup a new exporter for the mapping type specified $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter($mappingType); $entityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $entity) . '.php'; if (file_exists($entityPath)) { throw new \RuntimeException(sprintf("Entity %s already exists.", $class->name)); } if ('annotation' === $mappingType) { $exporter->setEntityGenerator($this->getEntityGenerator()); $entityCode = $exporter->exportClassMetadata($class); $mappingPath = $mappingCode = false; } else { $mappingType = 'yaml' == $mappingType ? 'yml' : $mappingType; $mappingPath = $bundle->getPath() . '/Resources/config/doctrine/' . str_replace('\\', '.', $fullEntityClassName) . '.orm.' . $mappingType; $mappingCode = $exporter->exportClassMetadata($class); $entityGenerator = $this->getEntityGenerator(); $entityCode = $entityGenerator->generateEntityClass($class); if (file_exists($mappingPath)) { throw new \RuntimeException(sprintf("Cannot generate entity when mapping <info>%s</info> already exists", $mappingPath)); } } $output->writeln(sprintf('Generating entity for "<info>%s</info>"', $bundle->getName())); $output->writeln(sprintf(' > entity <comment>%s</comment> into <info>%s</info>', $fullEntityClassName, $entityPath)); if (!is_dir($dir = dirname($entityPath))) { mkdir($dir, 0777, true); } file_put_contents($entityPath, $entityCode); if ($mappingPath) { $output->writeln(sprintf(' > mapping into <info>%s</info>', $mappingPath)); if (!is_dir($dir = dirname($mappingPath))) { mkdir($dir, 0777, true); } file_put_contents($mappingPath, $mappingCode); } }
public static function loadMetadata(ClassMetadataInfo $metadata) { $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'string')); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_CUSTOM); $metadata->setCustomGeneratorDefinition(array('class' => 'Doctrine\\Tests\\ORM\\Functional\\Ticket\\DDC2415Generator')); $metadata->isMappedSuperclass = true; }
/** * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ public static function loadMetadata(ORM\ClassMetadataInfo $metadata) { $metadata->setTableName('page'); $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE); $metadata->setCustomRepositoryClass('Orm\\Repository\\PageRepository'); $metadata->addLifecycleCallback('setTemplatecontentChecksumOnUpdate', 'prePersist'); $metadata->addLifecycleCallback('setTemplatecontentChecksumOnUpdate', 'preUpdate'); $metadata->addLifecycleCallback('setLastupdateToNow', 'prePersist'); $metadata->addLifecycleCallback('setLastupdateToNow', 'preUpdate'); $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('id' => true, 'fieldName' => 'websiteid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'templateid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'mediaid', 'type' => 'string', 'length' => 255, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'description', 'type' => 'text')); $metadata->mapField(array('fieldName' => 'date', 'type' => 'bigint', 'length' => 20)); $metadata->mapField(array('fieldName' => 'innavigation', 'type' => 'smallint', 'length' => 1)); $metadata->mapField(array('fieldName' => 'navigationtitle', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'content', 'type' => 'text')); $metadata->mapField(array('fieldName' => 'templatecontent', 'type' => 'text')); $metadata->mapField(array('fieldName' => 'templatecontentchecksum', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'globalcontent', 'type' => 'text', 'nullable' => true)); $metadata->mapField(array('fieldName' => 'pagetype', 'type' => 'string', 'length' => 255, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'pageattributes', 'type' => 'text', 'nullable' => true)); $metadata->mapField(array('fieldName' => 'lastupdate', 'type' => 'bigint', 'default' => 0)); }
public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'id')); $metadata->mapField(array('fieldName' => 'value', 'type' => 'float')); $metadata->isMappedSuperclass = true; $metadata->setCustomRepositoryClass("Doctrine\\Tests\\Models\\DDC869\\DDC869PaymentRepository"); $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_AUTO); }
/** * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ public static function loadMetadata(ORM\ClassMetadataInfo $metadata) { $metadata->setTableName('user_status'); $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE); $metadata->setCustomRepositoryClass('Orm\\Repository\\UserStatusRepository'); $metadata->mapField(array('id' => true, 'fieldName' => 'userid', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('id' => true, 'fieldName' => 'authbackend', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'lastlogin', 'type' => 'datetime')); }
/** * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ public static function loadMetadata(ORM\ClassMetadataInfo $metadata) { $metadata->setTableName('user_opt_in'); $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE); $metadata->setCustomRepositoryClass('Orm\\Repository\\OptInRepository'); $metadata->mapField(array('id' => true, 'fieldName' => 'userid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('id' => true, 'unique' => true, 'fieldName' => 'code', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'timestamp', 'type' => 'datetime')); $metadata->mapField(array('fieldName' => 'mode', 'type' => 'string', 'length' => 100)); }
/** * @throws \InvalidArgumentException When the bundle doesn't end with Bundle (Example: "Bundle\MySampleBundle") */ protected function execute(InputInterface $input, OutputInterface $output) { if (!preg_match('/Bundle$/', $bundle = $input->getArgument('bundle'))) { throw new \InvalidArgumentException('The bundle name must end with Bundle. Example: "Bundle\\MySampleBundle".'); } $dirs = $this->container->get('kernel')->getBundleDirs(); $tmp = str_replace('\\', '/', $bundle); $namespace = str_replace('/', '\\', dirname($tmp)); $bundle = basename($tmp); if (!isset($dirs[$namespace])) { throw new \InvalidArgumentException(sprintf('Unable to initialize the bundle entity (%s not defined).', $namespace)); } $entity = $input->getArgument('entity'); $entityNamespace = $namespace . '\\' . $bundle . '\\Entity'; $fullEntityClassName = $entityNamespace . '\\' . $entity; $tmp = str_replace('\\', '/', $fullEntityClassName); $tmp = str_replace('/', '\\', dirname($tmp)); $className = basename($tmp); $mappingType = $input->getOption('mapping-type'); $mappingType = $mappingType ? $mappingType : 'xml'; $class = new ClassMetadataInfo($fullEntityClassName); $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); // Map the specified fields $fields = $input->getOption('fields'); if ($fields) { $e = explode(' ', $fields); foreach ($e as $value) { $e = explode(':', $value); $name = $e[0]; $type = isset($e[1]) ? $e[1] : 'string'; preg_match_all('/(.*)\\((.*)\\)/', $type, $matches); $type = isset($matches[1][0]) ? $matches[1][0] : $type; $length = isset($matches[2][0]) ? $matches[2][0] : null; $class->mapField(array('fieldName' => $name, 'type' => $type, 'length' => $length)); } } // Setup a new exporter for the mapping type specified $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter($mappingType); if ('annotation' === $mappingType) { $path = $dirs[$namespace] . '/' . $bundle . '/Entity/' . str_replace($entityNamespace . '\\', null, $fullEntityClassName) . '.php'; $exporter->setEntityGenerator($this->getEntityGenerator()); } else { $mappingType = 'yaml' == $mappingType ? 'yml' : $mappingType; $path = $dirs[$namespace] . '/' . $bundle . '/Resources/config/doctrine/metadata/orm/' . str_replace('\\', '.', $fullEntityClassName) . '.dcm.' . $mappingType; } $code = $exporter->exportClassMetadata($class); if (!is_dir($dir = dirname($path))) { mkdir($dir, 0777, true); } $output->writeln(sprintf('Generating entity for "<info>%s</info>"', $bundle)); $output->writeln(sprintf(' > generating <comment>%s</comment>', $fullEntityClassName)); file_put_contents($path, $code); }
/** * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ public static function loadMetadata(ORM\ClassMetadataInfo $metadata) { $metadata->setTableName('album'); $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE); $metadata->setCustomRepositoryClass('Orm\\Repository\\AlbumRepository'); $metadata->addLifecycleCallback('setLastupdateToNow', 'prePersist'); $metadata->addLifecycleCallback('setLastupdateToNow', 'preUpdate'); $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('id' => true, 'fieldName' => 'websiteid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'lastupdate', 'type' => 'bigint', 'default' => 0)); }
public function generateTranslatableEntity(BundleInterface $bundle, $translatableEntity, $translationEntity, $format, array $fields, array $translatableFields, $withRepository) { // configure the bundle (needed if the bundle does not contain any Entities yet) $config = $this->registry->getManager(null)->getConfiguration(); $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces())); $translatableEntityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $translatableEntity; $translationEntityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $translationEntity; $translatableEntityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $translatableEntity) . '.php'; if (file_exists($translatableEntityPath)) { throw new \RuntimeException(sprintf('Entity "%s" already exists.', $translatableEntityClass)); } $translatableClass = new ClassMetadataInfo($translatableEntityClass); $translationClass = new ClassMetadataInfo($translationEntityClass); if ($withRepository) { $translatableClass->customRepositoryClassName = $translatableEntityClass . 'Repository'; } $translatableClass->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $translatableClass->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); foreach ($fields as $field) { $translatableClass->mapField($field); } foreach ($translatableFields as $translatableField) { $translationClass->mapField($translatableField); } $entityGenerator = $this->getEntityGenerator(); $entityGenerator->setClassToExtend('Prezent\\Doctrine\\Translatable\\Entity\\AbstractTranslatable'); if ('annotation' === $format) { $entityGenerator->setGenerateAnnotations(true); $entityCode = $entityGenerator->generateTranslatableEntityClass($translatableClass, $translationClass); $mappingPath = $mappingCode = false; } else { $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter('yml' == $format ? 'yaml' : $format); $mappingPath = $bundle->getPath() . '/Resources/config/doctrine/' . str_replace('\\', '.', $translatableEntity) . '.orm.' . $format; if (file_exists($mappingPath)) { throw new \RuntimeException(sprintf('Cannot generate entity when mapping "%s" already exists.', $mappingPath)); } $mappingCode = $exporter->exportClassMetadata($translatableClass); $entityGenerator->setGenerateAnnotations(false); $entityCode = $entityGenerator->generateTranslatableEntityClass($translatableClass, $translationClass); } $this->filesystem->mkdir(dirname($translatableEntityPath)); file_put_contents($translatableEntityPath, $entityCode); if ($mappingPath) { $this->filesystem->mkdir(dirname($mappingPath)); file_put_contents($mappingPath, $mappingCode); } if ($withRepository) { $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\')); $this->getRepositoryGenerator()->writeEntityRepositoryClass($translatableClass->customRepositoryClassName, $path); } }
/** * @param Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ public static function loadMetadata(ORM\ClassMetadataInfo $metadata) { $metadata->setTableName('locks'); $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE); $metadata->setCustomRepositoryClass('Orm\\Repository\\LockRepository'); $metadata->mapField(array('fieldName' => 'userid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'runid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('id' => true, 'fieldName' => 'itemid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('id' => true, 'fieldName' => 'websiteid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('id' => true, 'fieldName' => 'type', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'starttime', 'type' => 'string', 'length' => 20)); $metadata->mapField(array('fieldName' => 'lastactivity', 'type' => 'string', 'length' => 20)); }
/** * Creates an entity. * * @static */ public static function create($name, $path, array $fields, $annotationPrefix = 'ORM\\') { self::$annotationPrefix = $annotationPrefix; self::$name = $name; self::$path = $path; self::$fields = $fields; $class = new ClassMetadataInfo(self::$name); $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); foreach (self::$fields as $field) { $class->mapField($field); } file_put_contents(self::$path, self::getEntityGenerator()->generateEntityClass($class)); }
/** * @param \Doctrine\ORM\Mapping\ClassMetadata $metadata */ public static function loadMetadata(\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata) { $metadata->setTableName('user_group'); $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadataInfo::GENERATOR_TYPE_NONE); $metadata->setCustomRepositoryClass('Orm\\Repository\\GroupRepository'); $metadata->addLifecycleCallback('setLastupdateToNow', 'prePersist'); $metadata->addLifecycleCallback('setLastupdateToNow', 'preUpdate'); $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('id' => true, 'fieldName' => 'websiteid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'rights', 'type' => 'text', 'nullable' => true)); $metadata->mapField(array('fieldName' => 'users', 'type' => 'text')); $metadata->mapField(array('fieldName' => 'lastupdate', 'type' => 'bigint', 'default' => 0)); }
/** * @param Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ public static function loadMetadata(ORM\ClassMetadataInfo $metadata) { $metadata->setTableName('action_log'); $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_IDENTITY); $metadata->setCustomRepositoryClass('Orm\\Repository\\ActionLogRepository'); $metadata->mapField(array('id' => true, 'fieldName' => 'logid', 'type' => 'integer', 'generatedValue' => true)); $metadata->mapField(array('fieldName' => 'websiteid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'id', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'timestamp', 'type' => 'string', 'length' => 20)); $metadata->mapField(array('fieldName' => 'userlogin', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'action', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'additionalinfo', 'type' => 'text', 'nullable' => true)); }
/** * @param Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ public static function loadMetadata(ORM\ClassMetadataInfo $metadata) { $metadata->setTableName('ticket'); $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE); $metadata->setCustomRepositoryClass('Orm\\Repository\\TicketRepository'); $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'timestamp', 'type' => 'integer', 'length' => 11)); $metadata->mapField(array('fieldName' => 'websiteid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'isredirect', 'type' => 'boolean')); $metadata->mapField(array('fieldName' => 'isget', 'type' => 'boolean')); $metadata->mapField(array('fieldName' => 'requestconfig', 'type' => 'text')); $metadata->mapField(array('fieldName' => 'ticketlifetime', 'type' => 'integer')); $metadata->mapField(array('fieldName' => 'remainingcalls', 'type' => 'integer')); $metadata->mapField(array('fieldName' => 'sessionlifetime', 'type' => 'integer', 'nullable' => true)); $metadata->mapField(array('fieldName' => 'credentials', 'type' => 'text', 'nullable' => true)); }
/** * @param BundleInterface $bundle * @param string $entity * @param string $format * @param array $fields * * @return EntityGeneratorResult * * @throws \Doctrine\ORM\Tools\Export\ExportException */ public function generate(BundleInterface $bundle, $entity, $format, array $fields) { // configure the bundle (needed if the bundle does not contain any Entities yet) $config = $this->registry->getManager(null)->getConfiguration(); $config->setEntityNamespaces(array_merge(array($bundle->getName() => $bundle->getNamespace() . '\\Entity'), $config->getEntityNamespaces())); $entityClass = $this->registry->getAliasNamespace($bundle->getName()) . '\\' . $entity; $entityPath = $bundle->getPath() . '/Entity/' . str_replace('\\', '/', $entity) . '.php'; if (file_exists($entityPath)) { throw new \RuntimeException(sprintf('Entity "%s" already exists.', $entityClass)); } $class = new ClassMetadataInfo($entityClass); $class->customRepositoryClassName = str_replace('\\Entity\\', '\\Repository\\', $entityClass) . 'Repository'; $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); foreach ($fields as $field) { $class->mapField($field); } $entityGenerator = $this->getEntityGenerator(); if ('annotation' === $format) { $entityGenerator->setGenerateAnnotations(true); $class->setPrimaryTable(array('name' => Inflector::tableize($entity))); $entityCode = $entityGenerator->generateEntityClass($class); $mappingPath = $mappingCode = false; } else { $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter('yml' == $format ? 'yaml' : $format); $mappingPath = $bundle->getPath() . '/Resources/config/doctrine/' . str_replace('\\', '.', $entity) . '.orm.' . $format; if (file_exists($mappingPath)) { throw new \RuntimeException(sprintf('Cannot generate entity when mapping "%s" already exists.', $mappingPath)); } $mappingCode = $exporter->exportClassMetadata($class); $entityGenerator->setGenerateAnnotations(false); $entityCode = $entityGenerator->generateEntityClass($class); } $entityCode = str_replace(array("@var integer\n", "@var boolean\n", "@param integer\n", "@param boolean\n", "@return integer\n", "@return boolean\n"), array("@var int\n", "@var bool\n", "@param int\n", "@param bool\n", "@return int\n", "@return bool\n"), $entityCode); $this->filesystem->mkdir(dirname($entityPath)); file_put_contents($entityPath, $entityCode); if ($mappingPath) { $this->filesystem->mkdir(dirname($mappingPath)); file_put_contents($mappingPath, $mappingCode); } $path = $bundle->getPath() . str_repeat('/..', substr_count(get_class($bundle), '\\')); $this->getRepositoryGenerator()->writeEntityRepositoryClass($class->customRepositoryClassName, $path); $repositoryPath = $path . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class->customRepositoryClassName) . '.php'; return new EntityGeneratorResult($entityPath, $repositoryPath, $mappingPath); }
public function testWriteEntityClass() { $metadata = new ClassMetadataInfo('EntityGeneratorBook'); $metadata->primaryTable['name'] = 'book'; $metadata->mapField(array('fieldName' => 'name', 'type' => 'string')); $metadata->mapField(array('fieldName' => 'status', 'type' => 'string', 'default' => 'published')); $metadata->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $metadata->mapOneToOne(array('fieldName' => 'author', 'targetEntity' => 'Doctrine\\Tests\\ORM\\Tools\\EntityGeneratorAuthor', 'mappedBy' => 'book')); $joinColumns = array(array('name' => 'author_id', 'referencedColumnName' => 'id')); $metadata->mapManyToMany(array('fieldName' => 'comments', 'targetEntity' => 'Doctrine\\Tests\\ORM\\Tools\\EntityGeneratorComment', 'joinTable' => array('name' => 'book_comment', 'joinColumns' => array(array('name' => 'book_id', 'referencedColumnName' => 'id')), 'inverseJoinColumns' => array(array('name' => 'comment_id', 'referencedColumnName' => 'id'))))); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); $this->_generator->writeEntityClass($metadata, __DIR__); $path = __DIR__ . '/EntityGeneratorBook.php'; $this->assertTrue(file_exists($path)); require_once $path; return $metadata; }
/** * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ public static function loadMetadata(ORM\ClassMetadataInfo $metadata) { $metadata->setTableName('user'); $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE); $metadata->setCustomRepositoryClass('Orm\\Repository\\UserRepository'); $metadata->addLifecycleCallback('setLastupdateToNow', 'prePersist'); $metadata->addLifecycleCallback('setLastupdateToNow', 'preUpdate'); $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'lastname', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'firstname', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'password', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'gender', 'type' => 'string', 'length' => 10, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'email', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'language', 'type' => 'string', 'length' => 10, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'issuperuser', 'type' => 'boolean')); $metadata->mapField(array('fieldName' => 'isdeletable', 'type' => 'boolean')); $metadata->mapField(array('fieldName' => 'lastupdate', 'type' => 'bigint', 'default' => 0)); }
public function generateBookEntityFixture() { $metadata = new ClassMetadataInfo($this->_namespace . '\\EntityGeneratorBook'); $metadata->namespace = $this->_namespace; $metadata->customRepositoryClassName = $this->_namespace . '\\EntityGeneratorBookRepository'; $metadata->table['name'] = 'book'; $metadata->mapField(array('fieldName' => 'name', 'type' => 'string')); $metadata->mapField(array('fieldName' => 'status', 'type' => 'string', 'default' => 'published')); $metadata->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $metadata->mapOneToOne(array('fieldName' => 'author', 'targetEntity' => 'Doctrine\\Tests\\ORM\\Tools\\EntityGeneratorAuthor', 'mappedBy' => 'book')); $joinColumns = array(array('name' => 'author_id', 'referencedColumnName' => 'id')); $metadata->mapManyToMany(array('fieldName' => 'comments', 'targetEntity' => 'Doctrine\\Tests\\ORM\\Tools\\EntityGeneratorComment', 'joinTable' => array('name' => 'book_comment', 'joinColumns' => array(array('name' => 'book_id', 'referencedColumnName' => 'id')), 'inverseJoinColumns' => array(array('name' => 'comment_id', 'referencedColumnName' => 'id'))))); $metadata->addLifecycleCallback('loading', 'postLoad'); $metadata->addLifecycleCallback('willBeRemoved', 'preRemove'); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); $this->_generator->writeEntityClass($metadata, $this->_tmpDir); return $metadata; }
public function loadMetadataForClass($className, ClassMetadataInfo $metadata) { if ($className === 'Mapping\\Fixture\\Unmapped\\Timestampable') { $id = array(); $id['fieldName'] = 'id'; $id['type'] = 'integer'; $id['nullable'] = false; $id['columnName'] = 'id'; $id['id'] = true; $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_AUTO')); $metadata->mapField($id); $created = array(); $created['fieldName'] = 'created'; $created['type'] = 'datetime'; $created['nullable'] = false; $created['columnName'] = 'created'; $metadata->mapField($created); } }
/** * {@inheritdoc} */ public function generate($resourceName, OutputInterface $output = null) { if (!$this->_initialized) { $this->buildDefaultConfiguration($resourceName, $output); } $entityClass = $this->configuration['namespace'] . '\\' . $this->model; $modelPath = $this->configuration['directory'] . '/' . $this->model . '.php'; if (file_exists($modelPath)) { $this->addError(sprintf('Model "%s" already exist.', $modelPath)); return false; } $class = new ClassMetadataInfo($entityClass); $class->isMappedSuperclass = true; $class->setPrimaryTable(array('name' => strtolower($this->model))); $class->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $class->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); foreach ($this->configuration['fields'] as $field) { $class->mapField($field); } $entityGenerator = $this->getEntityGenerator(); if ($this->configuration['with_interface']) { $fields = $this->getFieldsFromMetadata($class); $this->renderFile('model/ModelInterface.php.twig', $this->configuration['directory'] . '/' . $this->model . 'Interface.php', array('fields' => $fields, 'namespace' => $this->configuration['namespace'], 'class_name' => $this->model . 'Interface')); } $cme = new ClassMetadataExporter(); $exporter = $cme->getExporter('yml' == $this->configuration['format'] ? 'yaml' : $this->configuration['format']); $mappingPath = $this->bundle->getPath() . '/Resources/config/doctrine/model/' . $this->model . '.orm.' . $this->configuration['format']; if (file_exists($mappingPath)) { $this->addError(sprintf('Cannot generate model when mapping "%s" already exists.', $mappingPath)); return false; } $mappingCode = $exporter->exportClassMetadata($class); $entityGenerator->setGenerateAnnotations(false); $entityCode = $entityGenerator->generateEntityClass($class); file_put_contents($modelPath, $entityCode); if ($mappingPath) { $this->fileSystem->mkdir(dirname($mappingPath)); file_put_contents($mappingPath, $mappingCode); } $this->renderFile('model/Repository.php.twig', $this->bundle->getPath() . '/Doctrine/ORM/' . $this->model . 'Repository.php', array('namespace' => $this->bundle->getNamespace() . '\\Doctrine\\ORM', 'class_name' => $this->model . 'Repository')); $this->patchDependencyInjection(); }
/** * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ public static function loadMetadata(ORM\ClassMetadataInfo $metadata) { $metadata->setTableName('media_item'); $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE); $metadata->setCustomRepositoryClass('Orm\\Repository\\MediaRepository'); $metadata->addLifecycleCallback('setLastupdateToNow', 'prePersist'); $metadata->addLifecycleCallback('setLastupdateToNow', 'preUpdate'); $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('id' => true, 'fieldName' => 'websiteid', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'dateUploaded', 'type' => 'integer', 'length' => 11, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 255, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'filename', 'type' => 'string', 'length' => 255, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'extension', 'type' => 'string', 'length' => 255, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'size', 'type' => 'bigint', 'length' => 20, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'lastmod', 'type' => 'string', 'length' => 20, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'file', 'type' => 'string', 'length' => 255, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'type', 'type' => 'string', 'length' => 255, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'mimetype', 'type' => 'string', 'length' => 255, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'albumid', 'type' => 'string', 'length' => 100, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'lastupdate', 'type' => 'bigint', 'default' => 0)); }
/** * @param \Doctrine\ORM\Mapping\ClassMetadataInfo|\Orm\Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ public static function loadMetadata(ORM\ClassMetadataInfo $metadata) { $metadata->setTableName('website'); $metadata->setIdGeneratorType(ORM\ClassMetadataInfo::GENERATOR_TYPE_NONE); $metadata->setCustomRepositoryClass('Orm\\Repository\\WebsiteRepository'); $metadata->addLifecycleCallback('setLastupdateToNow', 'prePersist'); $metadata->addLifecycleCallback('setLastupdateToNow', 'preUpdate'); $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'shortid', 'type' => 'string', 'length' => 10)); $metadata->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 255)); $metadata->mapField(array('fieldName' => 'description', 'type' => 'text')); $metadata->mapField(array('fieldName' => 'navigation', 'type' => 'text')); $metadata->mapField(array('fieldName' => 'publishingenabled', 'type' => 'boolean', 'default' => false)); $metadata->mapField(array('fieldName' => 'publish', 'type' => 'text', 'nullable' => true)); $metadata->mapField(array('fieldName' => 'colorscheme', 'type' => 'text')); $metadata->mapField(array('fieldName' => 'resolutions', 'type' => 'text')); $metadata->mapField(array('fieldName' => 'version', 'type' => 'integer')); $metadata->mapField(array('fieldName' => 'home', 'type' => 'string', 'length' => 100)); $metadata->mapField(array('fieldName' => 'usedsetid', 'type' => 'string', 'length' => 100, 'nullable' => true)); $metadata->mapField(array('fieldName' => 'creationmode', 'type' => 'string', 'length' => 10, 'default' => 'full')); $metadata->mapField(array('fieldName' => 'ismarkedfordeletion', 'type' => 'boolean')); $metadata->mapField(array('fieldName' => 'lastupdate', 'type' => 'bigint', 'default' => 0)); }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadataInfo $metadata) { $xmlRoot = $this->getElement($className); if ($xmlRoot->getName() == 'entity') { if (isset($xmlRoot['repository-class'])) { $metadata->setCustomRepositoryClass((string) $xmlRoot['repository-class']); } if (isset($xmlRoot['read-only']) && $xmlRoot['read-only'] == "true") { $metadata->markReadOnly(); } } else { if ($xmlRoot->getName() == 'mapped-superclass') { $metadata->setCustomRepositoryClass(isset($xmlRoot['repository-class']) ? (string) $xmlRoot['repository-class'] : null); $metadata->isMappedSuperclass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); } } // Evaluate <entity...> attributes $table = array(); if (isset($xmlRoot['table'])) { $table['name'] = (string) $xmlRoot['table']; } $metadata->setPrimaryTable($table); // Evaluate named queries if (isset($xmlRoot['named-queries'])) { foreach ($xmlRoot->{'named-queries'}->{'named-query'} as $namedQueryElement) { $metadata->addNamedQuery(array('name' => (string) $namedQueryElement['name'], 'query' => (string) $namedQueryElement['query'])); } } /* not implemented specially anyway. use table = schema.table if (isset($xmlRoot['schema'])) { $metadata->table['schema'] = (string)$xmlRoot['schema']; }*/ if (isset($xmlRoot['inheritance-type'])) { $inheritanceType = (string) $xmlRoot['inheritance-type']; $metadata->setInheritanceType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceType)); if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { // Evaluate <discriminator-column...> if (isset($xmlRoot->{'discriminator-column'})) { $discrColumn = $xmlRoot->{'discriminator-column'}; $metadata->setDiscriminatorColumn(array('name' => isset($discrColumn['name']) ? (string) $discrColumn['name'] : null, 'type' => isset($discrColumn['type']) ? (string) $discrColumn['type'] : null, 'length' => isset($discrColumn['length']) ? (string) $discrColumn['length'] : null, 'columnDefinition' => isset($discrColumn['column-definition']) ? (string) $discrColumn['column-definition'] : null)); } else { $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255)); } // Evaluate <discriminator-map...> if (isset($xmlRoot->{'discriminator-map'})) { $map = array(); foreach ($xmlRoot->{'discriminator-map'}->{'discriminator-mapping'} as $discrMapElement) { $map[(string) $discrMapElement['value']] = (string) $discrMapElement['class']; } $metadata->setDiscriminatorMap($map); } } } // Evaluate <change-tracking-policy...> if (isset($xmlRoot['change-tracking-policy'])) { $metadata->setChangeTrackingPolicy(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::CHANGETRACKING_' . strtoupper((string) $xmlRoot['change-tracking-policy']))); } // Evaluate <indexes...> if (isset($xmlRoot->indexes)) { $metadata->table['indexes'] = array(); foreach ($xmlRoot->indexes->index as $index) { $columns = explode(',', (string) $index['columns']); if (isset($index['name'])) { $metadata->table['indexes'][(string) $index['name']] = array('columns' => $columns); } else { $metadata->table['indexes'][] = array('columns' => $columns); } } } // Evaluate <unique-constraints..> if (isset($xmlRoot->{'unique-constraints'})) { $metadata->table['uniqueConstraints'] = array(); foreach ($xmlRoot->{'unique-constraints'}->{'unique-constraint'} as $unique) { $columns = explode(',', (string) $unique['columns']); if (isset($unique['name'])) { $metadata->table['uniqueConstraints'][(string) $unique['name']] = array('columns' => $columns); } else { $metadata->table['uniqueConstraints'][] = array('columns' => $columns); } } } if (isset($xmlRoot->options)) { $metadata->table['options'] = $this->_parseOptions($xmlRoot->options->children()); } // Evaluate <field ...> mappings if (isset($xmlRoot->field)) { foreach ($xmlRoot->field as $fieldMapping) { $mapping = array('fieldName' => (string) $fieldMapping['name']); if (isset($fieldMapping['type'])) { $mapping['type'] = (string) $fieldMapping['type']; } if (isset($fieldMapping['column'])) { $mapping['columnName'] = (string) $fieldMapping['column']; } if (isset($fieldMapping['length'])) { $mapping['length'] = (int) $fieldMapping['length']; } if (isset($fieldMapping['precision'])) { $mapping['precision'] = (int) $fieldMapping['precision']; } if (isset($fieldMapping['scale'])) { $mapping['scale'] = (int) $fieldMapping['scale']; } if (isset($fieldMapping['unique'])) { $mapping['unique'] = (string) $fieldMapping['unique'] == "false" ? false : true; } if (isset($fieldMapping['nullable'])) { $mapping['nullable'] = (string) $fieldMapping['nullable'] == "false" ? false : true; } if (isset($fieldMapping['version']) && $fieldMapping['version']) { $metadata->setVersionMapping($mapping); } if (isset($fieldMapping['column-definition'])) { $mapping['columnDefinition'] = (string) $fieldMapping['column-definition']; } if (isset($fieldMapping->options)) { $mapping['options'] = $this->_parseOptions($fieldMapping->options->children()); } $metadata->mapField($mapping); } } // Evaluate <id ...> mappings $associationIds = array(); foreach ($xmlRoot->id as $idElement) { if ((bool) $idElement['association-key'] == true) { $associationIds[(string) $idElement['name']] = true; continue; } $mapping = array('id' => true, 'fieldName' => (string) $idElement['name']); if (isset($idElement['type'])) { $mapping['type'] = (string) $idElement['type']; } if (isset($idElement['column'])) { $mapping['columnName'] = (string) $idElement['column']; } if (isset($idElement['column-definition'])) { $mapping['columnDefinition'] = (string) $idElement['column-definition']; } $metadata->mapField($mapping); if (isset($idElement->generator)) { $strategy = isset($idElement->generator['strategy']) ? (string) $idElement->generator['strategy'] : 'AUTO'; $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . $strategy)); } // Check for SequenceGenerator/TableGenerator definition if (isset($idElement->{'sequence-generator'})) { $seqGenerator = $idElement->{'sequence-generator'}; $metadata->setSequenceGeneratorDefinition(array('sequenceName' => (string) $seqGenerator['sequence-name'], 'allocationSize' => (string) $seqGenerator['allocation-size'], 'initialValue' => (string) $seqGenerator['initial-value'])); } else { if (isset($idElement->{'table-generator'})) { throw MappingException::tableIdGeneratorNotImplemented($className); } } } // Evaluate <one-to-one ...> mappings if (isset($xmlRoot->{'one-to-one'})) { foreach ($xmlRoot->{'one-to-one'} as $oneToOneElement) { $mapping = array('fieldName' => (string) $oneToOneElement['field'], 'targetEntity' => (string) $oneToOneElement['target-entity']); if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; } if (isset($oneToOneElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . (string) $oneToOneElement['fetch']); } if (isset($oneToOneElement['mapped-by'])) { $mapping['mappedBy'] = (string) $oneToOneElement['mapped-by']; } else { if (isset($oneToOneElement['inversed-by'])) { $mapping['inversedBy'] = (string) $oneToOneElement['inversed-by']; } $joinColumns = array(); if (isset($oneToOneElement->{'join-column'})) { $joinColumns[] = $this->_getJoinColumnMapping($oneToOneElement->{'join-column'}); } else { if (isset($oneToOneElement->{'join-columns'})) { foreach ($oneToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinColumns[] = $this->_getJoinColumnMapping($joinColumnElement); } } } $mapping['joinColumns'] = $joinColumns; } if (isset($oneToOneElement->cascade)) { $mapping['cascade'] = $this->_getCascadeMappings($oneToOneElement->cascade); } if (isset($oneToOneElement['orphan-removal'])) { $mapping['orphanRemoval'] = (bool) $oneToOneElement['orphan-removal']; } $metadata->mapOneToOne($mapping); } } // Evaluate <one-to-many ...> mappings if (isset($xmlRoot->{'one-to-many'})) { foreach ($xmlRoot->{'one-to-many'} as $oneToManyElement) { $mapping = array('fieldName' => (string) $oneToManyElement['field'], 'targetEntity' => (string) $oneToManyElement['target-entity'], 'mappedBy' => (string) $oneToManyElement['mapped-by']); if (isset($oneToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . (string) $oneToManyElement['fetch']); } if (isset($oneToManyElement->cascade)) { $mapping['cascade'] = $this->_getCascadeMappings($oneToManyElement->cascade); } if (isset($oneToManyElement['orphan-removal'])) { $mapping['orphanRemoval'] = (bool) $oneToManyElement['orphan-removal']; } if (isset($oneToManyElement->{'order-by'})) { $orderBy = array(); foreach ($oneToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) { $orderBy[(string) $orderByField['name']] = (string) $orderByField['direction']; } $mapping['orderBy'] = $orderBy; } if (isset($oneToManyElement['index-by'])) { $mapping['indexBy'] = (string) $oneToManyElement['index-by']; } else { if (isset($oneToManyElement->{'index-by'})) { throw new \InvalidArgumentException("<index-by /> is not a valid tag"); } } $metadata->mapOneToMany($mapping); } } // Evaluate <many-to-one ...> mappings if (isset($xmlRoot->{'many-to-one'})) { foreach ($xmlRoot->{'many-to-one'} as $manyToOneElement) { $mapping = array('fieldName' => (string) $manyToOneElement['field'], 'targetEntity' => (string) $manyToOneElement['target-entity']); if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; } if (isset($manyToOneElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . (string) $manyToOneElement['fetch']); } if (isset($manyToOneElement['inversed-by'])) { $mapping['inversedBy'] = (string) $manyToOneElement['inversed-by']; } $joinColumns = array(); if (isset($manyToOneElement->{'join-column'})) { $joinColumns[] = $this->_getJoinColumnMapping($manyToOneElement->{'join-column'}); } else { if (isset($manyToOneElement->{'join-columns'})) { foreach ($manyToOneElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinColumns[] = $this->_getJoinColumnMapping($joinColumnElement); } } } $mapping['joinColumns'] = $joinColumns; if (isset($manyToOneElement->cascade)) { $mapping['cascade'] = $this->_getCascadeMappings($manyToOneElement->cascade); } $metadata->mapManyToOne($mapping); } } // Evaluate <many-to-many ...> mappings if (isset($xmlRoot->{'many-to-many'})) { foreach ($xmlRoot->{'many-to-many'} as $manyToManyElement) { $mapping = array('fieldName' => (string) $manyToManyElement['field'], 'targetEntity' => (string) $manyToManyElement['target-entity']); if (isset($manyToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . (string) $manyToManyElement['fetch']); } if (isset($manyToManyElement['orphan-removal'])) { $mapping['orphanRemoval'] = (bool) $manyToManyElement['orphan-removal']; } if (isset($manyToManyElement['mapped-by'])) { $mapping['mappedBy'] = (string) $manyToManyElement['mapped-by']; } else { if (isset($manyToManyElement->{'join-table'})) { if (isset($manyToManyElement['inversed-by'])) { $mapping['inversedBy'] = (string) $manyToManyElement['inversed-by']; } $joinTableElement = $manyToManyElement->{'join-table'}; $joinTable = array('name' => (string) $joinTableElement['name']); if (isset($joinTableElement['schema'])) { $joinTable['schema'] = (string) $joinTableElement['schema']; } foreach ($joinTableElement->{'join-columns'}->{'join-column'} as $joinColumnElement) { $joinTable['joinColumns'][] = $this->_getJoinColumnMapping($joinColumnElement); } foreach ($joinTableElement->{'inverse-join-columns'}->{'join-column'} as $joinColumnElement) { $joinTable['inverseJoinColumns'][] = $this->_getJoinColumnMapping($joinColumnElement); } $mapping['joinTable'] = $joinTable; } } if (isset($manyToManyElement->cascade)) { $mapping['cascade'] = $this->_getCascadeMappings($manyToManyElement->cascade); } if (isset($manyToManyElement->{'order-by'})) { $orderBy = array(); foreach ($manyToManyElement->{'order-by'}->{'order-by-field'} as $orderByField) { $orderBy[(string) $orderByField['name']] = (string) $orderByField['direction']; } $mapping['orderBy'] = $orderBy; } if (isset($manyToManyElement['index-by'])) { $mapping['indexBy'] = (string) $manyToManyElement['index-by']; } else { if (isset($manyToManyElement->{'index-by'})) { throw new \InvalidArgumentException("<index-by /> is not a valid tag"); } } $metadata->mapManyToMany($mapping); } } // Evaluate <lifecycle-callbacks...> if (isset($xmlRoot->{'lifecycle-callbacks'})) { foreach ($xmlRoot->{'lifecycle-callbacks'}->{'lifecycle-callback'} as $lifecycleCallback) { $metadata->addLifecycleCallback((string) $lifecycleCallback['method'], constant('Doctrine\\ORM\\Events::' . (string) $lifecycleCallback['type'])); } } }
public static function loadMetadata(ClassMetadataInfo $metadata) { $metadata->setInheritanceType(ClassMetadataInfo::INHERITANCE_TYPE_NONE); $metadata->setPrimaryTable(array('name' => 'cms_users')); $metadata->setChangeTrackingPolicy(ClassMetadataInfo::CHANGETRACKING_DEFERRED_IMPLICIT); $metadata->addLifecycleCallback('doStuffOnPrePersist', 'prePersist'); $metadata->addLifecycleCallback('doOtherStuffOnPrePersistToo', 'prePersist'); $metadata->addLifecycleCallback('doStuffOnPostPersist', 'postPersist'); $metadata->mapField(array('id' => true, 'fieldName' => 'id', 'type' => 'integer', 'columnName' => 'id')); $metadata->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 50, 'unique' => true, 'nullable' => true, 'columnName' => 'name')); $metadata->mapField(array('fieldName' => 'email', 'type' => 'string', 'columnName' => 'user_email', 'columnDefinition' => 'CHAR(32) NOT NULL')); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); $metadata->mapOneToOne(array('fieldName' => 'address', 'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Address', 'cascade' => array(0 => 'remove'), 'mappedBy' => NULL, 'inversedBy' => 'user', 'joinColumns' => array(0 => array('name' => 'address_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE', 'onUpdate' => 'CASCADE')), 'orphanRemoval' => false)); $metadata->mapOneToMany(array('fieldName' => 'phonenumbers', 'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Phonenumber', 'cascade' => array(1 => 'persist'), 'mappedBy' => 'user', 'orphanRemoval' => true, 'orderBy' => array('number' => 'ASC'))); $metadata->mapManyToMany(array('fieldName' => 'groups', 'targetEntity' => 'Doctrine\\Tests\\ORM\\Mapping\\Group', 'cascade' => array(0 => 'remove', 1 => 'persist', 2 => 'refresh', 3 => 'merge', 4 => 'detach'), 'mappedBy' => NULL, 'joinTable' => array('name' => 'cms_users_groups', 'joinColumns' => array(0 => array('name' => 'user_id', 'referencedColumnName' => 'id', 'unique' => false, 'nullable' => false)), 'inverseJoinColumns' => array(0 => array('name' => 'group_id', 'referencedColumnName' => 'id', 'columnDefinition' => 'INT NULL'))), 'orderBy' => NULL)); $metadata->table['uniqueConstraints'] = array('search_idx' => array('columns' => array('name', 'user_email'))); $metadata->table['indexes'] = array('name_idx' => array('columns' => array('name')), 0 => array('columns' => array('user_email'))); $metadata->setSequenceGeneratorDefinition(array('sequenceName' => 'tablename_seq', 'allocationSize' => 100, 'initialValue' => 1)); }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadataInfo $metadata) { $class = $metadata->getReflectionClass(); if (!$class) { // this happens when running annotation driver in combination with // static reflection services. This is not the nicest fix $class = new \ReflectionClass($metadata->name); } $classAnnotations = $this->_reader->getClassAnnotations($class); // Compatibility with Doctrine Common 3.x if ($classAnnotations && is_int(key($classAnnotations))) { foreach ($classAnnotations as $annot) { $classAnnotations[get_class($annot)] = $annot; } } // Evaluate Entity annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\Entity'])) { $entityAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\Entity']; if ($entityAnnot->repositoryClass !== null) { $metadata->setCustomRepositoryClass($entityAnnot->repositoryClass); } if ($entityAnnot->readOnly) { $metadata->markReadOnly(); } } else { if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\MappedSuperclass'])) { $mappedSuperclassAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\MappedSuperclass']; $metadata->setCustomRepositoryClass($mappedSuperclassAnnot->repositoryClass); $metadata->isMappedSuperclass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); } } // Evaluate Table annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\Table'])) { $tableAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\Table']; $primaryTable = array('name' => $tableAnnot->name, 'schema' => $tableAnnot->schema); if ($tableAnnot->indexes !== null) { foreach ($tableAnnot->indexes as $indexAnnot) { $primaryTable['indexes'][$indexAnnot->name] = array('columns' => $indexAnnot->columns); } } if ($tableAnnot->uniqueConstraints !== null) { foreach ($tableAnnot->uniqueConstraints as $uniqueConstraint) { $primaryTable['uniqueConstraints'][$uniqueConstraint->name] = array('columns' => $uniqueConstraint->columns); } } if ($tableAnnot->options !== null) { $primaryTable['options'] = $tableAnnot->options; } $metadata->setPrimaryTable($primaryTable); } // Evaluate NamedQueries annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\NamedQueries'])) { $namedQueriesAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\NamedQueries']; if (!is_array($namedQueriesAnnot->value)) { throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); } foreach ($namedQueriesAnnot->value as $namedQuery) { if (!$namedQuery instanceof \Doctrine\ORM\Mapping\NamedQuery) { throw new \UnexpectedValueException("@NamedQueries should contain an array of @NamedQuery annotations."); } $metadata->addNamedQuery(array('name' => $namedQuery->name, 'query' => $namedQuery->query)); } } // Evaluate InheritanceType annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\InheritanceType'])) { $inheritanceTypeAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\InheritanceType']; $metadata->setInheritanceType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::INHERITANCE_TYPE_' . $inheritanceTypeAnnot->value)); if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { // Evaluate DiscriminatorColumn annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorColumn'])) { $discrColumnAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorColumn']; $metadata->setDiscriminatorColumn(array('name' => $discrColumnAnnot->name, 'type' => $discrColumnAnnot->type, 'length' => $discrColumnAnnot->length, 'columnDefinition' => $discrColumnAnnot->columnDefinition)); } else { $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255)); } // Evaluate DiscriminatorMap annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorMap'])) { $discrMapAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\DiscriminatorMap']; $metadata->setDiscriminatorMap($discrMapAnnot->value); } } } // Evaluate DoctrineChangeTrackingPolicy annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\ChangeTrackingPolicy'])) { $changeTrackingAnnot = $classAnnotations['Doctrine\\ORM\\Mapping\\ChangeTrackingPolicy']; $metadata->setChangeTrackingPolicy(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::CHANGETRACKING_' . $changeTrackingAnnot->value)); } // Evaluate annotations on properties/fields foreach ($class->getProperties() as $property) { if ($metadata->isMappedSuperclass && !$property->isPrivate() || $metadata->isInheritedField($property->name) || $metadata->isInheritedAssociation($property->name)) { continue; } $mapping = array(); $mapping['fieldName'] = $property->getName(); // Check for JoinColummn/JoinColumns annotations $joinColumns = array(); if ($joinColumnAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\JoinColumn')) { $joinColumns[] = array('name' => $joinColumnAnnot->name, 'referencedColumnName' => $joinColumnAnnot->referencedColumnName, 'unique' => $joinColumnAnnot->unique, 'nullable' => $joinColumnAnnot->nullable, 'onDelete' => $joinColumnAnnot->onDelete, 'columnDefinition' => $joinColumnAnnot->columnDefinition); } else { if ($joinColumnsAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\JoinColumns')) { foreach ($joinColumnsAnnot->value as $joinColumn) { $joinColumns[] = array('name' => $joinColumn->name, 'referencedColumnName' => $joinColumn->referencedColumnName, 'unique' => $joinColumn->unique, 'nullable' => $joinColumn->nullable, 'onDelete' => $joinColumn->onDelete, 'columnDefinition' => $joinColumn->columnDefinition); } } } // Field can only be annotated with one of: // @Column, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany if ($columnAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Column')) { if ($columnAnnot->type == null) { throw MappingException::propertyTypeIsRequired($className, $property->getName()); } $mapping['type'] = $columnAnnot->type; $mapping['length'] = $columnAnnot->length; $mapping['precision'] = $columnAnnot->precision; $mapping['scale'] = $columnAnnot->scale; $mapping['nullable'] = $columnAnnot->nullable; $mapping['unique'] = $columnAnnot->unique; if ($columnAnnot->options) { $mapping['options'] = $columnAnnot->options; } if (isset($columnAnnot->name)) { $mapping['columnName'] = $columnAnnot->name; } if (isset($columnAnnot->columnDefinition)) { $mapping['columnDefinition'] = $columnAnnot->columnDefinition; } if ($idAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Id')) { $mapping['id'] = true; } if ($generatedValueAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\GeneratedValue')) { $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . $generatedValueAnnot->strategy)); } if ($versionAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Version')) { $metadata->setVersionMapping($mapping); } $metadata->mapField($mapping); // Check for SequenceGenerator/TableGenerator definition if ($seqGeneratorAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\SequenceGenerator')) { $metadata->setSequenceGeneratorDefinition(array('sequenceName' => $seqGeneratorAnnot->sequenceName, 'allocationSize' => $seqGeneratorAnnot->allocationSize, 'initialValue' => $seqGeneratorAnnot->initialValue)); } else { if ($tblGeneratorAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\TableGenerator')) { throw MappingException::tableIdGeneratorNotImplemented($className); } } } else { if ($oneToOneAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OneToOne')) { if ($idAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Id')) { $mapping['id'] = true; } $mapping['targetEntity'] = $oneToOneAnnot->targetEntity; $mapping['joinColumns'] = $joinColumns; $mapping['mappedBy'] = $oneToOneAnnot->mappedBy; $mapping['inversedBy'] = $oneToOneAnnot->inversedBy; $mapping['cascade'] = $oneToOneAnnot->cascade; $mapping['orphanRemoval'] = $oneToOneAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $oneToOneAnnot->fetch); $metadata->mapOneToOne($mapping); } else { if ($oneToManyAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OneToMany')) { $mapping['mappedBy'] = $oneToManyAnnot->mappedBy; $mapping['targetEntity'] = $oneToManyAnnot->targetEntity; $mapping['cascade'] = $oneToManyAnnot->cascade; $mapping['indexBy'] = $oneToManyAnnot->indexBy; $mapping['orphanRemoval'] = $oneToManyAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $oneToManyAnnot->fetch); if ($orderByAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OrderBy')) { $mapping['orderBy'] = $orderByAnnot->value; } $metadata->mapOneToMany($mapping); } else { if ($manyToOneAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\ManyToOne')) { if ($idAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Id')) { $mapping['id'] = true; } $mapping['joinColumns'] = $joinColumns; $mapping['cascade'] = $manyToOneAnnot->cascade; $mapping['inversedBy'] = $manyToOneAnnot->inversedBy; $mapping['targetEntity'] = $manyToOneAnnot->targetEntity; $mapping['fetch'] = $this->getFetchMode($className, $manyToOneAnnot->fetch); $metadata->mapManyToOne($mapping); } else { if ($manyToManyAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\ManyToMany')) { $joinTable = array(); if ($joinTableAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\JoinTable')) { $joinTable = array('name' => $joinTableAnnot->name, 'schema' => $joinTableAnnot->schema); foreach ($joinTableAnnot->joinColumns as $joinColumn) { $joinTable['joinColumns'][] = array('name' => $joinColumn->name, 'referencedColumnName' => $joinColumn->referencedColumnName, 'unique' => $joinColumn->unique, 'nullable' => $joinColumn->nullable, 'onDelete' => $joinColumn->onDelete, 'columnDefinition' => $joinColumn->columnDefinition); } foreach ($joinTableAnnot->inverseJoinColumns as $joinColumn) { $joinTable['inverseJoinColumns'][] = array('name' => $joinColumn->name, 'referencedColumnName' => $joinColumn->referencedColumnName, 'unique' => $joinColumn->unique, 'nullable' => $joinColumn->nullable, 'onDelete' => $joinColumn->onDelete, 'columnDefinition' => $joinColumn->columnDefinition); } } $mapping['joinTable'] = $joinTable; $mapping['targetEntity'] = $manyToManyAnnot->targetEntity; $mapping['mappedBy'] = $manyToManyAnnot->mappedBy; $mapping['inversedBy'] = $manyToManyAnnot->inversedBy; $mapping['cascade'] = $manyToManyAnnot->cascade; $mapping['indexBy'] = $manyToManyAnnot->indexBy; $mapping['orphanRemoval'] = $manyToManyAnnot->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $manyToManyAnnot->fetch); if ($orderByAnnot = $this->_reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OrderBy')) { $mapping['orderBy'] = $orderByAnnot->value; } $metadata->mapManyToMany($mapping); } } } } } } // Evaluate @HasLifecycleCallbacks annotation if (isset($classAnnotations['Doctrine\\ORM\\Mapping\\HasLifecycleCallbacks'])) { foreach ($class->getMethods() as $method) { // filter for the declaring class only, callbacks from parents will already be registered. if ($method->isPublic() && $method->getDeclaringClass()->getName() == $class->name) { $annotations = $this->_reader->getMethodAnnotations($method); // Compatibility with Doctrine Common 3.x if ($annotations && is_int(key($annotations))) { foreach ($annotations as $annot) { $annotations[get_class($annot)] = $annot; } } if (isset($annotations['Doctrine\\ORM\\Mapping\\PrePersist'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::prePersist); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostPersist'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postPersist); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PreUpdate'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preUpdate); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostUpdate'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postUpdate); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PreRemove'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preRemove); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostRemove'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postRemove); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PostLoad'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::postLoad); } if (isset($annotations['Doctrine\\ORM\\Mapping\\PreFlush'])) { $metadata->addLifecycleCallback($method->getName(), \Doctrine\ORM\Events::preFlush); } } } } }
/** * {@inheritdoc} */ public function loadMetadataForClass($className, ClassMetadataInfo $metadata) { $element = $this->getElement($className); if ($element['type'] == 'entity') { if (isset($element['repositoryClass'])) { $metadata->setCustomRepositoryClass($element['repositoryClass']); } if (isset($element['readOnly']) && $element['readOnly'] == true) { $metadata->markReadOnly(); } } else { if ($element['type'] == 'mappedSuperclass') { $metadata->setCustomRepositoryClass(isset($element['repositoryClass']) ? $element['repositoryClass'] : null); $metadata->isMappedSuperclass = true; } else { throw MappingException::classIsNotAValidEntityOrMappedSuperClass($className); } } // Evaluate root level properties $table = array(); if (isset($element['table'])) { $table['name'] = $element['table']; } $metadata->setPrimaryTable($table); // Evaluate named queries if (isset($element['namedQueries'])) { foreach ($element['namedQueries'] as $name => $queryMapping) { if (is_string($queryMapping)) { $queryMapping = array('query' => $queryMapping); } if (!isset($queryMapping['name'])) { $queryMapping['name'] = $name; } $metadata->addNamedQuery($queryMapping); } } /* not implemented specially anyway. use table = schema.table if (isset($element['schema'])) { $metadata->table['schema'] = $element['schema']; }*/ if (isset($element['inheritanceType'])) { $metadata->setInheritanceType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::INHERITANCE_TYPE_' . strtoupper($element['inheritanceType']))); if ($metadata->inheritanceType != \Doctrine\ORM\Mapping\ClassMetadata::INHERITANCE_TYPE_NONE) { // Evaluate discriminatorColumn if (isset($element['discriminatorColumn'])) { $discrColumn = $element['discriminatorColumn']; $metadata->setDiscriminatorColumn(array('name' => $discrColumn['name'], 'type' => $discrColumn['type'], 'length' => $discrColumn['length'])); } else { $metadata->setDiscriminatorColumn(array('name' => 'dtype', 'type' => 'string', 'length' => 255)); } // Evaluate discriminatorMap if (isset($element['discriminatorMap'])) { $metadata->setDiscriminatorMap($element['discriminatorMap']); } } } // Evaluate changeTrackingPolicy if (isset($element['changeTrackingPolicy'])) { $metadata->setChangeTrackingPolicy(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::CHANGETRACKING_' . strtoupper($element['changeTrackingPolicy']))); } // Evaluate indexes if (isset($element['indexes'])) { foreach ($element['indexes'] as $name => $index) { if (!isset($index['name'])) { $index['name'] = $name; } if (is_string($index['columns'])) { $columns = explode(',', $index['columns']); } else { $columns = $index['columns']; } $metadata->table['indexes'][$index['name']] = array('columns' => $columns); } } // Evaluate uniqueConstraints if (isset($element['uniqueConstraints'])) { foreach ($element['uniqueConstraints'] as $name => $unique) { if (!isset($unique['name'])) { $unique['name'] = $name; } if (is_string($unique['columns'])) { $columns = explode(',', $unique['columns']); } else { $columns = $unique['columns']; } $metadata->table['uniqueConstraints'][$unique['name']] = array('columns' => $columns); } } $associationIds = array(); if (isset($element['id'])) { // Evaluate identifier settings foreach ($element['id'] as $name => $idElement) { if (isset($idElement['associationKey']) && $idElement['associationKey'] == true) { $associationIds[$name] = true; continue; } $mapping = array('id' => true, 'fieldName' => $name); if (isset($idElement['type'])) { $mapping['type'] = $idElement['type']; } if (isset($idElement['column'])) { $mapping['columnName'] = $idElement['column']; } if (isset($idElement['length'])) { $mapping['length'] = $idElement['length']; } if (isset($idElement['columnDefinition'])) { $mapping['columnDefinition'] = $idElement['columnDefinition']; } $metadata->mapField($mapping); if (isset($idElement['generator'])) { $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . strtoupper($idElement['generator']['strategy']))); } // Check for SequenceGenerator/TableGenerator definition if (isset($idElement['sequenceGenerator'])) { $metadata->setSequenceGeneratorDefinition($idElement['sequenceGenerator']); } else { if (isset($idElement['tableGenerator'])) { throw MappingException::tableIdGeneratorNotImplemented($className); } } } } // Evaluate fields if (isset($element['fields'])) { foreach ($element['fields'] as $name => $fieldMapping) { $mapping = array('fieldName' => $name); if (isset($fieldMapping['type'])) { $e = explode('(', $fieldMapping['type']); $fieldMapping['type'] = $e[0]; $mapping['type'] = $fieldMapping['type']; if (isset($e[1])) { $fieldMapping['length'] = substr($e[1], 0, strlen($e[1]) - 1); } } if (isset($fieldMapping['id'])) { $mapping['id'] = true; if (isset($fieldMapping['generator']['strategy'])) { $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . strtoupper($fieldMapping['generator']['strategy']))); } } if (isset($fieldMapping['column'])) { $mapping['columnName'] = $fieldMapping['column']; } if (isset($fieldMapping['length'])) { $mapping['length'] = $fieldMapping['length']; } if (isset($fieldMapping['precision'])) { $mapping['precision'] = $fieldMapping['precision']; } if (isset($fieldMapping['scale'])) { $mapping['scale'] = $fieldMapping['scale']; } if (isset($fieldMapping['unique'])) { $mapping['unique'] = (bool) $fieldMapping['unique']; } if (isset($fieldMapping['options'])) { $mapping['options'] = $fieldMapping['options']; } if (isset($fieldMapping['nullable'])) { $mapping['nullable'] = $fieldMapping['nullable']; } if (isset($fieldMapping['version']) && $fieldMapping['version']) { $metadata->setVersionMapping($mapping); } if (isset($fieldMapping['columnDefinition'])) { $mapping['columnDefinition'] = $fieldMapping['columnDefinition']; } $metadata->mapField($mapping); } } // Evaluate oneToOne relationships if (isset($element['oneToOne'])) { foreach ($element['oneToOne'] as $name => $oneToOneElement) { $mapping = array('fieldName' => $name, 'targetEntity' => $oneToOneElement['targetEntity']); if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; } if (isset($oneToOneElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . $oneToOneElement['fetch']); } if (isset($oneToOneElement['mappedBy'])) { $mapping['mappedBy'] = $oneToOneElement['mappedBy']; } else { if (isset($oneToOneElement['inversedBy'])) { $mapping['inversedBy'] = $oneToOneElement['inversedBy']; } $joinColumns = array(); if (isset($oneToOneElement['joinColumn'])) { $joinColumns[] = $this->_getJoinColumnMapping($oneToOneElement['joinColumn']); } else { if (isset($oneToOneElement['joinColumns'])) { foreach ($oneToOneElement['joinColumns'] as $name => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $name; } $joinColumns[] = $this->_getJoinColumnMapping($joinColumnElement); } } } $mapping['joinColumns'] = $joinColumns; } if (isset($oneToOneElement['cascade'])) { $mapping['cascade'] = $oneToOneElement['cascade']; } if (isset($oneToOneElement['orphanRemoval'])) { $mapping['orphanRemoval'] = (bool) $oneToOneElement['orphanRemoval']; } $metadata->mapOneToOne($mapping); } } // Evaluate oneToMany relationships if (isset($element['oneToMany'])) { foreach ($element['oneToMany'] as $name => $oneToManyElement) { $mapping = array('fieldName' => $name, 'targetEntity' => $oneToManyElement['targetEntity'], 'mappedBy' => $oneToManyElement['mappedBy']); if (isset($oneToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . $oneToManyElement['fetch']); } if (isset($oneToManyElement['cascade'])) { $mapping['cascade'] = $oneToManyElement['cascade']; } if (isset($oneToManyElement['orphanRemoval'])) { $mapping['orphanRemoval'] = (bool) $oneToManyElement['orphanRemoval']; } if (isset($oneToManyElement['orderBy'])) { $mapping['orderBy'] = $oneToManyElement['orderBy']; } if (isset($oneToManyElement['indexBy'])) { $mapping['indexBy'] = $oneToManyElement['indexBy']; } $metadata->mapOneToMany($mapping); } } // Evaluate manyToOne relationships if (isset($element['manyToOne'])) { foreach ($element['manyToOne'] as $name => $manyToOneElement) { $mapping = array('fieldName' => $name, 'targetEntity' => $manyToOneElement['targetEntity']); if (isset($associationIds[$mapping['fieldName']])) { $mapping['id'] = true; } if (isset($manyToOneElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . $manyToOneElement['fetch']); } if (isset($manyToOneElement['inversedBy'])) { $mapping['inversedBy'] = $manyToOneElement['inversedBy']; } $joinColumns = array(); if (isset($manyToOneElement['joinColumn'])) { $joinColumns[] = $this->_getJoinColumnMapping($manyToOneElement['joinColumn']); } else { if (isset($manyToOneElement['joinColumns'])) { foreach ($manyToOneElement['joinColumns'] as $name => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $name; } $joinColumns[] = $this->_getJoinColumnMapping($joinColumnElement); } } } $mapping['joinColumns'] = $joinColumns; if (isset($manyToOneElement['cascade'])) { $mapping['cascade'] = $manyToOneElement['cascade']; } $metadata->mapManyToOne($mapping); } } // Evaluate manyToMany relationships if (isset($element['manyToMany'])) { foreach ($element['manyToMany'] as $name => $manyToManyElement) { $mapping = array('fieldName' => $name, 'targetEntity' => $manyToManyElement['targetEntity']); if (isset($manyToManyElement['fetch'])) { $mapping['fetch'] = constant('Doctrine\\ORM\\Mapping\\ClassMetadata::FETCH_' . $manyToManyElement['fetch']); } if (isset($manyToManyElement['mappedBy'])) { $mapping['mappedBy'] = $manyToManyElement['mappedBy']; } else { if (isset($manyToManyElement['joinTable'])) { if (isset($manyToManyElement['inversedBy'])) { $mapping['inversedBy'] = $manyToManyElement['inversedBy']; } $joinTableElement = $manyToManyElement['joinTable']; $joinTable = array('name' => $joinTableElement['name']); if (isset($joinTableElement['schema'])) { $joinTable['schema'] = $joinTableElement['schema']; } foreach ($joinTableElement['joinColumns'] as $name => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $name; } $joinTable['joinColumns'][] = $this->_getJoinColumnMapping($joinColumnElement); } foreach ($joinTableElement['inverseJoinColumns'] as $name => $joinColumnElement) { if (!isset($joinColumnElement['name'])) { $joinColumnElement['name'] = $name; } $joinTable['inverseJoinColumns'][] = $this->_getJoinColumnMapping($joinColumnElement); } $mapping['joinTable'] = $joinTable; } } if (isset($manyToManyElement['cascade'])) { $mapping['cascade'] = $manyToManyElement['cascade']; } if (isset($manyToManyElement['orderBy'])) { $mapping['orderBy'] = $manyToManyElement['orderBy']; } if (isset($manyToManyElement['indexBy'])) { $mapping['indexBy'] = $manyToManyElement['indexBy']; } $metadata->mapManyToMany($mapping); } } // Evaluate lifeCycleCallbacks if (isset($element['lifecycleCallbacks'])) { foreach ($element['lifecycleCallbacks'] as $type => $methods) { foreach ($methods as $method) { $metadata->addLifecycleCallback($method, constant('Doctrine\\ORM\\Events::' . $type)); } } } }
/** * Build field mapping from class metadata. * * @param \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ private function buildFieldMappings(ClassMetadataInfo $metadata) { $tableName = $metadata->table['name']; $columns = $this->tables[$tableName]->getColumns(); $primaryKeys = $this->getTablePrimaryKeys($this->tables[$tableName]); $foreignKeys = $this->getTableForeignKeys($this->tables[$tableName]); $allForeignKeys = array(); foreach ($foreignKeys as $foreignKey) { $allForeignKeys = array_merge($allForeignKeys, $foreignKey->getLocalColumns()); } $ids = array(); $fieldMappings = array(); foreach ($columns as $column) { if (in_array($column->getName(), $allForeignKeys)) { continue; } $fieldMapping = $this->buildFieldMapping($tableName, $column); if ($primaryKeys && in_array($column->getName(), $primaryKeys)) { $fieldMapping['id'] = true; $ids[] = $fieldMapping; } $fieldMappings[] = $fieldMapping; } // We need to check for the columns here, because we might have associations as id as well. if ($ids && count($primaryKeys) == 1) { $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_AUTO); } foreach ($fieldMappings as $fieldMapping) { $metadata->mapField($fieldMapping); } }
/** * @group DDC-2079 */ public function testGenerateEntityWithMultipleInverseJoinColumns() { $metadata = new ClassMetadataInfo($this->_namespace . '\\DDC2079Entity'); $metadata->namespace = $this->_namespace; $metadata->mapField(array('fieldName' => 'id', 'type' => 'integer', 'id' => true)); $metadata->setIdGeneratorType(ClassMetadataInfo::GENERATOR_TYPE_SEQUENCE); $metadata->mapManyToMany(array('fieldName' => 'centroCustos', 'targetEntity' => 'DDC2079CentroCusto', 'joinTable' => array('name' => 'unidade_centro_custo', 'joinColumns' => array(array('name' => 'idorcamento', 'referencedColumnName' => 'idorcamento'), array('name' => 'idunidade', 'referencedColumnName' => 'idunidade')), 'inverseJoinColumns' => array(array('name' => 'idcentrocusto', 'referencedColumnName' => 'idcentrocusto'), array('name' => 'idpais', 'referencedColumnName' => 'idpais'))))); $this->_generator->writeEntityClass($metadata, $this->_tmpDir); $filename = $this->_tmpDir . DIRECTORY_SEPARATOR . $this->_namespace . DIRECTORY_SEPARATOR . 'DDC2079Entity.php'; $this->assertFileExists($filename); require_once $filename; $property = new \ReflectionProperty($metadata->name, 'centroCustos'); $docComment = $property->getDocComment(); //joinColumns $this->assertContains('@JoinColumn(name="idorcamento", referencedColumnName="idorcamento"),', $docComment); $this->assertContains('@JoinColumn(name="idunidade", referencedColumnName="idunidade")', $docComment); //inverseJoinColumns $this->assertContains('@JoinColumn(name="idcentrocusto", referencedColumnName="idcentrocusto"),', $docComment); $this->assertContains('@JoinColumn(name="idpais", referencedColumnName="idpais")', $docComment); }
/** * Evaluate the property annotations and amend the metadata accordingly. * * @param ClassMetadataInfo $metadata * @return void * @throws MappingException */ protected function evaluatePropertyAnnotations(ClassMetadataInfo $metadata) { $className = $metadata->name; $class = $metadata->getReflectionClass(); $classSchema = $this->getClassSchema($className); foreach ($class->getProperties() as $property) { if (!$classSchema->hasProperty($property->getName()) || $classSchema->isPropertyTransient($property->getName()) || $metadata->isMappedSuperclass && !$property->isPrivate() || $metadata->isInheritedField($property->getName()) || $metadata->isInheritedAssociation($property->getName())) { continue; } $propertyMetaData = $classSchema->getProperty($property->getName()); $mapping = array(); $mapping['fieldName'] = $property->getName(); $mapping['columnName'] = strtolower($property->getName()); $mapping['targetEntity'] = $propertyMetaData['type']; $joinColumns = $this->evaluateJoinColumnAnnotations($property); // Field can only be annotated with one of: // @OneToOne, @OneToMany, @ManyToOne, @ManyToMany, @Column (optional) if ($oneToOneAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OneToOne')) { if ($oneToOneAnnotation->targetEntity) { $mapping['targetEntity'] = $oneToOneAnnotation->targetEntity; } if ($oneToOneAnnotation->inversedBy !== null || $oneToOneAnnotation->mappedBy === null) { $mapping['joinColumns'] = $this->buildJoinColumnsIfNeeded($joinColumns, $mapping, $property); } $mapping['mappedBy'] = $oneToOneAnnotation->mappedBy; $mapping['inversedBy'] = $oneToOneAnnotation->inversedBy; if ($oneToOneAnnotation->cascade) { $mapping['cascade'] = $oneToOneAnnotation->cascade; } elseif ($this->isValueObject($mapping['targetEntity'], $className)) { $mapping['cascade'] = array('persist'); } elseif ($this->isAggregateRoot($mapping['targetEntity'], $className) === false) { $mapping['cascade'] = array('all'); } if ($oneToOneAnnotation->orphanRemoval) { $mapping['orphanRemoval'] = $oneToOneAnnotation->orphanRemoval; } elseif ($this->isAggregateRoot($mapping['targetEntity'], $className) === false && $this->isValueObject($mapping['targetEntity'], $className) === false) { $mapping['orphanRemoval'] = true; } $mapping['fetch'] = $this->getFetchMode($className, $oneToOneAnnotation->fetch); $metadata->mapOneToOne($mapping); } elseif ($oneToManyAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OneToMany')) { $mapping['mappedBy'] = $oneToManyAnnotation->mappedBy; if ($oneToManyAnnotation->targetEntity) { $mapping['targetEntity'] = $oneToManyAnnotation->targetEntity; } elseif (isset($propertyMetaData['elementType'])) { $mapping['targetEntity'] = $propertyMetaData['elementType']; } if ($oneToManyAnnotation->cascade) { $mapping['cascade'] = $oneToManyAnnotation->cascade; } elseif ($this->isValueObject($mapping['targetEntity'], $className)) { $mapping['cascade'] = array('persist'); } elseif ($this->isAggregateRoot($mapping['targetEntity'], $className) === false) { $mapping['cascade'] = array('all'); } $mapping['indexBy'] = $oneToManyAnnotation->indexBy; if ($oneToManyAnnotation->orphanRemoval) { $mapping['orphanRemoval'] = $oneToManyAnnotation->orphanRemoval; } elseif ($this->isAggregateRoot($mapping['targetEntity'], $className) === false && $this->isValueObject($mapping['targetEntity'], $className) === false) { $mapping['orphanRemoval'] = true; } $mapping['fetch'] = $this->getFetchMode($className, $oneToManyAnnotation->fetch); if ($orderByAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OrderBy')) { $mapping['orderBy'] = $orderByAnnotation->value; } $metadata->mapOneToMany($mapping); } elseif ($manyToOneAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\ManyToOne')) { if ($manyToOneAnnotation->targetEntity) { $mapping['targetEntity'] = $manyToOneAnnotation->targetEntity; } $mapping['joinColumns'] = $this->buildJoinColumnsIfNeeded($joinColumns, $mapping, $property); if ($manyToOneAnnotation->cascade) { $mapping['cascade'] = $manyToOneAnnotation->cascade; } elseif ($this->isValueObject($mapping['targetEntity'], $className)) { $mapping['cascade'] = array('persist'); } elseif ($this->isAggregateRoot($mapping['targetEntity'], $className) === false) { $mapping['cascade'] = array('all'); } $mapping['inversedBy'] = $manyToOneAnnotation->inversedBy; $mapping['fetch'] = $this->getFetchMode($className, $manyToOneAnnotation->fetch); $metadata->mapManyToOne($mapping); } elseif ($manyToManyAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\ManyToMany')) { if ($manyToManyAnnotation->targetEntity) { $mapping['targetEntity'] = $manyToManyAnnotation->targetEntity; } elseif (isset($propertyMetaData['elementType'])) { $mapping['targetEntity'] = $propertyMetaData['elementType']; } /** @var JoinTable $joinTableAnnotation */ if ($joinTableAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\JoinTable')) { $joinTable = $this->evaluateJoinTableAnnotation($joinTableAnnotation, $property, $className, $mapping); } else { $joinColumns = array(array('name' => null, 'referencedColumnName' => null)); $joinTable = array('name' => $this->inferJoinTableNameFromClassAndPropertyName($className, $property->getName()), 'joinColumns' => $this->buildJoinColumnsIfNeeded($joinColumns, $mapping, $property, self::MAPPING_MM_REGULAR), 'inverseJoinColumns' => $this->buildJoinColumnsIfNeeded($joinColumns, $mapping, $property)); } $mapping['joinTable'] = $joinTable; $mapping['mappedBy'] = $manyToManyAnnotation->mappedBy; $mapping['inversedBy'] = $manyToManyAnnotation->inversedBy; if ($manyToManyAnnotation->cascade) { $mapping['cascade'] = $manyToManyAnnotation->cascade; } elseif ($this->isValueObject($mapping['targetEntity'], $className)) { $mapping['cascade'] = array('persist'); } elseif ($this->isAggregateRoot($mapping['targetEntity'], $className) === false) { $mapping['cascade'] = array('all'); } $mapping['indexBy'] = $manyToManyAnnotation->indexBy; $mapping['orphanRemoval'] = $manyToManyAnnotation->orphanRemoval; $mapping['fetch'] = $this->getFetchMode($className, $manyToManyAnnotation->fetch); if ($orderByAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\OrderBy')) { $mapping['orderBy'] = $orderByAnnotation->value; } $metadata->mapManyToMany($mapping); } else { $mapping['nullable'] = false; /** @var Column $columnAnnotation */ if ($columnAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Column')) { $mapping = $this->addColumnToMappingArray($columnAnnotation, $mapping); } if (!isset($mapping['type'])) { switch ($propertyMetaData['type']) { case 'DateTime': $mapping['type'] = 'datetime'; break; case 'string': case 'integer': case 'boolean': case 'float': case 'array': $mapping['type'] = $propertyMetaData['type']; break; default: if (strpos($propertyMetaData['type'], '\\') !== false) { if ($this->reflectionService->isClassAnnotatedWith($propertyMetaData['type'], \TYPO3\Flow\Annotations\ValueObject::class)) { $mapping['type'] = 'object'; } elseif (class_exists($propertyMetaData['type'])) { throw MappingException::missingRequiredOption($property->getName(), 'OneToOne', sprintf('The property "%s" in class "%s" has a non standard data type and doesn\'t define the type of the relation. You have to use one of these annotations: @OneToOne, @OneToMany, @ManyToOne, @ManyToMany', $property->getName(), $className)); } } else { throw MappingException::propertyTypeIsRequired($className, $property->getName()); } } } if ($this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\Id') !== null) { $mapping['id'] = true; } if ($generatedValueAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\GeneratedValue')) { $metadata->setIdGeneratorType(constant('Doctrine\\ORM\\Mapping\\ClassMetadata::GENERATOR_TYPE_' . strtoupper($generatedValueAnnotation->strategy))); } if ($this->reflectionService->isPropertyAnnotatedWith($className, $property->getName(), 'Doctrine\\ORM\\Mapping\\Version')) { $metadata->setVersionMapping($mapping); } $metadata->mapField($mapping); // Check for SequenceGenerator/TableGenerator definition if ($seqGeneratorAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\SequenceGenerator')) { $metadata->setSequenceGeneratorDefinition(array('sequenceName' => $seqGeneratorAnnotation->sequenceName, 'allocationSize' => $seqGeneratorAnnotation->allocationSize, 'initialValue' => $seqGeneratorAnnotation->initialValue)); } elseif ($this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\TableGenerator') !== null) { throw MappingException::tableIdGeneratorNotImplemented($className); } elseif ($customGeneratorAnnotation = $this->reader->getPropertyAnnotation($property, 'Doctrine\\ORM\\Mapping\\CustomIdGenerator')) { $metadata->setCustomGeneratorDefinition(array('class' => $customGeneratorAnnotation->class)); } } } }