/**
  * @dataProvider extractorsDataProvider
  *
  * @param $class
  * @param $extractor
  * @param $properties
  */
 public function testExtractors($class, $extractor, $properties)
 {
     $config = Setup::createAnnotationMetadataConfiguration([__DIR__], true);
     $entityManager = EntityManager::create(['driver' => 'pdo_sqlite'], $config);
     /** @var TypeExtractorInterface $extractor */
     $extractor = new $extractor($entityManager->getMetadataFactory());
     $propertyInfo = new PropertyInfo([$extractor], []);
     foreach ($properties as $property) {
         $reflectionProperty = new \ReflectionProperty($class, $property['name']);
         $expectedType = $property['type'];
         /** @var Type[] $actualTypes */
         $actualTypes = $propertyInfo->getTypes($reflectionProperty);
         $actualType = $actualTypes[0];
         if ($expectedType !== null) {
             $this->assertEquals($expectedType, $actualType->getType());
             $this->assertEquals($property['class'], $actualType->getClass());
             $this->assertEquals($property['collection'], $actualType->isCollection());
             if (isset($property['collectionType'])) {
                 $actualCollectionType = $actualType->getCollectionType();
                 $this->assertEquals($property['collectionType']['type'], $actualCollectionType->getType());
                 $this->assertEquals($property['collectionType']['class'], $actualCollectionType->getClass());
                 $this->assertEquals($property['collectionType']['collection'], $actualCollectionType->isCollection());
             }
         } else {
             $this->assertNull($actualType);
         }
     }
 }
예제 #2
0
 /**
  * @return EntityManager
  * @throws ServiceNotRegisteredException
  */
 public static function getEntityManager()
 {
     if (ServiceLocator::$entityManager === null) {
         ServiceLocator::$entityManager = EntityManager::create(['driver' => Config::DB_DRIVER, 'host' => Config::DB_HOST, 'dbname' => Config::DB_NAME, 'user' => Config::DB_USER, 'password' => Config::DB_PASS], Setup::createAnnotationMetadataConfiguration([__DIR__ . '/../Models'], Config::DEV_MODE, null, null, false));
     }
     return ServiceLocator::checkAndReturn(ServiceLocator::$entityManager);
 }
예제 #3
0
 public function __construct()
 {
     try {
         $conn = array("driver" => "pdo_mysql", "host" => "localhost", "port" => "3306", "user" => "root", "password" => "", "dbname" => "controle_gastos");
         /*
         var_dump(__DIR__);
         var_dump(PP);
         exit;
         */
         $loader = new \Doctrine\Common\ClassLoader("Entities", __DIR__);
         $loader->register();
         $config = Setup::createAnnotationMetadataConfiguration(array("../../" . __DIR__ . "/app/models"), false);
         $em = EntityManager::create($conn, $config);
         $cmf = new DisconnectedClassMetadataFactory();
         $cmf->setEntityManager($em);
         $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
         $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('enum', 'string');
         $driver = new DatabaseDriver($em->getConnection()->getSchemaManager());
         $em->getConfiguration()->setMetadataDriverImpl($driver);
         $metadata = $cmf->getAllMetadata();
         $generator = new EntityGenerator();
         $generator->setGenerateAnnotations(true);
         $generator->setGenerateStubMethods(true);
         $generator->setRegenerateEntityIfExists(true);
         $generator->setUpdateEntityIfExists(true);
         $generator->generate($metadata, "../../" . __DIR__ . "/app/models");
     } catch (\Exception $e) {
         throw $e;
     }
 }
예제 #4
0
 public function register(Application $app)
 {
     $paths = array(realpath($app['config']['doctrine']['paths']['entity']));
     $isDevMode = $app['config']['doctrine']['devMode'];
     $config = Setup::createAnnotationMetadataConfiguration($paths, $isDevMode, null, null, false);
     $app['doctrine'] = EntityManager::create($app['config']['doctrine']['db'], $config);
 }
예제 #5
0
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     $config = $serviceLocator->get('config');
     // The parameters in Doctrine 2 and ZF2 are slightly different.
     // Below is an example how we can reuse the db settings
     $doctrineDbConfig = (array) $config['db'];
     $doctrineDbConfig['driver'] = strtolower($doctrineDbConfig['driver']);
     if (!isset($doctrineDbConfig['dbname'])) {
         $doctrineDbConfig['dbname'] = $doctrineDbConfig['database'];
     }
     if (!isset($doctrineDbConfig['host'])) {
         $doctrineDbConfig['host'] = $doctrineDbConfig['hostname'];
     }
     if (!isset($doctrineDbConfig['user'])) {
         $doctrineDbConfig['user'] = $doctrineDbConfig['username'];
     }
     $doctrineConfig = Setup::createAnnotationMetadataConfiguration($config['doctrine']['entity_path'], true);
     $entityManager = DoctrineEntityManager::create($doctrineDbConfig, $doctrineConfig);
     if (isset($config['doctrine']['initializers'])) {
         $eventManager = $entityManager->getEventManager();
         foreach ($config['doctrine']['initializers'] as $initializer) {
             $eventClass = new DoctrineEvent(new $initializer(), $serviceLocator);
             $eventManager->addEventListener(\Doctrine\ORM\Events::postLoad, $eventClass);
         }
     }
     if ($serviceLocator->has('doctrine-profiler')) {
         $profiler = $serviceLocator->get('doctrine-profiler');
         $entityManager->getConfiguration()->setSQLLogger($profiler);
     }
     return $entityManager;
 }
 public function setUp()
 {
     // register our custom type
     if (!Type::hasType('hstore')) {
         Type::addType('hstore', 'EasyBib\\Doctrine\\Types\\Hstore');
     }
     $isDevMode = true;
     $doctrineConfig = Setup::createAnnotationMetadataConfiguration(array(__DIR__ . '/Entity'), $isDevMode);
     // database configuration parameters
     $rootTestsFolder = dirname(dirname(dirname(dirname(__DIR__))));
     $this->isTravis = getenv("TRAVIS");
     if (file_exists($rootTestsFolder . '/db-config.php')) {
         $dbConfig = (include $rootTestsFolder . '/db-config.php');
     } elseif (false !== $this->isTravis) {
         $dbConfig = (include $rootTestsFolder . '/db-config-travisci.php');
     } else {
         throw new \RuntimeException("No database configuration found.");
     }
     // create the entity manager
     $this->em = EntityManager::create($dbConfig, $doctrineConfig);
     // enable 'hstore'
     $this->em->getConnection()->exec("CREATE EXTENSION IF NOT EXISTS hstore");
     // register type with DBAL
     $this->em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('hstore', 'hstore');
     // make the PersistentObject happy
     PersistentObject::setObjectManager($this->em);
     // create table
     $this->setUpSchema($this->em);
 }
예제 #7
0
 /**
  * @param array $database
  * @throws \Exception
  */
 public function __construct($database = [])
 {
     $this->db = $database;
     foreach ($this->db as $key => $db) {
         $this->allDb[$key] = function () use($db) {
             $db['dev'] = isset($db['dev']) && $db['dev'] ? true : false;
             if (isset($db['db_url'])) {
                 $dbParams = array('url' => $db['db_url']);
             } else {
                 if (!isset($db['driver']) || !isset($db['user']) || !isset($db['pass']) || !isset($db['host']) || !isset($db['db'])) {
                     throw new \Exception('Missing arguments for doctrine constructor');
                 }
                 $dbParams = array('driver' => $this->getDriver($db['driver']), 'user' => $db['user'], 'password' => $db['pass'], 'host' => $db['host'], 'dbname' => $db['db'], 'charset' => isset($db['charset']) ? $db['charset'] : 'utf8');
             }
             $evm = new EventManager();
             if (isset($db['prefix'])) {
                 $tablePrefix = new TablePrefix($db['prefix']);
                 $evm->addEventListener(Events::loadClassMetadata, $tablePrefix);
             }
             $config = Setup::createAnnotationMetadataConfiguration($db['path'], $db['dev']);
             if (!$db['dev']) {
                 $config->setQueryCacheImpl($db['cache']);
                 $config->setResultCacheImpl($db['cache']);
                 $config->setMetadataCacheImpl($db['cache']);
             }
             if (isset($db['functions']) && !empty($db['functions'])) {
                 $config->setCustomDatetimeFunctions($db['functions']['customDatetimeFunctions']);
                 $config->setCustomNumericFunctions($db['functions']['customNumericFunctions']);
                 $config->setCustomStringFunctions($db['functions']['customStringFunctions']);
             }
             return EntityManager::create($dbParams, $config, $evm);
         };
     }
 }
 /**
  * @param ApplicationInterface $app
  *
  * @throws \Doctrine\ORM\ORMException
  * @throws \ObjectivePHP\Primitives\Exception
  * @throws \ObjectivePHP\ServicesFactory\Exception
  */
 public function buildEntityManagers(ApplicationInterface $app)
 {
     $entityManagers = $app->getConfig()->subset(Config\EntityManager::class);
     foreach ($entityManagers as $connection => $params) {
         if (isset($params['db'])) {
             $params = $params['db'];
         }
         // normalize if needed
         $entitiesPaths = $params['entities.locations'];
         Collection::cast($entitiesPaths)->each(function (&$path) {
             if (strpos($path, '/') !== 0) {
                 $path = getcwd() . '/' . $path;
             }
         });
         // TODO: handle isDev depending on app config
         $emConfig = Setup::createAnnotationMetadataConfiguration((array) $entitiesPaths, true);
         $emConfig->setNamingStrategy(new UnderscoreNamingStrategy());
         $em = EntityManager::create($params, $emConfig);
         if (!empty($params['mapping_types']) && is_array($params['mapping_types'])) {
             $platform = $em->getConnection()->getDatabasePlatform();
             foreach ($params['mapping_types'] as $type => $mapping) {
                 if (!Type::hasType($type) && class_exists($mapping)) {
                     Type::addType($type, $mapping);
                     $mapping = $type;
                 }
                 $platform->registerDoctrineTypeMapping($type, $mapping);
             }
         }
         // register entity manager as a service
         $emServiceId = 'doctrine.em.' . Str::cast($connection)->lower();
         $app->getServicesFactory()->registerService(['id' => $emServiceId, 'instance' => $em]);
         $app->getServicesFactory()->registerService(['id' => 'db.connection.' . $connection, 'instance' => $em->getConnection()->getWrappedConnection()]);
     }
 }
예제 #9
0
 /**
  * @return void
  */
 public function init()
 {
     if ($this->isInitialized()) {
         return;
     }
     $context = $this->getApplication()->getContext();
     $this->serviceConfig = $this->getServiceConfig();
     $this->config = $this->getServiceConfig();
     $this->eventManager = new EventManager();
     $conn = $context->pluck('phpcrystal.phpcrystal.database')->toArray();
     // database connection config
     $isDevEnv = $context->getEnv() == 'dev';
     $this->ormConfig = Setup::createAnnotationMetadataConfiguration([], $isDevEnv);
     $this->ormConfig = new Configuration();
     $cache = new ArrayCache();
     $this->ormConfig->setMetadataCacheImpl($cache);
     $driverImpl = $this->ormConfig->newDefaultAnnotationDriver([], false);
     $this->ormConfig->setMetadataDriverImpl($driverImpl);
     $this->ormConfig->setQueryCacheImpl($cache);
     $this->ormConfig->setQueryCacheImpl($cache);
     if (null != ($entityNSArray = $this->config->get('entityNamespaces'))) {
         $this->ormConfig->setEntityNamespaces($entityNSArray);
     }
     // Proxy configuration
     $this->ormConfig->setProxyDir($this->config->get('proxyDir'));
     $this->ormConfig->setProxyNamespace($this->config->get('proxyNamespace'));
     $this->entityManager = $this->createEntityManager($conn, $this->ormConfig, $this->eventManager);
     $this->isInitialized = true;
     return $this;
 }
예제 #10
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     if (!GeometryEngineRegistry::has()) {
         $this->markTestSkipped('This test requires a connection to a database.');
     }
     $engine = GeometryEngineRegistry::get();
     if (!$engine instanceof PDOEngine) {
         $this->markTestSkipped('This test currently only works with a PDO connection.');
     }
     $this->platform = $this->_conn->getDatabasePlatform();
     $this->platform->registerDoctrineTypeMapping('geometry', 'binary');
     $this->platform->registerDoctrineTypeMapping('linestring', 'binary');
     $this->platform->registerDoctrineTypeMapping('multilinestring', 'binary');
     $this->platform->registerDoctrineTypeMapping('multipoint', 'binary');
     $this->platform->registerDoctrineTypeMapping('multipolygon', 'binary');
     $this->platform->registerDoctrineTypeMapping('point', 'binary');
     $this->platform->registerDoctrineTypeMapping('polygon', 'binary');
     switch ($this->platform->getName()) {
         case 'postgresql':
             $this->_conn->executeQuery('CREATE EXTENSION IF NOT EXISTS postgis;');
             break;
     }
     $this->fixtureLoader = new Loader();
     $config = Setup::createAnnotationMetadataConfiguration([__DIR__ . '/Fixtures'], false);
     $config->addCustomNumericFunction('EarthDistance', EarthDistanceFunction::class);
     $this->em = EntityManager::create($this->_conn, $config, $this->platform->getEventManager());
     $this->schemaTool = new SchemaTool($this->em);
     $this->schemaTool->updateSchema([$this->em->getClassMetadata(Fixtures\GeometryEntity::class), $this->em->getClassMetadata(Fixtures\LineStringEntity::class), $this->em->getClassMetadata(Fixtures\MultiLineStringEntity::class), $this->em->getClassMetadata(Fixtures\MultiPointEntity::class), $this->em->getClassMetadata(Fixtures\MultiPolygonEntity::class), $this->em->getClassMetadata(Fixtures\PointEntity::class), $this->em->getClassMetadata(Fixtures\PolygonEntity::class)]);
     $purger = new ORMPurger();
     $this->ormExecutor = new ORMExecutor($this->em, $purger);
 }
 private function registerEntityManager()
 {
     $this->app->singleton('DoctrineOrm', function ($app) {
         $config = $app['config']['doctrine::doctrine'];
         $metadata = Setup::createAnnotationMetadataConfiguration($config['metadata'], $app['config']['app.debug'], $config['proxy']['directory'], $app[CacheManager::class]->getCache($config['cache_provider']), $config['simple_annotations']);
         $metadata->addFilter('trashed', TrashedFilter::class);
         $metadata->setAutoGenerateProxyClasses($config['proxy']['auto_generate']);
         $metadata->setDefaultRepositoryClassName($config['repository']);
         $metadata->setSQLLogger($config['logger']);
         $metadata->setNamingStrategy($app->make(LaravelNamingStrategy::class));
         if (isset($config['proxy']['namespace'])) {
             $metadata->setProxyNamespace($config['proxy']['namespace']);
         }
         $eventManager = new EventManager();
         $connection_config = $this->mapLaravelToDoctrineConfig($app['config']);
         //load prefix listener
         if (isset($connection_config['prefix'])) {
             $tablePrefix = new TablePrefix($connection_config['prefix']);
             $eventManager->addEventListener(Events::loadClassMetadata, $tablePrefix);
         }
         $eventManager->addEventListener(Events::onFlush, new SoftDeletableListener());
         $entityManager = EntityManager::create($connection_config, $metadata, $eventManager);
         $entityManager->getFilters()->enable('trashed');
         return $entityManager;
     });
     //$this->app->alias('DoctrineOrm', EntityManagerInterface::class);
 }
예제 #12
0
 private static function initDoctrine()
 {
     App::$inst->container->singleton('DoctrineConfig', function () {
         $paths = array(APPLICATION_PATH . "/models/Entity");
         $isDevMode = false;
         $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($paths, $isDevMode);
         if (isset(App::$inst->config['resources']['doctrine']['proxiesPath'])) {
             $config->setProxyDir(App::$inst->config['resources']['doctrine']['proxiesPath']);
         } elseif (IS_SAVVIS) {
             $config->setProxyDir(sprintf('/tmp/%s/proxies', App::$inst->config['resources']['doctrine']['dbal']['connection']['parameters']['dbname']));
         } else {
             $config->setProxyDir(APPLICATION_PATH . '/tmp/proxies');
         }
         $config->setProxyNamespace('Application\\tmp\\proxies');
         $config->setAutoGenerateProxyClasses(true);
         return $config;
     });
     App::$inst->container->singleton('em', function () {
         $config = App::$inst->DoctrineConfig;
         $entityManager = \Doctrine\ORM\EntityManager::create(App::$inst->config['resources']['doctrine']['dbal']['connection']['parameters'], $config);
         return $entityManager;
     });
     App::$inst->cache = Bootstrap::initDoctrineCache(App::$inst->DoctrineConfig);
     //init doctrine cache
 }
 /**
  * @throws \Doctrine\ORM\ORMException
  */
 public function boot()
 {
     $this->serializer = SerializerBuilder::create()->setDebug($this->devMode)->build();
     $this->entityFolder->create();
     AnnotationRegistry::registerAutoloadNamespace('JMS\\Serializer\\Annotation', __DIR__ . '/../../../../vendor/jms/serializer/src');
     $proxyDoctrineFolder = new Folder(sys_get_temp_dir() . '/doctrine');
     $config = Setup::createAnnotationMetadataConfiguration([$this->entityFolder->absolute()], $this->isDevMode(), $proxyDoctrineFolder->absolute());
     if ($this->cache !== null) {
         $config->setQueryCacheImpl($this->getCache());
         $config->setResultCacheImpl($this->getCache());
     }
     $this->entityManager = $this->createEntityManager($config);
     $debugStack = new DebugStack();
     $this->entityManager->getConnection()->getConfiguration()->setSQLLogger($debugStack);
     if ($this->getFileCreation()->getContent() == 1) {
         return;
     }
     if ($proxyDoctrineFolder->isFolder()) {
         $proxyDoctrineFolder->removeFiles();
     }
     $tool = new SchemaTool($this->entityManager);
     $metadatas = $this->entityManager->getMetadataFactory()->getAllMetadata();
     $proxyDoctrineFolder->create();
     $this->entityManager->getProxyFactory()->generateProxyClasses($metadatas, $proxyDoctrineFolder->absolute());
     if ($this->cloudFoundryBoot->isInCloudFoundry()) {
         $tool->updateSchema($metadatas);
     } else {
         $tool->createSchema($metadatas);
     }
     $this->getFileCreation()->setContent(1);
 }
예제 #14
0
 /**
  * Executa as configurações iniciais e prepara o a entidade responsáveç
  * da biblioteca escolhida para ORM.
  */
 public function init()
 {
     $config = Config::getInstance();
     $paths = [SYS_ROOT . 'App' . DS . 'Models' . DS];
     $dev_mode = $config->get('database.debug');
     $conn_params = $this->loadConfiguration();
     $doctrine_config = Setup::createAnnotationMetadataConfiguration($paths, $dev_mode);
     if ($config->get('cache.cache')) {
         try {
             $cache = Cache::getInstance();
             if ($cache instanceof Cache) {
                 $doctrine_config->setResultCacheImpl($cache->getDriver());
             }
         } catch (\Exception $e) {
             $error = new Error();
             $error->log($e);
         }
     }
     $proxy_dir = SYS_ROOT . 'App' . DS . 'Models' . DS . 'Proxies';
     if (!is_dir($proxy_dir)) {
         if (mkdir($proxy_dir)) {
             $doctrine_config->setProxyDir($proxy_dir);
         }
     }
     $prefix = $config->get('database.connection.table_prefix');
     if ($prefix != '') {
         $evm = new EventManager();
         $table_prefix = new DoctrineTablePrefix($prefix);
         $evm->addEventListener(Events::loadClassMetadata, $table_prefix);
         $this->entityManager = EntityManager::create($conn_params, $doctrine_config, $evm);
     } else {
         $this->entityManager = EntityManager::create($conn_params, $doctrine_config);
     }
 }
예제 #15
0
 /**
  * @return EntityManager
  */
 public function getEntityManager()
 {
     if (!$this->entityManager instanceof EntityManager) {
         $this->entityManager = EntityManager::create($this->getConfiguration()->get('database'), Setup::createAnnotationMetadataConfiguration([$this->rootPath . '/src/Classes/Entities/', __DIR__ . '/Domain/Entities/'], true));
     }
     return $this->entityManager;
 }
 protected function setUp()
 {
     $this->container = new Container();
     $this->container->set('doctrine.orm.entity_manager', EntityManager::create(array('driver' => 'pdo_sqlite', 'memory' => true), Setup::createAnnotationMetadataConfiguration(array())));
     $this->bundle = new DateIntervalBundle();
     $this->bundle->setContainer($this->container);
 }
예제 #17
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $dbName = $input->getArgument('dbname');
     $path = $input->getOption('path');
     $extensionKey = $input->getOption('extension-key');
     $connectionParams = array('dbname' => $dbName, 'user' => $input->getOption('user'), 'password' => $input->getOption('password'), 'host' => $input->getOption('host'), 'driver' => $input->getOption('driver'), 'port' => $input->getOption('port'));
     $config = Setup::createAnnotationMetadataConfiguration(array('.'), false);
     $em = EntityManager::create($connectionParams, $config);
     $em->getConfiguration()->setMetadataDriverImpl(new \Doctrine\ORM\Mapping\Driver\DatabaseDriver($em->getConnection()->getSchemaManager()));
     $cmf = new DisconnectedClassMetadataFactory();
     $cmf->setEntityManager($em);
     if (is_null($extensionKey)) {
         $extensionKey = $dbName;
         if (self::DEFAULT_PATH != $path) {
             $extensionKey = array_pop(explode(DIRECTORY_SEPARATOR, $path));
         }
     }
     $exporter = new ExtbaseExporter($cmf);
     $exporter->setExtensionKey($extensionKey);
     $exporter->setPath($input->getOption('path'));
     self::mapDefaultInputOptions($exporter, $input);
     $output->writeln(sprintf('Exporting database schema "<info>%s</info>".', $dbName));
     $result = $exporter->exportJson();
     foreach ($exporter->getLogs() as $log) {
         $output->writeln($log);
     }
     return $result ? 0 : 1;
 }
예제 #18
0
 /**
  * Create config for metadata and annotation config in dotrine
  * @return AnnnotationMetadataConfiguration
  */
 private function getConfig()
 {
     if (empty(self::$dir)) {
         throw new \Exception("Informe o diretorio que se encontra o config");
     }
     $config = (require self::$dir);
     $doctrineSetup = (object) $config['doctrine'];
     $setup = Setup::createAnnotationMetadataConfiguration($doctrineSetup->entity, self::$isDevMode);
     $setup->setProxyDir($doctrineSetup->metadata);
     /**Create cache region and factory **/
     $cache = new \Doctrine\Common\Cache\ApcCache();
     $cacheRegionConfiguration = new \Doctrine\ORM\Cache\RegionsConfiguration();
     $factory = new \Doctrine\ORM\Cache\DefaultCacheFactory($cacheRegionConfiguration, $cache);
     $setup->setSecondLevelCacheEnabled();
     $setup->getSecondLevelCacheConfiguration()->setCacheFactory($factory);
     $setup->addCustomStringFunction("SOUNDEX", 'RespectDoctrine\\Doctrine\\Functions\\SoundexFunction');
     $setup->addCustomStringFunction("RAND", 'RespectDoctrine\\Doctrine\\Functions\\Rand');
     $setup->addCustomStringFunction("MATCH", 'RespectDoctrine\\Doctrine\\Functions\\MatchAgainst');
     $setup->addCustomNumericFunction("LEVENSHTEIN", 'RespectDoctrine\\Doctrine\\Functions\\LevenshteinFunction');
     $filters = $doctrineSetup->filters;
     $this->filters = [];
     foreach ($filters as $name => $filter) {
         $setup->addFilter($name, $filter);
         $this->filters[] = $name;
     }
     return $setup;
 }
예제 #19
0
 public function register(Application $app)
 {
     $dbConnection = array('driver' => 'pdo_mysql', 'host' => 'localhost', 'user' => 'root', 'password' => 'password', 'dbname' => 'icfs');
     $config = \Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/Model"), true);
     $app['db.em'] = \Doctrine\ORM\EntityManager::create($dbConnection, $config);
     $app->register(new \Silex\Provider\DoctrineServiceProvider(), array('db.options' => $dbConnection));
 }
예제 #20
0
파일: bootstrap.php 프로젝트: V3N0m21/Uppu4
function createDoctrineConfig($cache, $cachedAnnotationReader)
{
    AnnotationRegistry::registerFile(dirname(__DIR__) . "/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php");
    //$cache = new Doctrine\Common\Cache\ArrayCache;
    //    if (extension_loaded('apc')) {
    //        $cache = new \Doctrine\Common\Cache\ApcCache();
    //    } else {
    //        $cache = new \Doctrine\Common\Cache\PhpFileCache();
    //    }
    $isDevMode = true;
    //    $annotationReader = new AnnotationReader;
    //    $cachedAnnotationReader = new Doctrine\Common\Annotations\CachedReader(
    //        $annotationReader, // use reader
    //        $cache // and a cache driver
    //    );
    $annotationDriver = new Doctrine\ORM\Mapping\Driver\AnnotationDriver($cachedAnnotationReader, array(__DIR__ . '/Resource'));
    $driverChain = new Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
    Gedmo\DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $cachedAnnotationReader);
    $driverChain->addDriver($annotationDriver, 'Uppu4\\Entity');
    $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__ . "/Resource"), $isDevMode);
    //!!!!!!
    $config = new Doctrine\ORM\Configuration();
    $config->setProxyDir(sys_get_temp_dir());
    $config->setProxyNamespace('Proxy');
    $config->setAutoGenerateProxyClasses(true);
    // this can be based on production config.
    // register metadata driver
    $config->setMetadataDriverImpl($driverChain);
    // use our already initialized cache driver
    $config->setMetadataCacheImpl($cache);
    $config->setQueryCacheImpl($cache);
    $deleted = $cache->deleteAll();
    return $config;
}
예제 #21
0
 protected function setUp()
 {
     parent::setUp();
     $this->connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::SQLITE_PATH], new Configuration());
     $config = Setup::createAnnotationMetadataConfiguration([__DIR__ . '/../..'], true);
     $this->entityManager = EntityManager::create($this->connection, $config);
 }
예제 #22
0
 public function __construct()
 {
     $yamlParser = new Parser();
     $dbParams = $yamlParser->parse(file_get_contents(__DIR__ . '/parameters.yml'));
     $config = Setup::createAnnotationMetadataConfiguration(array(__DIR__ . '/../Entity'), true);
     $this->em = EntityManager::create($dbParams['database'], $config);
 }
예제 #23
0
 /**
  * @param ServiceLocatorInterface $serviceLocator
  * @return \Doctrine\ORM\EntityManager
  * @throws \Doctrine\ORM\ORMException
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     $config = $serviceLocator->get('config');
     //set the Doctrine configuration array
     $doctrineDbSettings = (array) $config['db'];
     $doctrineDbSettings['driver'] = strtolower($config['db']['driver']);
     $doctrineDbSettings['dbname'] = isset($config['db']['database']) ? $config['db']['database'] : null;
     $doctrineDbSettings['host'] = isset($config['db']['hostname']) ? $config['db']['hostname'] : null;
     $doctrineDbSettings['user'] = isset($config['db']['username']) ? $config['db']['username'] : null;
     $proxyPath = isset($config['doctrine']['proxy_dir']) ? $config['doctrine']['proxy_dir'] : null;
     $isDevMode = isset($config['doctrine']['is_dev_mode']) ? $config['doctrine']['is_dev_mode'] : false;
     $doctrineConfig = Setup::createAnnotationMetadataConfiguration($config['doctrine']['entity_path'], $isDevMode, $proxyPath);
     $doctrineConfig->setAutoGenerateProxyClasses(true);
     $doctrineEntityManager = DocEManager::create($doctrineDbSettings, $doctrineConfig);
     if (isset($config['doctrine']['initializers'])) {
         $eventManager = $doctrineEntityManager->getEventManager();
         foreach ($config['doctrine']['initializers'] as $initializer) {
             $eventClass = new DoctrineEvent(new $initializer(), $serviceLocator);
             $eventManager->addEventListener(\Doctrine\ORM\Events::postLoad, $eventClass);
         }
     }
     if ($doctrineDbSettings['driver'] == 'pdo_sqlite') {
         //it is very important to make sure foreign keys are on with SQLite
         $query = $doctrineEntityManager->createNativeQuery("pragma foreign_keys=1", new \Doctrine\ORM\Query\ResultSetMapping());
         $query->execute();
     }
     return $doctrineEntityManager;
 }
예제 #24
0
 public function __construct()
 {
     $this->setRoot("/var/www/html/uan/");
     $this->setEntidade(array($this->getRoot() . "models/"));
     $this->setIsDevMode(true);
     $mode = "DESENVOLVIMENTO";
     $config = Setup::createAnnotationMetadataConfiguration($this->getEntidade(), $this->getIsDevMode(), NULL, NULL, FALSE);
     if ($mode == "DESENVOLVIMENTO") {
         $cache = new \Doctrine\Common\Cache\ArrayCache();
     } else {
         $cache = new \Doctrine\Common\Cache\ApcCache();
     }
     $config = new Configuration();
     $config->setMetadataCacheImpl($cache);
     $driverImpl = $config->newDefaultAnnotationDriver($this->getRoot() . 'models/');
     $config->setMetadataDriverImpl($driverImpl);
     $config->setQueryCacheImpl($cache);
     $config->setProxyDir($this->getRoot() . 'proxies/');
     $config->setProxyNamespace('proxies');
     if ($mode == "DESENVOLVIMENTO") {
         $config->setAutoGenerateProxyClasses(true);
     } else {
         $config->setAutoGenerateProxyClasses(false);
     }
     $config = Setup::createAnnotationMetadataConfiguration($this->getEntidade(), $this->getIsDevMode(), NULL, NULL, FALSE);
     $dbParams = array('driver' => 'pdo_mysql', 'user' => 'root', 'password' => '', 'dbname' => 'ceafie', 'charset' => 'utf8', 'driverOptions' => array(1002 => 'SET NAMES utf8'));
     $this->em = EntityManager::create($dbParams, $config);
     $loader = new ClassLoader('Entity', __DIR__ . '/models');
     $loader->register();
 }
예제 #25
0
 public function __construct($configDir, $environment = 'dev')
 {
     if (!@file_exists("{$configDir}/config.yml")) {
         throw new \Exception("File: {$configDir}/config.yml does not exist.");
     }
     if (!@file_exists("{$configDir}/config_{$environment}.yml")) {
         throw new \Exception("File: {$configDir}/config_{$environment}.yml does not exist.");
     }
     try {
         $config = Yaml\Yaml::parse("{$configDir}/config.yml");
         $configEnv = Yaml\Yaml::parse("{$configDir}/config_{$environment}.yml");
     } catch (Yaml\Exception\ParseException $e) {
         throw new \Exception($e->getMessage());
     }
     $this->config = Arr::merge($config, $configEnv);
     $entityPaths = Arr::get($this->config, 'doctrine.entity.paths', array());
     $proxiesPath = Arr::get($this->config, 'doctrine.proxy.path', '');
     $proxiesNamespace = Arr::get($this->config, 'doctrine.proxy.namespace', '');
     $database = Arr::get($this->config, 'doctrine.database', array());
     $isDevMode = Arr::get($this->config, 'doctrine.isDevMode', TRUE);
     $this->cache = new \Doctrine\Common\Cache\ArrayCache();
     $this->reader = new AnnotationReader();
     $this->driver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($this->reader, $entityPaths);
     $this->config = Setup::createAnnotationMetadataConfiguration($entityPaths, $isDevMode);
     $this->config->setMetadataCacheImpl($this->cache);
     $this->config->setQueryCacheImpl($this->cache);
     $this->config->setMetadataDriverImpl($this->driver);
     $this->config->setProxyDir($proxiesPath);
     $this->config->setProxyNamespace($proxiesNamespace);
     $this->config->setAutoGenerateProxyClasses($isDevMode);
     $this->entityManager = EntityManager::create($database, $this->config);
     $this->platform = $this->entityManager->getConnection()->getDatabasePlatform();
     $this->platform->registerDoctrineTypeMapping('enum', 'string');
 }
예제 #26
0
 /**
  * This method is used to add an entity manager to the doctrine service.
  * @param $id string The id you would like to store with the entity manager.
  * @param ulfberht\module\doctrine\config $config The doctrine configuration for
  *        the entity manager.
  * @return void
  */
 public function addEntityManager($id, config $config)
 {
     $development = $config->develop ? true : false;
     $cache = $config->enableCache ? new ArrayCache() : null;
     //setup type of metadata reading
     switch ($config->type) {
         case 'annotation':
             $docConfig = Setup::createAnnotationMetadataConfiguration($config->paths, $development, null, $cache);
             break;
         case 'xml':
             $docConfig = Setup::createXMLMetadataConfiguration($config->paths, $development, null, $cache);
             break;
         case 'yaml':
             $docConfig = Setup::createYAMLMetadataConfiguration($config->paths, $development, null, $cache);
             break;
     }
     //setup caching
     if (!is_null($cache)) {
         $docConfig->setQueryCacheImpl($cache);
         $docConfig->setMetadataCacheImpl($cache);
     }
     //setup database connection
     $dbConnInfo = array('driver' => $config->database->driver, 'host' => $config->database->host, 'dbname' => $config->database->name, 'user' => $config->database->user, 'password' => $config->database->password);
     //store entity manager
     $this->_doctrineEntityMangers[$id] = EntityManager::create($dbConnInfo, $docConfig);
 }
 /**
  * Just for internal use, could be overridden in child classes
  * User $em property in case if you need EntityManager
  *
  * @return EntityManagerMock
  */
 protected function getEntityManagerInstanceMock()
 {
     $this->config = Setup::createAnnotationMetadataConfiguration(array('./Fixtures'), true);
     $this->config->setQuoteStrategy(new QuotingStrategy());
     $conn = array('driverClass' => 'Luxifer\\Tests\\Mocks\\DriverMock', 'wrapperClass' => 'Luxifer\\Tests\\Mocks\\ConnectionMock', 'user' => 'john', 'password' => 'wayne');
     $conn = DriverManager::getConnection($conn, $this->config);
     $this->config->setProxyDir(__DIR__ . '/Proxies');
     $this->config->setProxyNamespace('Luxifer\\Tests\\Proxies');
     $this->config->addCustomDatetimeFunction('date', 'Luxifer\\DQL\\Datetime\\Date');
     $this->config->addCustomDatetimeFunction('datediff', 'Luxifer\\DQL\\Datetime\\DateDiff');
     $this->config->addCustomDatetimeFunction('day', 'Luxifer\\DQL\\Datetime\\Day');
     $this->config->addCustomDatetimeFunction('dayofmonth', 'Luxifer\\DQL\\Datetime\\DayOfMonth');
     $this->config->addCustomDatetimeFunction('week', 'Luxifer\\DQL\\Datetime\\Week');
     $this->config->addCustomDatetimeFunction('dayofweek', 'Luxifer\\DQL\\Datetime\\DayOfWeek');
     $this->config->addCustomDatetimeFunction('dayofyear', 'Luxifer\\DQL\\Datetime\\DayOfYear');
     $this->config->addCustomDatetimeFunction('hour', 'Luxifer\\DQL\\Datetime\\Hour');
     $this->config->addCustomDatetimeFunction('minute', 'Luxifer\\DQL\\Datetime\\Minute');
     $this->config->addCustomDatetimeFunction('month', 'Luxifer\\DQL\\Datetime\\Month');
     $this->config->addCustomDatetimeFunction('quarter', 'Luxifer\\DQL\\Datetime\\Quarter');
     $this->config->addCustomDatetimeFunction('second', 'Luxifer\\DQL\\Datetime\\Second');
     $this->config->addCustomDatetimeFunction('time', 'Luxifer\\DQL\\Datetime\\Time');
     $this->config->addCustomDatetimeFunction('year', 'Luxifer\\DQL\\Datetime\\Year');
     $this->config->addCustomDatetimeFunction('convert_tz', 'Luxifer\\DQL\\Datetime\\ConvertTZ');
     $this->config->addCustomDatetimeFunction('date_format', 'Luxifer\\DQL\\Datetime\\DateFormat');
     $this->config->addCustomDatetimeFunction('concat_ws', 'Luxifer\\DQL\\String\\ConcatWs');
     return EntityManagerMock::create($conn, $this->config);
 }
 public function __construct($sm, $params = array())
 {
     $this->sm = $sm;
     $path = $sm->get('pegase.core.path');
     foreach ($params['entities_folders'] as $i => $f) {
         $params['entities_folders'][$i] = $path->get_path($f);
     }
     $this->db_params = $params['database'];
     $isDevMode = true;
     $config = Setup::createAnnotationMetadataConfiguration($params['entities_folders'], $isDevMode);
     $this->em = EntityManager::create($params['database'], $config);
     /*
       // on vérifie la validité des mappings
     
       $validator = new SchemaValidator($this->em);
       $errors = $validator->validateMapping();
     
       if(count($errors) > 0) {
         // Lots of errors!
         echo implode("\n\n", $errors);
       }
       else
         echo "Les mappings sont ok.\n";
     */
     $this->schema = new Schema($sm, $this);
     $this->database = new Database($sm, $this);
     $this->entity = new Entity($sm, $this);
 }
예제 #29
0
 private function initDB()
 {
     require_once APPPATH . 'config/database.php';
     // Database connection information
     $dbParams = array('driver' => 'pdo_mysql', 'user' => "helpie38_neo", 'password' => "x#rnoPA;P}74", 'host' => "localhost", 'dbname' => "helpie38_main");
     $path = array(APPPATH . 'BusinessLogic/Models/Entities');
     $config = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($path, true);
     $config->addEntityNamespace("Entities", 'BusinessLogic\\Models\\Entities');
     // $config->setResultCacheImpl(new \Doctrine\Common\Cache\ApcCache());
     // $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ApcCache());
     // $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ApcCache());
     //$config->setProxyDir("NeoMvc/Proxy");
     //$config->setProxyNamespace("Proxy");
     // $config->setResultCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
     // $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
     // $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
     require_once APPPATH . "libraries/UVd/DoctrineFunction/DateFormat.php";
     $config->addCustomStringFunction("DATE_FORMAT", "\\UVd\\DoctrineFunction\\DateFormat");
     $config->setAutoGenerateProxyClasses(true);
     $em = EntityManager::create($dbParams, $config);
     try {
         // $this->updateSchema($em);
     } catch (\Exception $e) {
         echo $e->getMessage();
     }
     return $em;
 }
 private function getMetadataConfig(Application $app, array $metadataConfig)
 {
     foreach (['type', 'paths'] as $requiredParam) {
         if (!in_array($requiredParam, array_keys($metadataConfig))) {
             throw new \Exception(sprintf('Missing param %s in matadata config.', $requiredParam));
         }
     }
     if (!is_array($metadataConfig['paths'])) {
         throw new \Exception('Paths must be an array.');
     }
     switch ($metadataConfig['type']) {
         case 'annotation':
             $config = Setup::createAnnotationMetadataConfiguration($metadataConfig['paths'], $app['debug']);
             // setting driver
             $driver = new AnnotationDriver(new AnnotationReader(), $metadataConfig['paths']);
             $config->setMetadataDriverImpl($driver);
             // setting cache
             $cache = new ArrayCache();
             // todo add redis cache
             $config->setMetadataCacheImpl($cache);
             $config->setQueryCacheImpl($cache);
             break;
         default:
             throw new \Exception('The only type allowed is annotation.');
     }
     return $config;
 }