/** * Initializes context. * * @param ManagerRegistry $doctrine */ public function __construct(ManagerRegistry $doctrine) { $this->manager = $doctrine->getManager(); $this->schemaTool = new SchemaTool($this->manager); $this->classes = $this->manager->getMetadataFactory()->getAllMetadata(); $this->inspector = new JsonInspector('javascript'); }
/** * Initializes context. * * Every scenario gets its own context instance. * You can also pass arbitrary arguments to the * context constructor through behat.yml. */ public function __construct(ManagerRegistry $doctrine) { $this->doctrine = $doctrine; $this->manager = $doctrine->getManager(); $this->schemaTool = new SchemaTool($this->manager); $this->classes = $this->manager->getMetadataFactory()->getAllMetadata(); }
/** * Create the database schema. * * @param ObjectManager $om */ protected function createSchema(ObjectManager $om) { if ($om instanceof \Doctrine\ORM\EntityManager) { $schemaTool = new \Doctrine\ORM\Tools\SchemaTool($om); $schemaTool->createSchema($om->getMetadataFactory()->getAllMetadata()); } elseif ($om instanceof \Doctrine\ODM\MongoDB\DocumentManager) { $sm = new \Doctrine\ODM\MongoDB\SchemaManager($om, $om->getMetadataFactory()); $sm->createCollections(); } }
/** * Initializes context. * * Every scenario gets its own context instance. * You can also pass arbitrary arguments to the * context constructor through behat.yml. * * @param ManagerRegistry $doctrine * @param JWTManagerInterface $jwtManager * @param UserManager $userManager * @param EncoderFactoryInterface $encoderFactory */ public function __construct(ManagerRegistry $doctrine, JWTManagerInterface $jwtManager, UserManager $userManager, EncoderFactoryInterface $encoderFactory) { $this->doctrine = $doctrine; $this->manager = $doctrine->getManager(); $this->schemaTool = new SchemaTool($this->manager); $this->metadata = $this->manager->getMetadataFactory()->getAllMetadata(); $this->jwtManager = $jwtManager; $this->userManager = $userManager; $this->encoderFactory = $encoderFactory; $this->inspector = new JsonInspector('javascript'); }
/** * {@inheritdoc} */ public function setUp() { static::$kernel = static::createKernel(); static::$kernel->boot(); $this->doctrine = static::$kernel->getContainer()->get('doctrine'); $this->doctrineManager = $this->doctrine->getManager(); $this->validator = static::$kernel->getContainer()->get('validator'); // Recreate a fresh database instance before each test case $metadata = $this->doctrineManager->getMetadataFactory()->getAllMetadata(); $schemaTool = new SchemaTool($this->doctrineManager); $schemaTool->dropSchema($metadata); $schemaTool->createSchema($metadata); }
protected function setUp() { if (!class_exists('Twig_Environment')) { $this->markTestSkipped('Twig is not available.'); } if (null === $this->em) { $this->em = $this->client->getContainer()->get('doctrine')->getManager(); if (!static::$schemaSetUp) { $st = new SchemaTool($this->em); $classes = $this->em->getMetadataFactory()->getAllMetadata(); $st->dropSchema($classes); $st->createSchema($classes); static::$schemaSetUp = true; } } parent::setUp(); }
public function load(ObjectManager $manager, $tags = null) { if (!$this->hasTag($tags)) { return; } $cmf = $manager->getMetadataFactory(); // The model class for all fixtures defined in this file $class = $this->file['model']; // Get the fields that are not "associations" $metadata = $cmf->getMetaDataFor($class); $mapping = array_keys($metadata->fieldMappings); $associations = array_keys($metadata->associationMappings); foreach ($this->file['fixtures'] as $reference => $fixture) { // Instantiate new object $object = new $class(); foreach ($fixture as $field => $value) { // Add the fields defined in the fistures file $method = Inflector::camelize('set_' . $field); // if (strpos($value, '$') === 0) { // custom reference loader format: $<referencedEntityKey>|<referencedColumn> // ex: $first_campaign|idcampaign list($referencedEntity, $referenceColumn) = explode('|', ltrim($value, '$')); $getterMethod = Inflector::camelize('get_' . $referenceColumn); $object->{$method}($this->loader->getReference($referencedEntity)->{$getterMethod}()); } elseif (in_array($field, $mapping)) { // Dates need to be converted to DateTime objects $type = $metadata->fieldMappings[$field]['type']; if ($type == 'datetime' or $type == 'date') { $value = new \DateTime($value); } $object->{$method}($value); } else { if (in_array($field, $associations)) { // This field is an association, we load it from the references $object->{$method}($this->loader->getReference($value)); } else { // It's a method call that will set a field named differently // eg: FOSUserBundle ->setPlainPassword sets the password after // Encrypting it $object->{$method}($value); } } } // Save a reference to the current object $this->loader->setReference($reference, $object); if (!$this->isReverseSaveOrder()) { $manager->persist($object); } } if ($this->isReverseSaveOrder()) { $refs = array_keys($this->file['fixtures']); for ($i = count($refs) - 1; $i >= 0; $i--) { $manager->persist($this->loader->getReference($refs[$i])); } } $manager->flush(); }
/** * Get all entities * * @access public * * @return array entities */ public function getAllEntities() { $entities = array(); $allMetadata = $this->entityManager->getMetadataFactory()->getAllMetadata(); foreach ($allMetadata as $entityMetadata) { $entities[] = $entityMetadata->getName(); } return $entities; }
private function createData(ObjectManager $manager) { $data = array('entities' => array(), 'relations' => array()); $passes = array(new ImportMetadataPass(), new InheritancePass(), new ShortNamePass()); foreach ($passes as $pass) { $data = $pass->process($manager->getMetadataFactory(), $data); } return $data; }
/** * Checks whether provided entity is supported by the Metadatable Controller. * * @param mixed $entity * * @return bool */ protected function isEntitySupported($entity) { try { $classMetadata = $this->om->getMetadataFactory()->getMetadataFor(get_class($entity)); } catch (\Exception $e) { return false; } $reflClass = $classMetadata->reflClass; $traitNames = []; while ($reflClass) { $traitNames = array_merge($traitNames, $reflClass->getTraitNames()); $reflClass = $reflClass->getParentClass(); } $supported = in_array('Unifik\\DoctrineBehaviorsBundle\\Model\\Metadatable\\Metadatable', $traitNames); if (!$supported && is_callable([$entity, 'getTranslation'])) { return $this->isEntitySupported($entity->getTranslation()); } return $supported; }
/** * @param string $entityName * * @return bool */ protected function isCorrectClassName($entityName) { try { $classMetadata = $this->em->getMetadataFactory()->getMetadataFor($entityName); $classMetadata->getName(); } catch (\Exception $e) { return false; } return true; }
/** * Initializes extension driver. * * @param \Doctrine\Common\Persistence\ObjectManager $objectManager * @param string $extensionNamespace * @param object $annotationReader */ public function __construct(ObjectManager $objectManager, $extensionNamespace, $annotationReader) { $this->objectManager = $objectManager; $this->annotationReader = $annotationReader; $this->extensionNamespace = $extensionNamespace; $omDriver = $objectManager->getConfiguration()->getMetadataDriverImpl(); $omCache = $this->objectManager->getMetadataFactory()->getCacheDriver(); $metadataClassName = null; if (class_exists($this->extensionNamespace . '\\Mapping\\ClassMetadata')) { $metadataClassName = $this->extensionNamespace . '\\Mapping\\ClassMetadata'; } $driver = $this->getDriver($omDriver); $driver->setBaseMetadataFactory($objectManager->getMetadataFactory()); parent::__construct($driver, $omCache, $extensionNamespace, $metadataClassName); }
/** * Called from functional tests, creates/updates database tables and compiles proxies. * * @return boolean */ public function compile() { // "driver" is used only for Doctrine, thus we (mis-)use it here // additionally, when no path is set, skip this step, assuming no DB is needed if ($this->settings['backendOptions']['driver'] !== null && $this->settings['backendOptions']['path'] !== null) { $schemaTool = new SchemaTool($this->entityManager); if ($this->settings['backendOptions']['driver'] === 'pdo_sqlite') { $schemaTool->createSchema($this->entityManager->getMetadataFactory()->getAllMetadata()); } else { $schemaTool->updateSchema($this->entityManager->getMetadataFactory()->getAllMetadata()); } $proxyFactory = $this->entityManager->getProxyFactory(); $proxyFactory->generateProxyClasses($this->entityManager->getMetadataFactory()->getAllMetadata()); $this->systemLogger->log('Doctrine 2 setup finished'); return true; } else { $this->systemLogger->log('Doctrine 2 setup skipped, driver and path backend options not set!', LOG_NOTICE); return false; } }
/** * Generates a new migration file and returns the path to it. * * If $diffAgainstCurrent is TRUE, it generates a migration file with the * diff between current DB structure and the found mapping metadata. * * Only include tables/sequences matching the $filterExpression regexp when * diffing models and existing schema. * * Otherwise an empty migration skeleton is generated. * * @param boolean $diffAgainstCurrent * @param string $filterExpression * @return string Path to the new file */ public function generateMigration($diffAgainstCurrent = true, $filterExpression = null) { $configuration = $this->getMigrationConfiguration(); $up = null; $down = null; if ($diffAgainstCurrent === true) { /** @var \Doctrine\DBAL\Connection $connection */ $connection = $this->entityManager->getConnection(); if ($filterExpression) { $connection->getConfiguration()->setFilterSchemaAssetsExpression($filterExpression); } $metadata = $this->entityManager->getMetadataFactory()->getAllMetadata(); if (empty($metadata)) { return ['No mapping information to process.', null]; } $tool = new SchemaTool($this->entityManager); $fromSchema = $connection->getSchemaManager()->createSchema(); $toSchema = $tool->getSchemaFromMetadata($metadata); if ($filterExpression) { foreach ($toSchema->getTables() as $table) { $tableName = $table->getName(); if (!preg_match($filterExpression, $this->resolveTableName($tableName))) { $toSchema->dropTable($tableName); } } foreach ($toSchema->getSequences() as $sequence) { $sequenceName = $sequence->getName(); if (!preg_match($filterExpression, $this->resolveTableName($sequenceName))) { $toSchema->dropSequence($sequenceName); } } } $platform = $connection->getDatabasePlatform(); $up = $this->buildCodeFromSql($configuration, $fromSchema->getMigrateToSql($toSchema, $platform)); $down = $this->buildCodeFromSql($configuration, $fromSchema->getMigrateFromSql($toSchema, $platform)); if (!$up && !$down) { return ['No changes detected in your mapping information.', null]; } } return ['Generated new migration class!', $this->writeMigrationClassToFile($configuration, $up, $down)]; }
/** * Generates a new migration file and returns the path to it. * * If $diffAgainstCurrent is TRUE, it generates a migration file with the * diff between current DB structure and the found mapping metadata. * * Otherwise an empty migration skeleton is generated. * * @param boolean $diffAgainstCurrent * @return string Path to the new file */ public function generateMigration($diffAgainstCurrent = true) { $configuration = $this->getMigrationConfiguration(); $up = null; $down = null; if ($diffAgainstCurrent === true) { $connection = $this->entityManager->getConnection(); $platform = $connection->getDatabasePlatform(); $metadata = $this->entityManager->getMetadataFactory()->getAllMetadata(); if (empty($metadata)) { return 'No mapping information to process.'; } $tool = new \Doctrine\ORM\Tools\SchemaTool($this->entityManager); $fromSchema = $connection->getSchemaManager()->createSchema(); $toSchema = $tool->getSchemaFromMetadata($metadata); $up = $this->buildCodeFromSql($configuration, $fromSchema->getMigrateToSql($toSchema, $platform)); $down = $this->buildCodeFromSql($configuration, $fromSchema->getMigrateFromSql($toSchema, $platform)); if (!$up && !$down) { return 'No changes detected in your mapping information.'; } } return $this->writeMigrationClassToFile($configuration, $up, $down); }
/** * Get the configuration for specific object class * if cache driver is present it scans it also * * @param Common\Persistence\ObjectManager $objectManager * @param string $class * * @return array */ public function getObjectConfigurations(Common\Persistence\ObjectManager $objectManager, $class) { $config = []; if (isset(self::$objectConfigurations[$class])) { $config = self::$objectConfigurations[$class]; } else { $metadataFactory = $objectManager->getMetadataFactory(); /** @var Common\Cache\Cache $cacheDriver|NULL */ $cacheDriver = $metadataFactory->getCacheDriver(); if ($cacheDriver !== NULL) { $cacheId = self::getCacheId($class); if (($cached = $cacheDriver->fetch($cacheId)) !== FALSE) { self::$objectConfigurations[$class] = $cached; $config = $cached; } else { /** @var ORM\Mapping\ClassMetadata $classMetadata */ $classMetadata = $metadataFactory->getMetadataFor($class); // Re-generate metadata on cache miss $this->loadMetadataForObjectClass($objectManager, $classMetadata); if (isset(self::$objectConfigurations[$class])) { $config = self::$objectConfigurations[$class]; } } $objectClass = isset($config['useObjectClass']) ? $config['useObjectClass'] : $class; if ($objectClass !== $class) { $this->getObjectConfigurations($objectManager, $objectClass); } } } return $config; }
/** * @Deprecated * * Returns the entity repository * * @return \Doctrine\ORM\EntityRepository */ protected function getRepository() { $classMetadata = $this->objectManager->getMetadataFactory()->getMetadataFor($this->attributeClass); return new AttributeRepository($this->objectManager, $classMetadata); }
/** * Get the configuration for specific object class * if cache driver is present it scans it also * * @param ObjectManager $objectManager * @param string $class * @return array */ public function getConfiguration(ObjectManager $objectManager, $class) { $config = array(); if (isset($this->configurations[$class])) { $config = $this->configurations[$class]; } else { $cacheDriver = $objectManager->getMetadataFactory()->getCacheDriver(); $cacheId = ExtensionMetadataFactory::getCacheId($class, $this->getNamespace()); if ($cacheDriver && ($cached = $cacheDriver->fetch($cacheId)) !== false) { $this->configurations[$class] = $cached; $config = $cached; } } return $config; }
/** * Get the configuration for specific object class * if cache driver is present it scans it also * * @param ObjectManager $objectManager * @param string $class * @return array */ public function getConfiguration(ObjectManager $objectManager, $class) { $config = array(); if (isset(self::$configurations[$this->name][$class])) { $config = self::$configurations[$this->name][$class]; } else { $factory = $objectManager->getMetadataFactory(); $cacheDriver = $factory->getCacheDriver(); if ($cacheDriver) { $cacheId = ExtensionMetadataFactory::getCacheId($class, $this->getNamespace()); if (($cached = $cacheDriver->fetch($cacheId)) !== false) { self::$configurations[$this->name][$class] = $cached; $config = $cached; } else { // re-generate metadata on cache miss $this->loadMetadataForObjectClass($objectManager, $factory->getMetadataFor($class)); if (isset(self::$configurations[$this->name][$class])) { $config = self::$configurations[$this->name][$class]; } } } } return $config; }
/** * @param $entity * @param Common\Persistence\ObjectManager $objectManager * * @throws Phone\Exceptions\NoValidCountryException * @throws Phone\Exceptions\NoValidPhoneException */ private function postLoadAndPreFlush($entity, Common\Persistence\ObjectManager $objectManager) { $cache = $objectManager->getMetadataFactory()->getCacheDriver(); if (!($fieldsMap = $this->getEntityPhoneFields($entity, $cache))) { return; } foreach ($fieldsMap as $phoneAssoc => $phoneMeta) { foreach ($phoneMeta['fields'] as $phoneField) { $number = $phoneMeta['class']->getFieldValue($entity, $phoneField); if ($number instanceof Phone\Entities\Phone || $number === NULL) { continue; } $phoneMeta['class']->setFieldValue($entity, $phoneField, Phone\Entities\Phone::fromNumber($number)); } } }
protected function getAllMetadata() { return $this->objectManager->getMetadataFactory()->getAllMetadata(); }
/** * @param ObjectManager $objectManager */ public function initDoctrinePropertiesByEntityManager(ObjectManager $objectManager) { /** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */ $metadata = $objectManager->getMetadataFactory()->getMetadataFor($this->entityName); $this->entityRepository = $objectManager->getRepository($this->entityName); $this->idFieldName = $metadata->getSingleIdentifierFieldName(); $this->objectManager = $objectManager; }
/** * просто собирает информации о зарегистрированных классах в ObjectManager * * @param ObjectManager $om * * @return array список классов из менеджера объектов */ private function getRegisteredClassNamesFromObjectManager(ObjectManager $om) { $arrayOfClasses = []; $allMetadata = $om->getMetadataFactory()->getAllMetadata(); array_walk($allMetadata, function (ClassMetadata $meta) use(&$arrayOfClasses) { $arrayOfClasses[] = $meta->getName(); }); return $arrayOfClasses; }
public function getMetadataFromObject(ObjectManager $entityManager, $object) { return $entityManager->getMetadataFactory()->getMetadataFor(get_class($object)); }
/** * @param ObjectManager $objectManager */ public function __construct(ObjectManager $objectManager) { $this->metadataFactory = $objectManager->getMetadataFactory(); }