示例#1
0
 /**
  * @return EntityManager
  */
 protected function getEntityManager()
 {
     if (null !== $this->em) {
         return $this->em;
     }
     $config = new Configuration();
     $config->setMetadataCacheImpl(new ArrayCache());
     $config->setQueryCacheImpl(new ArrayCache());
     $config->setProxyDir(__DIR__ . '/Proxies');
     $config->setAutoGenerateProxyClasses(ProxyFactory::AUTOGENERATE_EVAL);
     $config->setProxyNamespace('SimpleThings\\EntityAudit\\Tests\\Proxies');
     $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver(array(realpath(__DIR__ . '/Fixtures/Core'), realpath(__DIR__ . '/Fixtures/Issue'), realpath(__DIR__ . '/Fixtures/Relation')), false));
     Gedmo\DoctrineExtensions::registerAnnotations();
     $connection = $this->_getConnection();
     // get rid of more global state
     $evm = $connection->getEventManager();
     foreach ($evm->getListeners() as $event => $listeners) {
         foreach ($listeners as $listener) {
             $evm->removeEventListener(array($event), $listener);
         }
     }
     $this->em = EntityManager::create($connection, $config);
     if (isset($this->customTypes) and is_array($this->customTypes)) {
         foreach ($this->customTypes as $customTypeName => $customTypeClass) {
             if (!Type::hasType($customTypeName)) {
                 Type::addType($customTypeName, $customTypeClass);
             }
             $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('db_' . $customTypeName, $customTypeName);
         }
     }
     return $this->em;
 }
 /**
  *
  * @param array $config
  * @return DocumentManager
  */
 public static function createDocumentManager($config, Container $container)
 {
     $configuration = new Configuration();
     if (is_null($config['eventManager'])) {
         $evm = new EventManager();
     } else {
         $evm = $config['eventManager'];
     }
     $configuration->setProxyDir($config['proxyDir']);
     $configuration->setProxyNamespace($config['proxyNamespace']);
     $configuration->setHydratorDir($config['hydratorDir']);
     $configuration->setHydratorNamespace($config['hydratorNamespace']);
     $configuration->setAutoGenerateHydratorClasses($config['autoGenerateHydratorClasses']);
     $configuration->setAutoGenerateProxyClasses($config['autoGenerateProxyClasses']);
     if (isset($config['metaDataCache'])) {
         $metadataCache = $config['metaDataCache'];
     } else {
         $metadataCache = new $config['metaDataCacheClass']();
         $metadataCache->setNamespace($config['cachePrefix']);
     }
     $configuration->setMetadataCacheImpl($metadataCache);
     AnnotationDriver::registerAnnotationClasses();
     $reader = new AnnotationReader();
     if ($config['cacheAnnotations'] == TRUE) {
         $reader = new CachedReader($reader, $metadataCache, $config['debug']);
     }
     if ($config['indexAnnotations'] == TRUE) {
         $reader = new IndexedReader($reader);
     }
     if (class_exists(\Gedmo\DoctrineExtensions::class)) {
         \Gedmo\DoctrineExtensions::registerAnnotations();
         $configuration->addFilter('soft-deleteable', \Gedmo\SoftDeleteable\Filter\ODM\SoftDeleteableFilter::class);
         foreach ($config['listeners'] as $listenerName => $enabled) {
             if ($enabled) {
                 $listener = self::configureListener($listenerName, $reader);
                 $evm->addEventSubscriber($listener);
             }
         }
     }
     $driverImpl = new AnnotationDriver($reader, $config['documentsDir']);
     $configuration->setMetadataDriverImpl($driverImpl);
     $configuration->setDefaultDB($config['dbname']);
     $logger = new Logger($config['logger'], $config['loggerPrefix']);
     $configuration->setLoggerCallable([$logger, 'logQuery']);
     $mongo = new MongoClient($config['uri'], $config['mongoOptions']);
     $connection = new Connection($mongo);
     $dm = DocumentManager::create($connection, $configuration, $evm);
     foreach ($config['filters'] as $filter => $enabled) {
         if ($enabled) {
             $dm->getFilterCollection()->enable($filter);
         }
     }
     return $dm;
 }
 /**
  * @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;
 }
示例#4
0
 private function setupOrms()
 {
     $app = $this;
     // Override "orm.cache.configurer" service provided for benefiting
     // of "phraseanet.cache-service"
     $app['orm.cache.configurer'] = $app->protect(function ($name, Configuration $config, $options) use($app) {
         /** @var Manager $service */
         $service = $app['phraseanet.cache-service'];
         $config->setMetadataCacheImpl($service->factory('ORM_metadata', $app['orm.cache.driver'], $app['orm.cache.options']));
         $config->setQueryCacheImpl($service->factory('ORM_query', $app['orm.cache.driver'], $app['orm.cache.options']));
         $config->setResultCacheImpl($service->factory('ORM_result', $app['orm.cache.driver'], $app['orm.cache.options']));
         $config->setHydrationCacheImpl($service->factory('ORM_hydration', $app['orm.cache.driver'], $app['orm.cache.options']));
     });
     $app['orm.proxies_dir'] = $app['root.path'] . '/resources/proxies';
     $app['orm.auto_generate_proxies'] = $app['debug'];
     $app['orm.proxies_namespace'] = 'Alchemy\\Phrasea\\Model\\Proxies';
     $this['orm.ems'] = $this->share($this->extend('orm.ems', function (\Pimple $ems, $app) {
         GedmoExtension::registerAnnotations();
         foreach ($ems->keys() as $key) {
             $app['orm.annotation.register']($key);
             $connection = $ems[$key]->getConnection();
             $app['connection.pool.manager']->add($connection);
             $types = $app['orm.ems.options'][$key]['types'];
             $app['dbal.type.register']($connection, $types);
         }
         return $ems;
     }));
 }
示例#5
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>');
     }
 }
示例#6
0
文件: app.php 项目: kulishkin/gis
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Normalizer\PropertyNormalizer;
use Dflydev\Silex\Provider\DoctrineOrm\DoctrineOrmServiceProvider;
$app = new Application();
$app['profiling.start'] = microtime(true);
$app->register(new MonologServiceProvider(), ['monolog.logfile' => __DIR__ . '/../var/logs/prod.log', 'monolog.level' => Logger::ERROR]);
$app->register(new ServiceControllerServiceProvider());
$app->register(new SerializerServiceProvider());
$app['serializer.normalizers'] = $app->share(function () {
    return [new PropertyNormalizer(new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader())))];
});
$app->register(new DoctrineServiceProvider(), ['db.options' => ['driver' => 'pdo_mysql', 'host' => 'localhost', 'dbname' => 'gis', 'user' => 'root', 'password' => 'test', 'charset' => 'utf8mb4']]);
$app->register(new DoctrineOrmServiceProvider(), ['orm.proxies_dir' => __DIR__ . '/Gis/Proxy', 'orm.default_cache' => 'apc', 'orm.em.options' => ['mappings' => [['type' => 'annotation', 'namespace' => 'Gis\\Entity', 'path' => __DIR__ . '/Gis/Entity', 'use_simple_annotation_reader' => false]]], 'orm.custom.functions.numeric' => ['DISTANCE' => 'Gis\\Doctrine\\Query\\Mysql\\Distance']]);
$app->register(new UrlGeneratorServiceProvider());
$app->get('/', function () use($app) {
    return $app->redirect('/api/v1');
});
$apiProvider = new ApiProvider();
$app->register($apiProvider);
$app->mount('/api/v1', $apiProvider);
$app->error(function (\Exception $e, $code) use($app) {
    $app['monolog']->addError($e->getMessage());
    $app['monolog']->addError($e->getTraceAsString());
    return new Response($app['serializer']->serialize(ResponseMeta::error($e->getMessage()), $app['request']->getRequestFormat('json')), Response::HTTP_INTERNAL_SERVER_ERROR);
});
AnnotationRegistry::registerFile(__DIR__ . '/../vendor/symfony/serializer/Annotation/Groups.php');
DoctrineExtensions::registerAnnotations();
$treeListener = new TreeListener();
$app['db.event_manager']->addEventSubscriber($treeListener);
return $app;