public function createService(ServiceLocatorInterface $serviceLocator)
 {
     /** @var $options \DoctrineORMModule\Options\Configuration */
     $options = $this->getOptions($serviceLocator);
     $config = new Configuration();
     $config->setAutoGenerateProxyClasses($options->getGenerateProxies());
     $config->setProxyDir($options->getProxyDir());
     $config->setProxyNamespace($options->getProxyNamespace());
     $config->setEntityNamespaces($options->getEntityNamespaces());
     $config->setCustomDatetimeFunctions($options->getDatetimeFunctions());
     $config->setCustomStringFunctions($options->getStringFunctions());
     $config->setCustomNumericFunctions($options->getNumericFunctions());
     $config->setClassMetadataFactoryName($options->getClassMetadataFactoryName());
     foreach ($options->getNamedQueries() as $name => $query) {
         $config->addNamedQuery($name, $query);
     }
     foreach ($options->getNamedNativeQueries() as $name => $query) {
         $config->addNamedNativeQuery($name, $query['sql'], new $query['rsm']());
     }
     foreach ($options->getCustomHydrationModes() as $modeName => $hydrator) {
         $config->addCustomHydrationMode($modeName, $hydrator);
     }
     foreach ($options->getFilters() as $name => $class) {
         $config->addFilter($name, $class);
     }
     $config->setMetadataCacheImpl($serviceLocator->get($options->getMetadataCache()));
     $config->setQueryCacheImpl($serviceLocator->get($options->getQueryCache()));
     $config->setResultCacheImpl($serviceLocator->get($options->getResultCache()));
     $config->setHydrationCacheImpl($serviceLocator->get($options->getHydrationCache()));
     $config->setMetadataDriverImpl($serviceLocator->get($options->getDriver()));
     if ($namingStrategy = $options->getNamingStrategy()) {
         if (is_string($namingStrategy)) {
             if (!$serviceLocator->has($namingStrategy)) {
                 throw new InvalidArgumentException(sprintf('Naming strategy "%s" not found', $namingStrategy));
             }
             $config->setNamingStrategy($serviceLocator->get($namingStrategy));
         } else {
             $config->setNamingStrategy($namingStrategy);
         }
     }
     if ($repositoryFactory = $options->getRepositoryFactory()) {
         if (is_string($repositoryFactory)) {
             if (!$serviceLocator->has($repositoryFactory)) {
                 throw new InvalidArgumentException(sprintf('Repository factory "%s" not found', $repositoryFactory));
             }
             $config->setRepositoryFactory($serviceLocator->get($repositoryFactory));
         } else {
             $config->setRepositoryFactory($repositoryFactory);
         }
     }
     if ($entityListenerResolver = $options->getEntityListenerResolver()) {
         if ($entityListenerResolver instanceof EntityListenerResolver) {
             $config->setEntityListenerResolver($entityListenerResolver);
         } else {
             $config->setEntityListenerResolver($serviceLocator->get($entityListenerResolver));
         }
     }
     $this->setupDBALConfiguration($serviceLocator, $config);
     return $config;
 }
Esempio n. 2
0
 public function testSetGetNamingStrategy()
 {
     $this->assertInstanceOf('Doctrine\\ORM\\Mapping\\NamingStrategy', $this->configuration->getNamingStrategy());
     $namingStrategy = $this->getMock('Doctrine\\ORM\\Mapping\\NamingStrategy');
     $this->configuration->setNamingStrategy($namingStrategy);
     $this->assertSame($namingStrategy, $this->configuration->getNamingStrategy());
 }
Esempio n. 3
0
 /**
  * Creates a new EntityManager instance based on the provided configuration.
  *
  *     $factory = new Doctrine_EMFactory;
  *     $em = $factory->entity_manager();
  *
  * @param string $db_group the name of the Kohana database config group to get connection information from
  *
  * @return \Doctrine\ORM\EntityManager
  */
 public function entity_manager($db_group = 'default')
 {
     $config = $this->config->load('doctrine');
     // Ensure the composer autoloader is registered
     require_once $config['composer_vendor_path'] . 'autoload.php';
     // Create the Configuration class
     $orm_config = new Configuration();
     // Create the metadata driver
     $driver = $this->create_annotation_driver();
     $orm_config->setMetadataDriverImpl($driver);
     // Configure the proxy directory and namespace
     $orm_config->setProxyDir($config['proxy_dir']);
     $orm_config->setProxyNamespace($config['proxy_namespace']);
     if ($config->get('use_underscore_naming_strategy')) {
         $naming_strategy = new UnderscoreNamingStrategy($config->get('case_underscore_naming_strategy'));
         $orm_config->setNamingStrategy($naming_strategy);
     }
     // Configure environment-specific options
     if ($this->environment === Kohana::DEVELOPMENT) {
         $orm_config->setAutoGenerateProxyClasses(TRUE);
         $cache = new ArrayCache();
     } else {
         $orm_config->setAutoGenerateProxyClasses(FALSE);
         $cache = new ApcCache();
     }
     // Set the cache drivers
     $orm_config->setMetadataCacheImpl($cache);
     $orm_config->setQueryCacheImpl($cache);
     // Create the Entity Manager with the database connection information
     $em = EntityManager::create($this->get_connection_config($db_group), $orm_config);
     $this->register_custom_types($config);
     return $em;
 }
 /**
  * @param  ContainerInterface $container
  * @return EntityManager
  */
 public function __invoke(ContainerInterface $container)
 {
     $config = $container->has('config') ? $container->get('config') : [];
     if (!isset($config['doctrine'])) {
         throw new ServiceNotCreatedException('Missing Doctrine configuration');
     }
     $config = $config['doctrine'];
     $proxyDir = isset($config['proxy_dir']) ? $config['proxy_dir'] : 'data/DoctrineORM/Proxy';
     $proxyNamespace = isset($config['proxy_namespace']) ? $config['proxy_namespace'] : 'DoctrineORM/Proxy';
     $autoGenerateProxyClasses = isset($config['configuration']['auto_generate_proxy_classes']) ? $config['configuration']['auto_generate_proxy_classes'] : false;
     $underscoreNamingStrategy = isset($config['configuration']['underscore_naming_strategy']) ? $config['configuration']['underscore_naming_strategy'] : false;
     // Doctrine ORM
     $doctrine = new Configuration();
     $doctrine->setProxyDir($proxyDir);
     $doctrine->setProxyNamespace($proxyNamespace);
     $doctrine->setAutoGenerateProxyClasses($autoGenerateProxyClasses);
     // Naming Strategy
     if ($underscoreNamingStrategy) {
         $doctrine->setNamingStrategy(new UnderscoreNamingStrategy());
     }
     // ORM mapping by Annotation
     //AnnotationRegistry::registerAutoloadNamespace($config['driver']['annotations']['class']);
     AnnotationRegistry::registerFile('vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');
     $driver = new AnnotationDriver(new AnnotationReader(), $config['driver']['annotations']['paths']);
     $doctrine->setMetadataDriverImpl($driver);
     // Cache
     $cache = $container->get(\Doctrine\Common\Cache\Cache::class);
     $doctrine->setQueryCacheImpl($cache);
     $doctrine->setResultCacheImpl($cache);
     $doctrine->setMetadataCacheImpl($cache);
     // EntityManager
     return EntityManager::create($config['connection']['orm_default']['params'], $doctrine);
 }
 /**
  * @param \Doctrine\ORM\Configuration $config
  * @param array $options
  * @throws \InvalidArgumentException
  */
 protected static function setupNamingStrategy(Configuration &$config, array $options = [])
 {
     $namingStrategy = self::getOption($options, 'naming_strategy') ?: new UnderscoreNamingStrategy();
     if (!$namingStrategy instanceof NamingStrategy) {
         throw new \InvalidArgumentException('Naming strategy provided is not valid');
     }
     $config->setNamingStrategy($namingStrategy);
 }
 /**
  * @param ContainerInterface $container
  *
  * @return EntityManagerInterface
  * @throws ORMException
  */
 public function __invoke(ContainerInterface $container)
 {
     $config = $container->has('config') ? $container->get('config') : [];
     $proxyDir = isset($config['doctrine']['orm']['proxy_dir']) ? $config['doctrine']['orm']['proxy_dir'] : 'data/cache/EntityProxy';
     $proxyNamespace = isset($config['doctrine']['orm']['proxy_namespace']) ? $config['doctrine']['orm']['proxy_namespace'] : 'EntityProxy';
     $autoGenerateProxyClasses = isset($config['doctrine']['orm']['auto_generate_proxy_classes']) ? $config['doctrine']['orm']['auto_generate_proxy_classes'] : false;
     $underscoreNamingStrategy = isset($config['doctrine']['orm']['underscore_naming_strategy']) ? $config['doctrine']['orm']['underscore_naming_strategy'] : false;
     $entityPaths = isset($config['doctrine']['orm']['entity_paths']) ? $config['doctrine']['orm']['entity_paths'] : ['src'];
     // Doctrine ORM
     $doctrine = new Configuration();
     $doctrine->setProxyDir($proxyDir);
     $doctrine->setProxyNamespace($proxyNamespace);
     $doctrine->setAutoGenerateProxyClasses($autoGenerateProxyClasses);
     if ($underscoreNamingStrategy) {
         $doctrine->setNamingStrategy(new UnderscoreNamingStrategy());
     }
     // Cache
     $cache = $container->get(Cache::class);
     $doctrine->setQueryCacheImpl($cache);
     $doctrine->setResultCacheImpl($cache);
     $doctrine->setMetadataCacheImpl($cache);
     // ORM mapping by Annotation
     AnnotationRegistry::registerFile('vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');
     if (class_exists(DoctrineExtensions::class)) {
         DoctrineExtensions::registerAnnotations();
     }
     $cachedAnnotationReader = new CachedReader(new AnnotationReader(), $cache);
     $driver = new AnnotationDriver($cachedAnnotationReader, $entityPaths);
     $doctrine->setMetadataDriverImpl($driver);
     $eventManager = new EventManager();
     if (isset($config['doctrine']['orm']['event_subscribers'])) {
         foreach ($config['doctrine']['orm']['event_subscribers'] as $subscriber) {
             $subscriberInstance = $container->get($subscriber);
             if ($subscriberInstance instanceof MappedEventSubscriber) {
                 $subscriberInstance->setAnnotationReader($cachedAnnotationReader);
             }
             $eventManager->addEventSubscriber($subscriberInstance);
         }
     }
     $entityManager = EntityManager::create($config['doctrine']['connection']['orm_default'], $doctrine, $eventManager);
     // Types
     Type::addType('uuid', UuidType::class);
     $entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('uuid', 'uuid');
     if (isset($config['doctrine']['orm']['types'])) {
         foreach ($config['doctrine']['orm']['types'] as $type => $class) {
             Type::addType($type, $class);
         }
     }
     return $entityManager;
 }
Esempio n. 7
0
/*
 * Copyright 2015 Jack Sleight <http://jacksleight.com/>
 * This source file is subject to the MIT license that is bundled with this package in the file LICENCE.md. 
 */
use Doctrine\ORM\Configuration;
use Doctrine\Common\EventManager;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Proxy\Autoloader;
use Chalk\Doctrine\ORM\EntityManager as ChalkEntityManager;
use Chalk\Doctrine\NamingStrategy;
use Chalk\Listener;
\Coast\Doctrine\register_dbal_types();
if (!isset($app->config->database)) {
    throw new \Chalk\Exception('Database connection details are required');
}
$config = new Configuration();
$config->setNamingStrategy(new NamingStrategy());
$config->setMetadataDriverImpl($config->newDefaultAnnotationDriver());
$config->setProxyDir($app->config->dataDir->dir('proxy'));
$config->setProxyNamespace('Chalk\\Proxy');
$config->setAutoGenerateProxyClasses(false);
$config->setQueryCacheImpl($app->cache->value());
$config->setResultCacheImpl($app->cache->value());
$config->setMetadataCacheImpl($app->cache->value());
Autoloader::register($app->config->dataDir->dir('proxy'), 'Chalk\\Proxy');
$evm = new EventManager();
$evm->addEventSubscriber(new Listener());
$em = new ChalkEntityManager(EntityManager::create($app->config->database + ['driver' => 'pdo_mysql', 'charset' => 'utf8'], $config, $evm));
$em->getConnection()->exec("SET NAMES utf8");
Toast\Wrapper::$em = $em;
return $em;
 /**
  * @param array         $settings
  * @param Configuration $configuration
  */
 protected function setNamingStrategy(array $settings = [], Configuration $configuration)
 {
     $strategy = array_get($settings, 'naming_strategy', LaravelNamingStrategy::class);
     $configuration->setNamingStrategy($this->container->make($strategy));
 }
 /**
  * Setup naming strategy.
  *
  * @param \Doctrine\ORM\Configuration $config
  * @param array                       $options
  *
  * @throws \InvalidArgumentException
  */
 protected static function setupNamingStrategy(Configuration &$config, array $options)
 {
     $namingStrategy = $options['naming_strategy'] ?: new UnderscoreNamingStrategy(CASE_LOWER);
     if (!$namingStrategy instanceof NamingStrategy) {
         throw new \InvalidArgumentException('Naming strategy provided is not valid');
     }
     $config->setNamingStrategy($namingStrategy);
 }
 /**
  * {@inheritDoc}
  *
  * @return Configuration
  */
 public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
 {
     /** @var $options \DoctrineORMModule\Options\Configuration */
     $options = $this->getOptions($container);
     $config = new Configuration();
     $config->setAutoGenerateProxyClasses($options->getGenerateProxies());
     $config->setProxyDir($options->getProxyDir());
     $config->setProxyNamespace($options->getProxyNamespace());
     $config->setEntityNamespaces($options->getEntityNamespaces());
     $config->setCustomDatetimeFunctions($options->getDatetimeFunctions());
     $config->setCustomStringFunctions($options->getStringFunctions());
     $config->setCustomNumericFunctions($options->getNumericFunctions());
     $config->setClassMetadataFactoryName($options->getClassMetadataFactoryName());
     foreach ($options->getNamedQueries() as $name => $query) {
         $config->addNamedQuery($name, $query);
     }
     foreach ($options->getNamedNativeQueries() as $name => $query) {
         $config->addNamedNativeQuery($name, $query['sql'], new $query['rsm']());
     }
     foreach ($options->getCustomHydrationModes() as $modeName => $hydrator) {
         $config->addCustomHydrationMode($modeName, $hydrator);
     }
     foreach ($options->getFilters() as $name => $class) {
         $config->addFilter($name, $class);
     }
     $config->setMetadataCacheImpl($container->get($options->getMetadataCache()));
     $config->setQueryCacheImpl($container->get($options->getQueryCache()));
     $config->setResultCacheImpl($container->get($options->getResultCache()));
     $config->setHydrationCacheImpl($container->get($options->getHydrationCache()));
     $config->setMetadataDriverImpl($container->get($options->getDriver()));
     if ($namingStrategy = $options->getNamingStrategy()) {
         if (is_string($namingStrategy)) {
             if (!$container->has($namingStrategy)) {
                 throw new InvalidArgumentException(sprintf('Naming strategy "%s" not found', $namingStrategy));
             }
             $config->setNamingStrategy($container->get($namingStrategy));
         } else {
             $config->setNamingStrategy($namingStrategy);
         }
     }
     if ($quoteStrategy = $options->getQuoteStrategy()) {
         if (is_string($quoteStrategy)) {
             if (!$container->has($quoteStrategy)) {
                 throw new InvalidArgumentException(sprintf('Quote strategy "%s" not found', $quoteStrategy));
             }
             $config->setQuoteStrategy($container->get($quoteStrategy));
         } else {
             $config->setQuoteStrategy($quoteStrategy);
         }
     }
     if ($repositoryFactory = $options->getRepositoryFactory()) {
         if (is_string($repositoryFactory)) {
             if (!$container->has($repositoryFactory)) {
                 throw new InvalidArgumentException(sprintf('Repository factory "%s" not found', $repositoryFactory));
             }
             $config->setRepositoryFactory($container->get($repositoryFactory));
         } else {
             $config->setRepositoryFactory($repositoryFactory);
         }
     }
     if ($entityListenerResolver = $options->getEntityListenerResolver()) {
         if ($entityListenerResolver instanceof EntityListenerResolver) {
             $config->setEntityListenerResolver($entityListenerResolver);
         } else {
             $config->setEntityListenerResolver($container->get($entityListenerResolver));
         }
     }
     $secondLevelCache = $options->getSecondLevelCache();
     if ($secondLevelCache->isEnabled()) {
         $regionsConfig = new RegionsConfiguration($secondLevelCache->getDefaultLifetime(), $secondLevelCache->getDefaultLockLifetime());
         foreach ($secondLevelCache->getRegions() as $regionName => $regionConfig) {
             if (isset($regionConfig['lifetime'])) {
                 $regionsConfig->setLifetime($regionName, $regionConfig['lifetime']);
             }
             if (isset($regionConfig['lock_lifetime'])) {
                 $regionsConfig->setLockLifetime($regionName, $regionConfig['lock_lifetime']);
             }
         }
         // As Second Level Cache caches queries results, we reuse the result cache impl
         $cacheFactory = new DefaultCacheFactory($regionsConfig, $config->getResultCacheImpl());
         $cacheFactory->setFileLockRegionDirectory($secondLevelCache->getFileLockRegionDirectory());
         $cacheConfiguration = new CacheConfiguration();
         $cacheConfiguration->setCacheFactory($cacheFactory);
         $cacheConfiguration->setRegionsConfiguration($regionsConfig);
         $config->setSecondLevelCacheEnabled();
         $config->setSecondLevelCacheConfiguration($cacheConfiguration);
     }
     if ($className = $options->getDefaultRepositoryClassName()) {
         $config->setDefaultRepositoryClassName($className);
     }
     $this->setupDBALConfiguration($container, $config);
     return $config;
 }
 /**
  * Configures the metadata configuration instance.
  *
  * @param Configuration $configuration
  * @param array                       $doctrineConfig
  *
  * @throws ORMException
  */
 protected function configureMetadataConfiguration(Configuration $configuration, array $doctrineConfig)
 {
     if (isset($doctrineConfig['filters'])) {
         foreach ($doctrineConfig['filters'] as $name => $filter) {
             $configuration->addFilter($name, $filter['class']);
         }
     }
     if (isset($doctrineConfig['logger'])) {
         $configuration->setSQLLogger($doctrineConfig['logger']);
     }
     if (isset($doctrineConfig['proxy']) && isset($doctrineConfig['proxy']['auto_generate'])) {
         $configuration->setAutoGenerateProxyClasses($doctrineConfig['proxy']['auto_generate']);
     }
     if (isset($doctrineConfig['proxy']) && isset($doctrineConfig['proxy']['namespace'])) {
         $configuration->setProxyNamespace($doctrineConfig['proxy']['namespace']);
     }
     if (isset($doctrineConfig['repository'])) {
         $configuration->setDefaultRepositoryClassName($doctrineConfig['repository']);
     }
     $namingStrategy = array_get($doctrineConfig, 'naming_strategy', 'Nord\\Lumen\\Doctrine\\ORM\\NamingStrategy');
     $configuration->setNamingStrategy(new $namingStrategy());
 }
Esempio n. 12
0
 /**
  * @inheritdoc
  */
 public function start()
 {
     parent::start();
     $connectionConfig = $this->config('connection');
     if (!empty($connectionConfig) && is_array($connectionConfig)) {
         // Setup Doctrine. Largely borrowed from
         // https://github.com/l3pp4rd/DoctrineExtensions/blob/master/doc/annotations.md#em-setup
         // Register Doctrine default annotations.
         AnnotationRegistry::registerFile($this->getEngine()->getSiteInfo()->getSiteRoot() . '/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');
         // Setup annotation metadata cache
         if ($this->getEngine()->getEnvironmentInfo()->isDevMode() || !$this->getEngine()->config('memcache.enabled')) {
             $cache = new ArrayCache();
         } else {
             $cache = new MemcacheCache();
             $cache->setMemcache($this->getEngine()->getMemcache());
         }
         // Setup annotation metadata reader and driver
         /** @var AnnotationReader $cachedAnnotationReader (for all intents and purposes...) */
         $cachedAnnotationReader = new CachedReader(new AnnotationReader(), $cache);
         $this->driverChain = new MappingDriverChain();
         $this->annotationDriver = new AnnotationDriver($cachedAnnotationReader, array($this->getEngine()->getApplicationInfo()->getSitegearRoot()));
         // Setup Gedmo extension annotations
         \Gedmo\DoctrineExtensions::registerAnnotations();
         $this->driverChain->addDriver($this->annotationDriver, 'Gedmo');
         // Setup Sitegear extension annotations
         // TODO Make model-providing modules declare their own namespaces
         $this->driverChain->addDriver($this->annotationDriver, 'Sitegear\\Module\\Customer\\Model');
         $this->driverChain->addDriver($this->annotationDriver, 'Sitegear\\Module\\News\\Model');
         $this->driverChain->addDriver($this->annotationDriver, 'Sitegear\\Module\\Locations\\Model');
         $this->driverChain->addDriver($this->annotationDriver, 'Sitegear\\Module\\Products\\Model');
         // Create the entity manager configuration, with proxy generation, cached metadata and lowercase-underscore
         // database naming convention.
         $entityManagerConfig = new Configuration();
         // TODO Make this a temp directory set in the engine config
         $entityManagerConfig->setProxyDir(sys_get_temp_dir());
         // TODO Configurable namespace and naming strategy
         $entityManagerConfig->setProxyNamespace('Proxy');
         $entityManagerConfig->setAutoGenerateProxyClasses($this->getEngine()->getEnvironmentInfo()->isDevMode());
         $entityManagerConfig->setMetadataDriverImpl($this->driverChain);
         $entityManagerConfig->setMetadataCacheImpl($cache);
         $entityManagerConfig->setQueryCacheImpl($cache);
         $entityManagerConfig->setNamingStrategy(new UnderscoreNamingStrategy(CASE_LOWER));
         // Setup event subscribers.
         $eventManager = new EventManager();
         foreach ($this->config('orm.subscribers') as $subscriberConfig) {
             /** @var \Doctrine\Common\EventSubscriber $subscriber */
             $subscriber = TypeUtilities::buildTypeCheckedObject($subscriberConfig['class'], 'event subscriber', null, array('\\Doctrine\\Common\\EventSubscriber'), isset($subscriberConfig['arguments']) ? $subscriberConfig['arguments'] : array());
             if ($subscriber instanceof MappedEventSubscriber) {
                 /** @var MappedEventSubscriber $subscriber */
                 $subscriber->setAnnotationReader($cachedAnnotationReader);
             }
             $eventManager->addEventSubscriber($subscriber);
         }
         // Create the entity manager using the configured connection parameters.
         $this->entityManager = EntityManager::create($this->config('connection'), $entityManagerConfig, $eventManager);
         // Register the JSON custom data type.  This has to be done last, when the entity manager has a connection.
         foreach ($this->config('dbal.types') as $key => $className) {
             Type::addType($key, $className);
             $this->entityManager->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping(preg_replace('/^.*\\\\(.*?)$/', '$1', $className), $key);
         }
     } else {
         throw new \DomainException('<h1>Incorrect or Missing Configuration</h1><p>You have attempted to use the Doctrine module in your site, but you have not provided all the required connection parameters in your configuration file.</p><p>Please rectify this by providing connection parameters ("driver", "dbname", plus normally "username" and "password") or disabling the Doctrine module.</p>');
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function createWithConfig(ContainerInterface $container, $configKey)
 {
     $config = $this->retrieveConfig($container, $configKey, 'configuration');
     $configuration = new Configuration();
     $configuration->setProxyDir($config['proxy_dir']);
     $configuration->setProxyNamespace($config['proxy_namespace']);
     $configuration->setAutoGenerateProxyClasses($config['auto_generate_proxy_classes']);
     $configuration->setEntityNamespaces($config['entity_namespaces']);
     $configuration->setCustomDatetimeFunctions($config['datetime_functions']);
     $configuration->setCustomStringFunctions($config['string_functions']);
     $configuration->setCustomNumericFunctions($config['numeric_functions']);
     $configuration->setCustomHydrationModes($config['custom_hydration_modes']);
     $configuration->setClassMetadataFactoryName($config['class_metadata_factory_name']);
     foreach ($config['named_queries'] as $name => $dql) {
         $configuration->addNamedQuery($name, $dql);
     }
     foreach ($config['named_native_queries'] as $name => $query) {
         $configuration->addNamedNativeQuery($name, $query['sql'], $query['rsm']);
     }
     foreach ($config['filters'] as $name => $className) {
         $configuration->addFilter($name, $className);
     }
     $configuration->setMetadataCacheImpl($this->retrieveDependency($container, $config['metadata_cache'], 'cache', CacheFactory::class));
     $configuration->setQueryCacheImpl($this->retrieveDependency($container, $config['query_cache'], 'cache', CacheFactory::class));
     $configuration->setResultCacheImpl($this->retrieveDependency($container, $config['result_cache'], 'cache', CacheFactory::class));
     $configuration->setHydrationCacheImpl($this->retrieveDependency($container, $config['hydration_cache'], 'cache', CacheFactory::class));
     $configuration->setMetadataDriverImpl($this->retrieveDependency($container, $config['driver'], 'driver', DriverFactory::class));
     if (is_string($config['naming_strategy'])) {
         $configuration->setNamingStrategy($container->get($config['naming_strategy']));
     } elseif (null !== $config['naming_strategy']) {
         $configuration->setNamingStrategy($config['naming_strategy']);
     }
     if (is_string($config['repository_factory'])) {
         $configuration->setRepositoryFactory($container->get($config['repository_factory']));
     } elseif (null !== $config['repository_factory']) {
         $configuration->setRepositoryFactory($config['repository_factory']);
     }
     if (is_string($config['entity_listener_resolver'])) {
         $configuration->setEntityListenerResolver($container->get($config['entity_listener_resolver']));
     } elseif (null !== $config['entity_listener_resolver']) {
         $configuration->setEntityListenerResolver($config['entity_listener_resolver']);
     }
     if (null !== $config['default_repository_class_name']) {
         $configuration->setDefaultRepositoryClassName($config['default_repository_class_name']);
     }
     if ($config['second_level_cache']['enabled']) {
         $regionsConfig = new RegionsConfiguration($config['second_level_cache']['default_lifetime'], $config['second_level_cache']['default_lock_lifetime']);
         foreach ($config['second_level_cache']['regions'] as $regionName => $regionConfig) {
             if (array_key_exists('lifetime', $regionConfig)) {
                 $regionsConfig->setLifetime($regionName, $regionConfig['lifetime']);
             }
             if (array_key_exists('lock_lifetime', $regionConfig)) {
                 $regionsConfig->setLockLifetime($regionName, $regionConfig['lock_lifetime']);
             }
         }
         $cacheFactory = new DefaultCacheFactory($regionsConfig, $configuration->getResultCacheImpl());
         $cacheFactory->setFileLockRegionDirectory($config['second_level_cache']['file_lock_region_directory']);
         $cacheConfiguration = new CacheConfiguration();
         $cacheConfiguration->setCacheFactory($cacheFactory);
         $cacheConfiguration->setRegionsConfiguration($regionsConfig);
         $configuration->setSecondLevelCacheEnabled(true);
         $configuration->setSecondLevelCacheConfiguration($cacheConfiguration);
     }
     if (is_string($config['sql_logger'])) {
         $configuration->setSQLLogger($container->get($config['sql_logger']));
     } elseif (null !== $config['sql_logger']) {
         $configuration->setSQLLogger($config['sql_logger']);
     }
     return $configuration;
 }
Esempio n. 14
0
 public function register(Container $c)
 {
     parent::register($c);
     $c['orm.options'] = array();
     $c['orm.types'] = array();
     $c['orm.proxies_dir'] = sys_get_temp_dir();
     $c['orm.proxies_namespace'] = 'DoctrineProxy';
     $c['orm.auto_generate_proxies'] = $c->factory(function ($c) {
         return $c['debug'];
     });
     $c['orm.custom.functions.string'] = array();
     $c['orm.custom.functions.numeric'] = array();
     $c['orm.custom.functions.datetime'] = array();
     $c['orm.custom.hydration_modes'] = array();
     $c['orm.class_metadata_factory_name'] = 'Doctrine\\ORM\\Mapping\\ClassMetadataFactory';
     $c['orm.default_repository_class'] = 'Doctrine\\ORM\\EntityRepository';
     $c['orm.initialize'] = $c->protect(function () use($c) {
         static $initialized = false;
         if ($initialized) {
             return;
         }
         $initialized = true;
         if (!isset($c['orm.options'])) {
             $c['orm.options'] = array('default' => array());
         } elseif (!is_array(reset($c['orm.options']))) {
             // Se o primeiro elemento do array de opções não for um array,
             // muito provavelmente o usuário está colocando as options de
             // uma única conexão, então usar como default
             $c['orm.options'] = array('default' => $c['orm.options']);
         }
         $tmp = $c['orm.options'];
         foreach ($tmp as $name => &$options) {
             if (!isset($options['connection'])) {
                 throw new \LogicException("Missing 'connection' param in Doctrine ORM in {$name}.");
             }
             if (is_string($options['connection'])) {
                 $options['connection'] = $c['dbal.options'][$options['connection']];
             } elseif (!is_array($options['connection']) && !$options['connection'] instanceof Connection) {
                 throw new \LogicException("Param 'connection' in {$name} must be a string, array or a Connection instance.");
             }
         }
         $c['orm.options'] = $tmp;
         $c['orm.defaultName'] = key($c['orm.options']);
     });
     $c['orm.ems'] = function ($c) {
         $c['orm.initialize']();
         $ems = new Container();
         foreach ($c['orm.options'] as $name => $options) {
             $config = $c['orm.configs'][$name];
             $connection = $options['connection'];
             $ems[$name] = function ($ems) use($connection, $config) {
                 return EntityManager::create($connection, $config);
             };
         }
         return $ems;
     };
     $c['orm.configs'] = function ($c) {
         $c['orm.initialize']();
         $configs = new Container();
         foreach ($c['orm.options'] as $name => $options) {
             $configs[$name] = $config = new Configuration();
             $config->setProxyDir($c['orm.proxies_dir']);
             $config->setProxyNamespace($c['orm.proxies_namespace']);
             $config->setAutoGenerateProxyClasses($c['orm.auto_generate_proxies']);
             $config->setCustomStringFunctions($c['orm.custom.functions.string']);
             $config->setCustomNumericFunctions($c['orm.custom.functions.numeric']);
             $config->setCustomDatetimeFunctions($c['orm.custom.functions.datetime']);
             $config->setCustomHydrationModes($c['orm.custom.hydration_modes']);
             $config->setClassMetadataFactoryName($c['orm.class_metadata_factory_name']);
             $config->setDefaultRepositoryClassName($c['orm.default_repository_class']);
             $config->setEntityListenerResolver($c['orm.entity_listener_resolver']);
             $config->setRepositoryFactory($c['orm.repository_factory']);
             $config->setNamingStrategy($c['orm.strategy.naming']);
             $config->setQuoteStrategy($c['orm.strategy.quote']);
             $chain = new MappingDriverChain();
             $config->setMetadataDriverImpl($chain);
             foreach ((array) $options['mappings'] as $entity) {
                 if (!is_array($entity)) {
                     throw new \InvalidArgumentException("The 'orm.options' option 'mappings' should be an array of arrays.");
                 }
                 if (isset($entity['alias'])) {
                     $config->addEntityNamespace($entity['alias'], $entity['namespace']);
                 }
                 switch ($entity['type']) {
                     case 'annotation':
                         if (isset($c['annotation.reader'])) {
                             $driver = new AnnotationDriver($c['annotation.reader'], (array) $entity['path']);
                         } else {
                             $simple = isset($entity['use_simple_annotation_reader']) ? $entity['use_simple_annotation_reader'] : true;
                             $driver = $config->newDefaultAnnotationDriver((array) $entity['path'], $simple);
                         }
                         break;
                     case 'yml':
                         $driver = new YamlDriver($entity['path']);
                         break;
                     case 'simple_yml':
                         $driver = new SimplifiedYamlDriver(array($entity['path'] => $entity['namespace']));
                         break;
                     case 'xml':
                         $driver = new XmlDriver($entity['path']);
                         break;
                     case 'simple_xml':
                         $driver = new SimplifiedXmlDriver(array($entity['path'] => $entity['namespace']));
                         break;
                     case 'php':
                         $driver = new StaticPHPDriver($entity['path']);
                         break;
                     default:
                         throw new \InvalidArgumentException(sprintf('"%s" is not a recognized driver', $entity['type']));
                 }
                 $chain->addDriver($driver, $entity['namespace']);
             }
         }
         foreach ((array) $c['orm.types'] as $typeName => $typeClass) {
             if (Type::hasType($typeName)) {
                 Type::overrideType($typeName, $typeClass);
             } else {
                 Type::addType($typeName, $typeClass);
             }
         }
         return $configs;
     };
     $c['orm.strategy.naming'] = function ($c) {
         return new DefaultNamingStrategy();
     };
     $c['orm.strategy.quote'] = function ($c) {
         return new DefaultQuoteStrategy();
     };
     $c['orm.entity_listener_resolver'] = function ($c) {
         return new DefaultEntityListenerResolver();
     };
     $c['orm.repository_factory'] = function ($c) {
         return new DefaultRepositoryFactory();
     };
     $c->extend('doctrine.registry', function ($registry, $c) {
         $c['orm.initialize']();
         return new OrmRegistry($c['dbal.conns'], $c['orm.ems'], 'Doctrine\\Common\\Persistence\\Proxy', array_keys($c['dbal.options']), array_keys($c['orm.options']), $c['dbal.defaultName'], $c['orm.defaultName']);
     });
     // TODO passar pro Container\ValidatorExtensionableProviderInterface
     if (isset($c['validator.object_initializers'])) {
         $c->extend('validator.object_initializers', function ($initializers, $c) {
             $initializers[] = new DoctrineInitializer($c['doctrine.registry']);
             $c['doctrine.orm.validator.unique'] = new UniqueEntityValidator($c['doctrine.registry']);
             return $initializers;
         });
     }
 }
Esempio n. 15
0
 protected function setupNamingStrategy(Configuration $config, $spec)
 {
     $strategyClass = $spec['naming_strategy'];
     if (isset($strategyClass)) {
         $strategy = new $strategyClass();
         $config->setNamingStrategy($strategy);
         if (isset($spec['table_prefixes']) && method_exists($strategy, 'setTablePrefixes')) {
             $strategy->setTablePrefixes($spec['table_prefixes']);
         }
     }
 }