Пример #1
0
 /**
  * Enable this listener for the given entity
  * This will apply the number generator when this entity will be flushed.
  *
  * @param SequenceSubjectInterface $subject
  */
 public function enableEntity(SequenceSubjectInterface $subject)
 {
     $this->entitiesEnabled[spl_object_hash($subject)] = $subject;
     if (!$this->listenerEnabled) {
         $this->eventManager->addEventListener(Events::preFlush, $this);
         $this->listenerEnabled = true;
     }
 }
Пример #2
0
 /**
  * @return DoctrineEventManager
  */
 public function configureEventManager()
 {
     $eventConfiguration = $this->configuration->get('events');
     foreach ($eventConfiguration['listeners'] as $listener => $events) {
         $this->eventManager->addEventListener((array) $events, new $listener());
     }
     foreach ($eventConfiguration['subscribers'] as $subscriber) {
         $this->eventManager->addEventSubscriber(new $subscriber());
     }
     return $this->eventManager;
 }
Пример #3
0
 public static function getEntityManager($smart = FALSE, $path_to_entity = null, $proxyPath = null, $proxyNamespace = null)
 {
     if (empty(self::$em)) {
         if ($path_to_entity === NULL) {
             //$path_to_entity = PATH_ROOT . '/' . Sokol::getApp()->name . '/Entity';
             $path_to_entity = PATH_ROOT . '/Entity';
         }
         $isDev = Sokol::getApp()->isDev;
         $connectionParams = Sokol::getConfig('db');
         //---Table Prefix---
         $tablePrefix = !empty($connectionParams['tablePrefix']) ? $connectionParams['tablePrefix'] : null;
         if ($tablePrefix) {
             $evm = new EventManager();
             $tablePrefix = new TablePrefix($tablePrefix);
             $evm->addEventListener(Events::loadClassMetadata, $tablePrefix);
         }
         //---/Table Prefix---
         if ($smart) {
             self::$em = self::getEmSmart($path_to_entity, $isDev, $connectionParams, $evm);
         } else {
             if ($proxyPath === NULL) {
                 $proxyPath = PATH_ROOT . '/' . Sokol::getApp()->name . '/Proxy';
             }
             if ($proxyNamespace === NULL) {
                 $proxyNamespace = Sokol::getApp()->getNamespace() . '\\Proxy';
             }
             self::$em = self::getEm($path_to_entity, $isDev, $connectionParams, $evm, $proxyPath, $proxyNamespace);
         }
         //подключаем тип данных "html"
         Type::addType('html', 'Sokol\\Doctrine\\Extension\\HtmlType');
         self::$em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('db_html', 'html');
     }
     return self::$em;
 }
Пример #4
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);
     }
 }
Пример #5
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);
         };
     }
 }
 /**
  * @return \Doctrine\ORM\EntityManager
  */
 protected function createEntityManager()
 {
     // event manager used to create schema before tests
     $eventManager = new EventManager();
     $eventManager->addEventListener(array("preTestSetUp"), new SchemaSetupListener());
     // doctrine xml configs and namespaces
     $configPathList = array();
     if (is_dir(__DIR__ . '/../Resources/config/doctrine')) {
         $dir = __DIR__ . '/../Resources/config/doctrine';
         $configPathList[] = $dir;
         $prefixList[$dir] = 'Kitpages\\DataGridBundle\\Entities';
     }
     if (is_dir(__DIR__ . '/_doctrine/config')) {
         $dir = __DIR__ . '/_doctrine/config';
         $configPathList[] = $dir;
         $prefixList[$dir] = 'Kitpages\\DataGridBundle\\Tests\\TestEntities';
     }
     // create drivers (that reads xml configs)
     $driver = new \Symfony\Bridge\Doctrine\Mapping\Driver\XmlDriver($configPathList);
     $driver->setNamespacePrefixes($prefixList);
     // create config object
     $config = new Configuration();
     $config->setMetadataCacheImpl(new ArrayCache());
     $config->setMetadataDriverImpl($driver);
     $config->setProxyDir(__DIR__ . '/TestProxies');
     $config->setProxyNamespace('Kitpages\\DataGridBundle\\Tests\\TestProxies');
     $config->setAutoGenerateProxyClasses(true);
     //$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
     // create entity manager
     $em = EntityManager::create(array('driver' => 'pdo_sqlite', 'path' => "/tmp/sqlite-test.db"), $config, $eventManager);
     return $em;
 }
Пример #7
0
 /**
  * {@inheritdoc}
  */
 public static function create($conn, Configuration $config, EventManager $eventManager = null)
 {
     if (!$config->getMetadataDriverImpl()) {
         throw ORMException::missingMappingDriverImpl();
     }
     switch (true) {
         case is_array($conn):
             if (!$eventManager) {
                 $eventManager = new EventManager();
             }
             if (isset($conn['prefix']) && $conn['prefix']) {
                 $eventManager->addEventListener(Events::loadClassMetadata, new TablePrefix($conn['prefix']));
             }
             $conn = \Doctrine\DBAL\DriverManager::getConnection($conn, $config, $eventManager);
             break;
         case $conn instanceof Connection:
             if ($eventManager !== null && $conn->getEventManager() !== $eventManager) {
                 throw ORMException::mismatchedEventManager();
             }
             break;
         default:
             throw new \InvalidArgumentException("Invalid argument: " . $conn);
     }
     return new self($conn, $config, $conn->getEventManager());
 }
Пример #8
0
 public function testEventArgsNamespaceTest()
 {
     $listener = new ListenerStub();
     $manager = new EventManager();
     $manager->addEventListener(\Doctrine\MongoDB\Events::preConnect, $listener);
     $connection = new Connection(null, [], null, $manager);
     $connection->initialize();
 }
 /**
  * 
  * @return \Doctrine\Common\EventManager
  */
 protected function getEvent()
 {
     $options = config('database')['connections']['mysql'];
     $evm = new EventManager();
     $tablePrefix = new \PanGuKTD\LaravelDoctrineORM\Listeners\TablePrefixListener($options['prefix']);
     $evm->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix);
     return $evm;
 }
Пример #10
0
 /**
  * Add doctrine event manager lifecycle listener
  * @param $events Array of Event constants to listen to
  * @param object $listener The listener object.
  * @throws \Exception
  * @return $this
  */
 public function addLifecycleEventListener($events = array(), $listener)
 {
     if (empty($this->entityManager)) {
         throw new \Exception('Please establish the entity manager connection using getEntityManager prior to adding event listeners');
     }
     $this->eventManager->addEventListener($events, $listener);
     return $this;
 }
 protected function setUp()
 {
     $ev = new EventManager();
     $ev->addEventListener(Events::prePersist, new \stdClass());
     $lr = new ListenerResolver();
     $this->md = new ClassMetadata('Test');
     $this->md->documentListeners[Events::prePersist] = [];
     $this->md->lifecycleCallbacks[Events::prePersist] = [];
     $this->li = new ListenersInvoker($ev, $lr);
 }
Пример #12
0
 /**
  * @return EntityManager
  */
 private static function createEntityManager()
 {
     $config = \Doctrine\ORM\Tools\Setup::createConfiguration(true);
     $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver([__DIR__ . '/../../../../src/Driver/Doctrine/ORM/Entity', __DIR__ . '/Entity'], false));
     $rtel = new ResolveTargetEntityListener();
     $rtel->addResolveTargetEntity('FOS\\Message\\Model\\PersonInterface', 'FOS\\Message\\Tests\\Driver\\Doctrine\\ORM\\Entity\\TestPerson', []);
     $evm = new EventManager();
     $evm->addEventListener(Events::loadClassMetadata, $rtel);
     $dbParams = ['driver' => 'pdo_sqlite', 'path' => self::$dbFile];
     return \Doctrine\ORM\EntityManager::create($dbParams, $config, $evm);
 }
Пример #13
0
 /**
  * Create an entity manager
  *
  * @param array $params Parameters
  * @return object Entity manager
  * @filter
  */
 protected function createEntityManager()
 {
     $configuration = Setup::createAnnotationMetadataConfiguration([$this->_config['models']], Environment::is('development'), $this->_config['proxies'], isset($this->_config['cache']) ? call_user_func($this->_config['cache']) : null);
     $configuration->setProxyNamespace($this->_config['proxyNamespace']);
     $eventManager = new EventManager();
     $eventManager->addEventListener([Events::postLoad, Events::prePersist, Events::preUpdate], $this);
     $connection = $this->connectionSettings;
     $params = compact('connection', 'configuration', 'eventManager');
     return $this->_filter(__METHOD__, $params, function ($self, $params) {
         return EntityManager::create($params['connection'], $params['configuration'], $params['eventManager']);
     });
 }
 public static function setUpBeforeClass()
 {
     self::$connection = new MysqlPersistentConnection();
     $params = self::$connection->getConnectionParams();
     $configuration = Setup::createConfiguration(true);
     $event_manager = new EventManager();
     $annotation_reader = new AnnotationReader();
     $configuration->setMetadataDriverImpl(new AnnotationDriver($annotation_reader, [__DIR__ . '/Entity']));
     $annotation_metadata_provider = new EntityAnnotationMetadataProvider($annotation_reader);
     $mutation_metadata_provider = new EntityMutationMetadataProvider($annotation_reader);
     $entity_changed_listener = new EntityChangedListener($annotation_metadata_provider, $mutation_metadata_provider);
     $mutation_resolver = new MutationResolver($annotation_metadata_provider);
     $mutation_listener = new MutationListener($mutation_resolver);
     $event_manager->addEventListener('prePersist', $entity_changed_listener);
     $event_manager->addEventListener('preFlush', $entity_changed_listener);
     $event_manager->addEventListener('entityChanged', $mutation_listener);
     self::$entity_manager = EntityManager::create($params, $configuration, $event_manager);
     $metadata = self::$entity_manager->getMetadataFactory()->getAllMetadata();
     $schema_tool = new SchemaTool(self::$entity_manager);
     $schema_tool->createSchema($metadata);
 }
Пример #15
0
 public function testConnectDispatchEvent()
 {
     $listenerMock = $this->getMock('ConnectDispatchEventListener', array('postConnect'));
     $listenerMock->expects($this->once())->method('postConnect');
     $eventManager = new EventManager();
     $eventManager->addEventListener(array(Events::postConnect), $listenerMock);
     $driverMock = $this->getMock('Doctrine\\DBAL\\Driver');
     $driverMock->expects($this->at(0))->method('connect');
     $platform = new Mocks\MockPlatform();
     $conn = new Connection(array('platform' => $platform), $driverMock, new Configuration(), $eventManager);
     $conn->connect();
 }
 protected function createEntityManager()
 {
     $eventManager = new EventManager();
     $eventManager->addEventListener(array('preTestSetUp'), $this);
     $config = new \Doctrine\ORM\Configuration();
     $config->setMetadataDriverImpl($config->newDefaultAnnotationDriver());
     $config->setMetadataCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
     $config->setQueryCacheImpl(new \Doctrine\Common\Cache\ArrayCache());
     $config->setProxyDir(__DIR__ . '/Proxies');
     $config->setProxyNamespace('DoctrineExtensions\\Types\\Proxies');
     $conn = array('driver' => 'pdo_sqlite', 'memory' => true);
     return EntityManager::create($conn, $config, $eventManager);
 }
Пример #17
0
 public function __construct(Configuration $configuration = null, $isDevMode = true, $tablePrefixString = 'AM_')
 {
     if ($configuration === null) {
         $configuration = new Configuration();
     }
     $doctrineConfig = Doctrine\ORM\Tools\Setup::createAnnotationMetadataConfiguration($configuration->getEntityPaths(), $isDevMode);
     $conn = array('pdo' => $configuration->getPDOInstance());
     $tablePrefix = new TablePrefix($tablePrefixString);
     $eventManager = new Doctrine\Common\EventManager();
     $eventManager->addEventListener(Doctrine\ORM\Events::loadClassMetadata, $tablePrefix);
     $this->entityManager = Doctrine\ORM\EntityManager::create($conn, $doctrineConfig, $eventManager);
     $this->classes = $this->entityManager->getMetadataFactory()->getAllMetadata();
     $this->schemaTool = new Doctrine\ORM\Tools\SchemaTool($this->entityManager);
 }
Пример #18
0
 /**
  * @return \Doctrine\ORM\EntityManager
  */
 protected function createEntityManager()
 {
     $eventManager = new EventManager();
     $eventManager->addEventListener(array("preTestSetUp"), new SchemaSetupListener());
     $driver = new SimplifiedXmlDriver(array(__DIR__ . '/../Resources/config/doctrine' => 'Tbbc\\MoneyBundle\\Entity'));
     // create config object
     $config = new Configuration();
     $config->setMetadataCacheImpl(new ArrayCache());
     $config->setMetadataDriverImpl($driver);
     $config->setProxyDir(__DIR__ . '/TestProxies');
     $config->setProxyNamespace('Tbbc\\MoneyBundle\\Tests\\TestProxies');
     $config->setAutoGenerateProxyClasses(true);
     //$config->setSQLLogger(new \Doctrine\DBAL\Logging\EchoSQLLogger());
     // create entity manager
     return EntityManager::create(array('driver' => 'pdo_sqlite', 'path' => "/tmp/sqlite-tbbc-money-test.db"), $config, $eventManager);
 }
 private function registerEntityManager()
 {
     $this->app->singleton('Doctrine\\ORM\\EntityManager', function ($app) {
         $config = $app['config']['doctrine::doctrine'];
         $metadata = Setup::createAnnotationMetadataConfiguration($config['metadata'], $app['config']['app.debug'], $config['proxy']['directory'], $app['Mitch\\LaravelDoctrine\\CacheManager']->getCache($config['cache_provider']), $config['simple_annotations']);
         $metadata->addFilter('trashed', 'Mitch\\LaravelDoctrine\\Filters\\TrashedFilter');
         $metadata->setAutoGenerateProxyClasses($config['proxy']['auto_generate']);
         $metadata->setDefaultRepositoryClassName($config['repository']);
         $metadata->setSQLLogger($config['logger']);
         if (isset($config['proxy']['namespace'])) {
             $metadata->setProxyNamespace($config['proxy']['namespace']);
         }
         $eventManager = new EventManager();
         $eventManager->addEventListener(Events::onFlush, new SoftDeletableListener());
         $entityManager = EntityManager::create($this->getDatabaseConfig($app['config']), $metadata, $eventManager);
         $entityManager->getFilters()->enable('trashed');
         return $entityManager;
     });
     $this->app->singleton('Doctrine\\ORM\\EntityManagerInterface', 'Doctrine\\ORM\\EntityManager');
 }
Пример #20
0
 public function createEntityManager($smart = false, array $conn, array $paths, $isDevMode = false, $proxyDir = null, $proxyNamespace = null)
 {
     //--- Cache ---
     $cache = $isDevMode ? new ArrayCache() : ApcCache();
     //--- /END Cache ---
     //
     //--- Config
     //        $config = new Configuration();
     //        if($cache){
     //            $config->setMetadataCacheImpl($cache);
     //        }
     //        $driverImpl = $config->newDefaultAnnotationDriver($paths);
     //        $config->setMetadataDriverImpl($driverImpl);
     //        if($cache){
     //            $config->setQueryCacheImpl($cache);
     //        }
     //        $config->setProxyDir($proxyDir);
     //        $config->setProxyNamespace($proxyNamespace);
     //--- /END Config
     //--- EventManager ---
     $eventManager = null;
     if (!empty($conn['tablePrefix'])) {
         $eventManager = new EventManager();
         $tablePrefix = new TablePrefix($conn['tablePrefix']);
         $eventManager->addEventListener(Events::loadClassMetadata, $tablePrefix);
     }
     //--- /END EventManager ---
     if ($smart) {
         $em = $this->createEmSmart($conn, $paths, $isDevMode, $proxyDir, $cache, $eventManager);
     } else {
         $em = $this->createEm($conn, $paths, $isDevMode, $proxyDir, $cache, $eventManager, $proxyNamespace);
     }
     //подключаем тип данных "html"
     Type::addType('html', 'Phpnik\\Core\\DoctrineExtensions\\HtmlType');
     $em->getConnection()->getDatabasePlatform()->registerDoctrineTypeMapping('db_html', 'html');
     return $em;
 }
 /**
  * Add configured event subscribers and listeners to the event manager
  *
  * @return EventManager
  * @throws \TYPO3\Flow\Persistence\Exception\IllegalObjectTypeException
  */
 protected function buildEventManager()
 {
     $eventManager = new EventManager();
     if (isset($this->settings['doctrine']['eventSubscribers']) && is_array($this->settings['doctrine']['eventSubscribers'])) {
         foreach ($this->settings['doctrine']['eventSubscribers'] as $subscriberClassName) {
             $subscriber = $this->objectManager->get($subscriberClassName);
             if (!$subscriber instanceof EventSubscriber) {
                 throw new IllegalObjectTypeException('Doctrine eventSubscribers must extend class \\Doctrine\\Common\\EventSubscriber, ' . $subscriberClassName . ' fails to do so.', 1366018193);
             }
             $eventManager->addEventSubscriber($subscriber);
         }
     }
     if (isset($this->settings['doctrine']['eventListeners']) && is_array($this->settings['doctrine']['eventListeners'])) {
         foreach ($this->settings['doctrine']['eventListeners'] as $listenerOptions) {
             $listener = $this->objectManager->get($listenerOptions['listener']);
             $eventManager->addEventListener($listenerOptions['events'], $listener);
         }
     }
     return $eventManager;
 }
Пример #22
0
 /**
  * @return $this
  */
 public function connect()
 {
     // Prevent to connect twice
     if ($this->entityManager) {
         return $this;
     }
     $applicationDir = $this->core->getApplicationDir();
     $this->createModuleDirCache();
     $cache = $this->cache->getCacheProvider();
     $config = new \Doctrine\ORM\Configuration();
     $config->setMetadataCacheImpl($cache);
     $config->addCustomStringFunction('MD5', '\\DoctrineExtensions\\Query\\Mysql\\Md5');
     $config->addCustomStringFunction('ACOS', '\\DoctrineExtensions\\Query\\Mysql\\Acos');
     $config->addCustomStringFunction('ASIN', '\\DoctrineExtensions\\Query\\Mysql\\Asin');
     $config->addCustomStringFunction('ATAN', '\\DoctrineExtensions\\Query\\Mysql\\Atan');
     $config->addCustomStringFunction('ATAN2', '\\DoctrineExtensions\\Query\\Mysql\\Atan2');
     $config->addCustomStringFunction('BINARY', '\\DoctrineExtensions\\Query\\Mysql\\Binary');
     $config->addCustomStringFunction('CHARLENGTH', '\\DoctrineExtensions\\Query\\Mysql\\CharLength');
     $config->addCustomStringFunction('CONCATWS', '\\DoctrineExtensions\\Query\\Mysql\\ConcatWs');
     $config->addCustomStringFunction('COS', '\\DoctrineExtensions\\Query\\Mysql\\Cos');
     $config->addCustomStringFunction('COT', '\\DoctrineExtensions\\Query\\Mysql\\COT');
     $config->addCustomStringFunction('COUNTIF', '\\DoctrineExtensions\\Query\\Mysql\\CountIf');
     $config->addCustomStringFunction('CRC32', '\\DoctrineExtensions\\Query\\Mysql\\Crc32');
     $config->addCustomStringFunction('DATE', '\\DoctrineExtensions\\Query\\Mysql\\Date');
     $config->addCustomStringFunction('DATEADD', '\\DoctrineExtensions\\Query\\Mysql\\DateAdd');
     $config->addCustomStringFunction('DATEDIFF', '\\DoctrineExtensions\\Query\\Mysql\\DateFormat');
     $config->addCustomStringFunction('DAY', '\\DoctrineExtensions\\Query\\Mysql\\Day');
     $config->addCustomStringFunction('DEGREES', '\\DoctrineExtensions\\Query\\Mysql\\Degrees');
     $config->addCustomStringFunction('FIELD', '\\DoctrineExtensions\\Query\\Mysql\\Field');
     $config->addCustomStringFunction('FINDINSET', '\\DoctrineExtensions\\Query\\Mysql\\FindInSet');
     $config->addCustomStringFunction('GROUPCONCAT', '\\DoctrineExtensions\\Query\\Mysql\\GroupConcat');
     $config->addCustomStringFunction('HOUR', '\\DoctrineExtensions\\Query\\Mysql\\Hour');
     $config->addCustomStringFunction('IFELSE', '\\DoctrineExtensions\\Query\\Mysql\\IfElse');
     $config->addCustomStringFunction('IFNULL', '\\DoctrineExtensions\\Query\\Mysql\\IfNUll');
     $config->addCustomStringFunction('MATCHAGAINST', '\\DoctrineExtensions\\Query\\Mysql\\MatchAgainst');
     $config->addCustomStringFunction('MONTH', '\\DoctrineExtensions\\Query\\Mysql\\Month');
     $config->addCustomStringFunction('NULLIF', '\\DoctrineExtensions\\Query\\Mysql\\NullIf');
     $config->addCustomStringFunction('PI', '\\DoctrineExtensions\\Query\\Mysql\\Pi');
     $config->addCustomStringFunction('RADIANS', '\\DoctrineExtensions\\Query\\Mysql\\Radians');
     $config->addCustomStringFunction('RAND', '\\DoctrineExtensions\\Query\\Mysql\\Rand');
     $config->addCustomStringFunction('REGEXP', '\\DoctrineExtensions\\Query\\Mysql\\Regexp');
     $config->addCustomStringFunction('ROUND', '\\DoctrineExtensions\\Query\\Mysql\\Round');
     $config->addCustomStringFunction('SHA1', '\\DoctrineExtensions\\Query\\Mysql\\Sha1');
     $config->addCustomStringFunction('SHA2', '\\DoctrineExtensions\\Query\\Mysql\\Sha2');
     $config->addCustomStringFunction('SIN', '\\DoctrineExtensions\\Query\\Mysql\\Sin');
     $config->addCustomStringFunction('STRTODATE', '\\DoctrineExtensions\\Query\\Mysql\\StrToDate');
     $config->addCustomStringFunction('TAN', '\\DoctrineExtensions\\Query\\Mysql\\Tan');
     $config->addCustomStringFunction('TIMESTAMPDIFF', '\\DoctrineExtensions\\Query\\Mysql\\TimestampDiff');
     $config->addCustomStringFunction('WEEK', '\\DoctrineExtensions\\Query\\Mysql\\Week');
     $config->addCustomStringFunction('YEAR', '\\DoctrineExtensions\\Query\\Mysql\\Year');
     if (!defined('ENV') || ENV === \Fraym\Core::ENV_DEVELOPMENT) {
         $config->setAutoGenerateProxyClasses(true);
     }
     $modelDirs = $this->getModuleDirCache();
     \Doctrine\Common\Annotations\AnnotationRegistry::registerLoader(function ($class) {
         return class_exists($class, true);
     });
     $annotationReader = new \Doctrine\Common\Annotations\AnnotationReader();
     $this->cachedAnnotationReader = new \Doctrine\Common\Annotations\CachedReader($annotationReader, $cache);
     $this->annotationDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($this->cachedAnnotationReader, $modelDirs);
     /**
      * Ignore PHP-DI Annotation
      */
     $annotationReader->addGlobalIgnoredName('Injectable');
     $annotationReader->addGlobalIgnoredName('Inject');
     $config->setMetadataDriverImpl($this->annotationDriver);
     $config->setQueryCacheImpl($cache);
     $config->setResultCacheImpl($cache);
     $config->setProxyDir($applicationDir . DIRECTORY_SEPARATOR . CACHE_DOCTRINE_PROXY_PATH);
     $config->setProxyNamespace('Proxies');
     $this->fetchMode = \PDO::FETCH_OBJ;
     $tablePrefix = new TablePrefix(DB_TABLE_PREFIX);
     $this->eventManager = new \Doctrine\Common\EventManager();
     $this->eventManager->addEventListener(\Doctrine\ORM\Events::loadClassMetadata, $tablePrefix);
     $this->entityManager = \Doctrine\ORM\EntityManager::create($this->connectionOptions, $config, $this->eventManager);
     $this->pdo = $this->entityManager->getConnection();
     $this->pdo->getDatabasePlatform()->registerDoctrineTypeMapping('set', 'string');
     $driverChain = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
     \Gedmo\DoctrineExtensions::registerAbstractMappingIntoDriverChainORM($driverChain, $this->cachedAnnotationReader);
     $this->eventManager->addEventListener([\Doctrine\ORM\Events::preRemove, \Doctrine\ORM\Events::postRemove, \Doctrine\ORM\Events::prePersist, \Doctrine\ORM\Events::postPersist, \Doctrine\ORM\Events::preUpdate, \Doctrine\ORM\Events::postUpdate, \Doctrine\ORM\Events::postLoad, \Doctrine\ORM\Events::onFlush], $this->eventListener);
     return $this;
 }
Пример #23
0
 /**
  * Creates an entity manager.
  *
  * @param array $dbConnectionParameters Parameters used to connect to the database
  * @param string $tablePrefix Table prefix to use (optional)
  * @return \Doctrine\ORM\EntityManager
  */
 protected function createEntityManager($dbConnectionParameters, $tablePrefix = null)
 {
     // get table prefix set during installation if not provided
     if ($tablePrefix === null) {
         $tablePrefix = $this->getInstaller()->getInstallationParameter('db.tablePrefix', '');
     }
     // initialize Doctrine configuration
     $config = Setup::createAnnotationMetadataConfiguration(array(sprintf('%s/Modules/Core/Model/Entities', ABLERON_APP_DIR)), false, ABLERON_ROOT_DIR . '/generated/doctrine-proxies', new ArrayCache());
     // set namespace alias
     $config->addEntityNamespace('Core', 'Ableron\\Modules\\Core\\Model\\Entities');
     // configure event manager
     $eventManager = new EventManager();
     // handle table prefix
     if ($tablePrefix !== '') {
         $eventManager->addEventListener(Events::loadClassMetadata, new TablePrefixDoctrineExtension($tablePrefix));
     }
     // set up Doctrine's EntityManager
     return EntityManager::create($dbConnectionParameters, $config, $eventManager);
 }
Пример #24
0
 /**
  * @return EventManager
  */
 protected function createEventManager()
 {
     $eventManager = new EventManager();
     // Trap doctrine events, to support entity table prefix
     if ($prefix = config('doctrine.connection.prefix')) {
         $eventManager->addEventListener(Events::loadClassMetadata, new TablePrefix($prefix));
     }
     return $eventManager;
 }
 public function testGetAlterTableSqlDispatchEvent()
 {
     $events = array('onSchemaAlterTable', 'onSchemaAlterTableAddColumn', 'onSchemaAlterTableRemoveColumn', 'onSchemaAlterTableChangeColumn', 'onSchemaAlterTableRenameColumn');
     $listenerMock = $this->getMock('GetAlterTableSqlDispatchEvenListener', $events);
     $listenerMock->expects($this->once())->method('onSchemaAlterTable');
     $listenerMock->expects($this->once())->method('onSchemaAlterTableAddColumn');
     $listenerMock->expects($this->once())->method('onSchemaAlterTableRemoveColumn');
     $listenerMock->expects($this->once())->method('onSchemaAlterTableChangeColumn');
     $listenerMock->expects($this->once())->method('onSchemaAlterTableRenameColumn');
     $eventManager = new EventManager();
     $events = array(Events::onSchemaAlterTable, Events::onSchemaAlterTableAddColumn, Events::onSchemaAlterTableRemoveColumn, Events::onSchemaAlterTableChangeColumn, Events::onSchemaAlterTableRenameColumn);
     $eventManager->addEventListener($events, $listenerMock);
     $this->_platform->setEventManager($eventManager);
     $tableDiff = new TableDiff('mytable');
     $tableDiff->addedColumns['added'] = new \Doctrine\DBAL\Schema\Column('added', \Doctrine\DBAL\Types\Type::getType('integer'), array());
     $tableDiff->removedColumns['removed'] = new \Doctrine\DBAL\Schema\Column('removed', \Doctrine\DBAL\Types\Type::getType('integer'), array());
     $tableDiff->changedColumns['changed'] = new \Doctrine\DBAL\Schema\ColumnDiff('changed', new \Doctrine\DBAL\Schema\Column('changed2', \Doctrine\DBAL\Types\Type::getType('string'), array()), array());
     $tableDiff->renamedColumns['renamed'] = new \Doctrine\DBAL\Schema\Column('renamed2', \Doctrine\DBAL\Types\Type::getType('integer'), array());
     $this->_platform->getAlterTableSQL($tableDiff);
 }
Пример #26
0
 public function __construct(EventManager $evm)
 {
     $evm->addEventListener(array(self::postGenerateSchemaTable), $this);
 }
 public function testUpdate()
 {
     $query = ['a'];
     $newObj = ['b'];
     $options = ['c'];
     $modifiedQuery = ['d'];
     $modifiedNewObj = ['e'];
     $modifiedOptions = ['f'];
     // This listener will modify the data and options.
     $preUpdateListener = new PreUpdateListener($modifiedQuery, $modifiedNewObj, $modifiedOptions);
     $eventManager = new EventManager();
     $eventManager->addEventListener([Events::preUpdate], $preUpdateListener);
     // Ensure that the modified pipeline and options are sent to the doAggregate call.
     $collection = $this->getMockCollection($eventManager, ['doUpdate' => [$modifiedQuery, $modifiedNewObj, $modifiedOptions]]);
     $collection->update($query, $newObj, $options);
 }
Пример #28
0
 /**
  * Creates the global entity manager.
  *
  * @return \Doctrine\ORM\EntityManager
  */
 private function createEntityManager()
 {
     // find all modules and plugins that should be handled by the entity manager
     $managedModules = Application::getModuleManager()->getModules();
     $managedPlugins = Application::getPluginManager()->getPlugins();
     // initialize Doctrine configuration
     //TODO: Implement caching correctly (APC, memcached, XCache, ...); see \Doctrine\ORM\Tools\Setup::createConfiguration()
     $config = Setup::createAnnotationMetadataConfiguration($this->getEntityDirectories($managedModules, $managedPlugins), false, ABLERON_DOCTRINE_PROXY_DIR, null);
     // register namespace aliases for managed modules
     foreach ($managedModules as $managedModule) {
         $config->addEntityNamespace($managedModule->getNamespace(), sprintf('Ableron\\Modules\\%s\\Model\\Entities', $managedModule->getNamespace()));
     }
     // register namespace aliases for managed plugins
     foreach ($managedPlugins as $managedPlugin) {
         $config->addEntityNamespace($managedPlugin->getNamespace(), sprintf('Ableron\\Plugins\\%s\\Model\\Entities', $managedPlugin->getNamespace()));
     }
     // configure event manager
     $eventManager = new EventManager();
     // handle table prefix
     if (Application::getContext()->getSetting('doctrine.tablePrefix') !== '') {
         $eventManager->addEventListener(Events::loadClassMetadata, new TablePrefixDoctrineExtension(Application::getContext()->getSetting('doctrine.tablePrefix')));
     }
     // set up Doctrine's EntityManager
     return EntityManager::create(Application::getContext()->getSetting('doctrine.dbConnectionParameters'), $config, $eventManager);
 }
Пример #29
0
 /**
  * setup configuration for Doctrine ORM
  * 
  * @param array $db_config array config for override the default configuration.
  */
 public function setupConfigurationOrm(array $db_config = [])
 {
     // setup entity paths.
     // @todo [cms][modules] load models path from modules folder where module is enabled on certain site in db. Pending: decide to use Doctrine ORM or Spot ORM first.
     $paths = [];
     $fs = new \League\Flysystem\Filesystem(new \League\Flysystem\Adapter\Local(MODULE_PATH));
     $modules = $fs->listContents();
     if (is_array($modules)) {
         foreach ($modules as $module) {
             if (is_array($module) && array_key_exists('path', $module)) {
                 $module_dirs = $fs->listContents($module['path']);
                 if (is_array($module_dirs)) {
                     foreach ($module_dirs as $module_dir) {
                         if (is_array($module_dir) && array_key_exists('type', $module_dir) && $module_dir['type'] == 'dir' && array_key_exists('path', $module_dir) && array_key_exists('basename', $module_dir) && $module_dir['basename'] == 'Models') {
                             $paths[] = MODULE_PATH . DS . $module_dir['path'];
                         }
                     }
                     // endforeach;
                     unset($module_dir);
                 }
                 unset($module_dirs);
             }
         }
         // endforeach;
         unset($module);
     }
     unset($fs, $modules);
     // setup isDevmode.
     $config = new SystemConfig();
     $config->load('app');
     $is_devMode = $config->get('debug', 'app');
     //setup connection configuration.
     if (empty($db_config)) {
         $config->load('db');
         $db_params = $config->get('ALL', 'db');
         $table_prefix = $db_params['table_prefix'];
         unset($config, $db_params['table_prefix']);
     } else {
         // incase that there is overriden configuration.
         $db_params = $db_config;
         if (is_array($db_config)) {
             if (array_key_exists('table_prefix', $db_config)) {
                 $table_prefix = $db_config['table_prefix'];
             }
             if (array_key_exists('table_siteid_prefix', $db_config)) {
                 $table_siteid_prefix = $db_config['table_siteid_prefix'];
             }
         }
         unset($db_params['table_prefix'], $db_params['table_siteid_prefix']);
     }
     $evm = new EventManager();
     $table_prefix_class = new TablePrefix($table_prefix, isset($table_siteid_prefix) ? $table_siteid_prefix : '');
     $evm->addEventListener(Events::loadClassMetadata, $table_prefix_class);
     unset($table_prefix, $table_prefix_class);
     $doctrine_config = Setup::createAnnotationMetadataConfiguration($paths, $is_devMode);
     $doctrine_config->setSQLLogger(new \System\Libraries\Db\Logger());
     $this->EntityManager = EntityManager::create($db_params, $doctrine_config, $evm);
     unset($db_params, $doctrine_config, $evm, $is_devMode);
 }
 /**
  * Configures the Doctrine event manager instance.
  *
  * @param array        $doctrineConfig
  * @param EventManager $eventManager
  */
 protected function configureEventManager(array $doctrineConfig, EventManager $eventManager)
 {
     if (isset($doctrineConfig['event_listeners'])) {
         foreach ($doctrineConfig['event_listeners'] as $name => $listener) {
             $eventManager->addEventListener($listener['events'], new $listener['class']());
         }
     }
 }