PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/library/Bisna/Doctrine/Container.php

http://github.com/guilhermeblanco/ZendFramework1-Doctrine2
PHP | 1095 lines | 668 code | 175 blank | 252 comment | 82 complexity | 07523b1f65d98fc7fe5cef61032f2945 MD5 | raw file
  1. <?php
  2. namespace Bisna\Doctrine;
  3. use Bisna\Exception,
  4. Doctrine\DBAL\Types\Type,
  5. Doctrine\Common\Annotations\AnnotationRegistry;
  6. /**
  7. * Doctrine Container class.
  8. *
  9. * @author Guilherme Blanco <guilhermeblanco@hotmail.com>
  10. */
  11. class Container
  12. {
  13. /**
  14. * @var string Default DBAL Connection name.
  15. */
  16. public $defaultConnection = 'default';
  17. /**
  18. * @var string Default Cache Instance name.
  19. */
  20. public $defaultCacheInstance = 'default';
  21. /**
  22. * @var string Default ODM DocumentManager name.
  23. */
  24. public $defaultDocumentManager = 'default';
  25. /**
  26. * @var string Default ORM EntityManager name.
  27. */
  28. public $defaultEntityManager = 'default';
  29. /**
  30. * @var array Doctrine Context configuration.
  31. */
  32. private $configuration = array();
  33. /**
  34. * @var array Available DBAL Connections.
  35. */
  36. private $connections = array();
  37. /**
  38. * @var array Available Cache Instances.
  39. */
  40. private $cacheInstances = array();
  41. /**
  42. * @var array Available ODM DocumentManagers.
  43. */
  44. private $documentManagers = array();
  45. /**
  46. * @var array Available ORM EntityManagers.
  47. */
  48. private $entityManagers = array();
  49. /**
  50. * Constructor.
  51. *
  52. * @param array $config Doctrine Container configuration
  53. */
  54. public function __construct(array $config = array())
  55. {
  56. // Registering Class Loaders
  57. if (isset($config['classLoader'])) {
  58. $this->registerClassLoaders($config['classLoader']);
  59. }
  60. // Defining DBAL configuration
  61. $dbalConfig = $this->prepareDBALConfiguration($config);
  62. // Defining default DBAL Connection name
  63. $this->defaultConnection = $dbalConfig['defaultConnection'];
  64. // Defining Cache configuration
  65. $cacheConfig = array();
  66. if (isset($config['cache'])) {
  67. $cacheConfig = $this->prepareCacheInstanceConfiguration($config);
  68. // Defining default Cache instance
  69. $this->defaultCacheInstance = $cacheConfig['defaultCacheInstance'];
  70. }
  71. // Defining ORM configuration
  72. $ormConfig = array();
  73. if (isset($config['orm'])) {
  74. $ormConfig = $this->prepareORMConfiguration($config);
  75. // Defining default ORM EntityManager
  76. $this->defaultEntityManager = $ormConfig['defaultEntityManager'];
  77. }
  78. // Defining ODM configuration
  79. if (isset($config['odm'])) {
  80. $odmConfig = $this->prepareODMConfiguration($config);
  81. // Defining default ORM EntityManager
  82. $this->defaultDocumentManager = $odmConfig['defaultDocumentManager'];
  83. }
  84. // Defining Doctrine Context configuration
  85. $this->configuration = array(
  86. 'dbal' => $dbalConfig['connections'],
  87. 'cache' => $cacheConfig['instances'],
  88. 'orm' => $ormConfig['entityManagers']
  89. );
  90. // In case a ODM configuration is available, add it to the main configuration
  91. if (isset($odmConfig['documentManagers'])) {
  92. $this->configuration['odm'] = $odmConfig['documentManagers'];
  93. }
  94. }
  95. /**
  96. * Register Doctrine Class Loaders
  97. *
  98. * @param array $config Doctrine Class Loader configuration
  99. */
  100. private function registerClassLoaders(array $config = array())
  101. {
  102. $classLoaderClass = $config['loaderClass'];
  103. $classLoaderFile = $config['loaderFile'];
  104. require_once $classLoaderFile;
  105. foreach ($config['loaders'] as $loaderItem) {
  106. if (! isset($loaderItem['includePath'])) {
  107. $loaderItem['includePath'] = null;
  108. }
  109. $classLoader = new $classLoaderClass($loaderItem['namespace'], $loaderItem['includePath']);
  110. $classLoader->register();
  111. }
  112. }
  113. /**
  114. * Prepare DBAL Connections configurations.
  115. *
  116. * @param array $config Doctrine Container configuration
  117. *
  118. * @return array
  119. */
  120. private function prepareDBALConfiguration(array $config = array())
  121. {
  122. $dbalConfig = $config['dbal'];
  123. $defaultConnectionName = isset($dbalConfig['defaultConnection'])
  124. ? $dbalConfig['defaultConnection'] : $this->defaultConnection;
  125. unset($dbalConfig['defaultConnection']);
  126. $defaultConnection = array(
  127. 'eventManagerClass' => 'Doctrine\Common\EventManager',
  128. 'eventSubscribers' => array(),
  129. 'configurationClass' => 'Doctrine\DBAL\Configuration',
  130. 'sqlLoggerClass' => null,
  131. 'sqlLoggerParams' => null,
  132. 'types' => array(),
  133. 'parameters' => array(
  134. 'wrapperClass' => null,
  135. 'driver' => 'pdo_mysql',
  136. 'host' => 'localhost',
  137. 'user' => 'root',
  138. 'password' => null,
  139. 'port' => null,
  140. 'driverOptions' => array()
  141. )
  142. );
  143. $connections = array();
  144. if (isset($dbalConfig['connections'])) {
  145. $configConnections = $dbalConfig['connections'];
  146. foreach ($configConnections as $name => $connection) {
  147. $name = isset($connection['id']) ? $connection['id'] : $name;
  148. $connections[$name] = array_replace_recursive($defaultConnection, $connection);
  149. }
  150. } else {
  151. $connections = array(
  152. $defaultConnectionName => array_replace_recursive($defaultConnection, $dbalConfig)
  153. );
  154. }
  155. return array(
  156. 'defaultConnection' => $defaultConnectionName,
  157. 'connections' => $connections
  158. );
  159. }
  160. /**
  161. * Prepare Cache Instances configurations.
  162. *
  163. * @param array $config Doctrine Container configuration
  164. *
  165. * @return array
  166. */
  167. private function prepareCacheInstanceConfiguration(array $config = array())
  168. {
  169. $cacheConfig = $config['cache'];
  170. $defaultCacheInstanceName = isset($cacheConfig['defaultCacheInstance'])
  171. ? $cacheConfig['defaultCacheInstance'] : $this->defaultCacheInstance;
  172. unset($cacheConfig['defaultCacheInstance']);
  173. $defaultCacheInstance = array(
  174. 'adapterClass' => 'Doctrine\Common\Cache\ArrayCache',
  175. 'namespace' => '',
  176. 'options' => array()
  177. );
  178. $instances = array();
  179. if (isset($cacheConfig['instances'])) {
  180. $configInstances = $cacheConfig['instances'];
  181. foreach ($configInstances as $name => $instance) {
  182. $name = isset($instance['id']) ? $instance['id'] : $name;
  183. $instances[$name] = array_replace_recursive($defaultCacheInstance, $instance);
  184. }
  185. } else {
  186. $instances = array(
  187. $defaultCacheInstanceName => array_replace_recursive($defaultCacheInstance, $cacheConfig)
  188. );
  189. }
  190. return array(
  191. 'defaultCacheInstance' => $defaultCacheInstanceName,
  192. 'instances' => $instances
  193. );
  194. }
  195. /**
  196. * Prepare ODM EntityManagers configurations.
  197. *
  198. * @param array $config Doctrine Container configuration
  199. *
  200. * @return array
  201. */
  202. private function prepareODMConfiguration(array $config = array())
  203. {
  204. $odmConfig = $config['odm'];
  205. $defaultDocumentManagerName = isset($odmConfig['defaultDocumentManager'])
  206. ? $odmConfig['defaultDocumentManager']
  207. : $this->defaultDocumentManager;
  208. unset($odmConfig['defaultDocumentManager']);
  209. $defaultDocumentManager = array(
  210. 'documentManagerClass' => 'Doctrine\ODM\MongoDB\DocumentManager',
  211. 'configurationClass' => 'Doctrine\ODM\MongoDB\Configuration',
  212. 'documentNamespaces' => array(),
  213. 'connection' => $this->defaultConnection,
  214. 'proxy' => array(
  215. 'autoGenerateClasses' => true,
  216. 'namespace' => 'Proxy',
  217. 'dir' => APPLICATION_PATH . '/../library/Proxy'
  218. ),
  219. 'hydrator' => array(
  220. 'namespace' => 'Hydrators',
  221. 'dir' => APPLICATION_PATH . '/../cache'
  222. ),
  223. 'queryCache' => $this->defaultCacheInstance,
  224. 'resultCache' => $this->defaultCacheInstance,
  225. 'metadataCache' => $this->defaultCacheInstance,
  226. 'metadataDrivers' => array(),
  227. 'connectionString' => ''
  228. );
  229. $documentManagers = array();
  230. if (isset($odmConfig['documentManagers'])) {
  231. $configDocumentManagers = $odmConfig['documentManagers'];
  232. foreach ($configDocumentManagers as $name => $documentManager) {
  233. $name = isset($documentManager['id']) ? $documentManager['id'] : $name;
  234. $documentManagers[$name] = array_replace_recursive($defaultDocumentManager, $documentManager);
  235. }
  236. } else {
  237. $documentManagers = array(
  238. $this->defaultConnection => array_replace_recursive($defaultDocumentManager, $odmConfig)
  239. );
  240. }
  241. return array(
  242. 'defaultDocumentManager' => $defaultDocumentManagerName,
  243. 'documentManagers' => $documentManagers
  244. );
  245. }
  246. /**
  247. * Prepare ORM EntityManagers configurations.
  248. *
  249. * @param array $config Doctrine Container configuration
  250. *
  251. * @return array
  252. */
  253. private function prepareORMConfiguration(array $config = array())
  254. {
  255. $ormConfig = $config['orm'];
  256. $defaultEntityManagerName = isset($ormConfig['defaultEntityManager'])
  257. ? $ormConfig['defaultEntityManager'] : $this->defaultEntityManager;
  258. unset($ormConfig['defaultEntityManager']);
  259. $defaultEntityManager = array(
  260. 'entityManagerClass' => 'Doctrine\ORM\EntityManager',
  261. 'configurationClass' => 'Doctrine\ORM\Configuration',
  262. 'entityNamespaces' => array(),
  263. 'connection' => $this->defaultConnection,
  264. 'proxy' => array(
  265. 'autoGenerateClasses' => true,
  266. 'namespace' => 'Proxy',
  267. 'dir' => APPLICATION_PATH . '/../library/Proxy'
  268. ),
  269. 'queryCache' => $this->defaultCacheInstance,
  270. 'resultCache' => $this->defaultCacheInstance,
  271. 'metadataCache' => $this->defaultCacheInstance,
  272. 'secondLevelCache' => array(
  273. 'enabled' => false,
  274. 'cache' => $this->defaultCacheInstance,
  275. 'cacheFactoryClass' => 'Doctrine\ORM\Cache\DefaultCacheFactory',
  276. 'regionsConfigurationClass' => 'Doctrine\ORM\Cache\RegionsConfiguration'
  277. ),
  278. 'metadataDrivers' => array(),
  279. 'namingStrategyClass' => 'Doctrine\ORM\Mapping\DefaultNamingStrategy',
  280. 'DQLFunctions' => array(
  281. 'numeric' => array(),
  282. 'datetime' => array(),
  283. 'string' => array()
  284. )
  285. );
  286. $entityManagers = array();
  287. if (isset($ormConfig['entityManagers'])) {
  288. $configEntityManagers = $ormConfig['entityManagers'];
  289. foreach ($configEntityManagers as $name => $entityManager) {
  290. $name = isset($entityManager['id']) ? $entityManager['id'] : $name;
  291. $entityManagers[$name] = array_replace_recursive($defaultEntityManager, $entityManager);
  292. }
  293. } else {
  294. $entityManagers = array(
  295. $this->defaultConnection => array_replace_recursive($defaultEntityManager, $ormConfig)
  296. );
  297. }
  298. return array(
  299. 'defaultEntityManager' => $defaultEntityManagerName,
  300. 'entityManagers' => $entityManagers
  301. );
  302. }
  303. /**
  304. * Retrieve DBAL Connection based on its name. If no argument is provided,
  305. * it will attempt to get the default Connection.
  306. * If DBAL Connection name could not be found, NameNotFoundException is thrown.
  307. *
  308. * @throws \Bisna\Exception\NameNotFoundException
  309. *
  310. * @param string $connName Optional DBAL Connection name
  311. *
  312. * @return \Doctrine\DBAL\Connection DBAL Connection
  313. */
  314. public function getConnection($connName = null)
  315. {
  316. $connName = $connName ?: $this->defaultConnection;
  317. // Check if DBAL Connection has not yet been initialized
  318. if ( ! isset($this->connections[$connName])) {
  319. // Check if DBAL Connection is configured
  320. if ( ! isset($this->configuration['dbal'][$connName])) {
  321. throw new Exception\NameNotFoundException("Unable to find Doctrine DBAL Connection '{$connName}'.");
  322. }
  323. $this->connections[$connName] = $this->startDBALConnection($this->configuration['dbal'][$connName]);
  324. unset($this->configuration['dbal'][$connName]);
  325. }
  326. return $this->connections[$connName];
  327. }
  328. /**
  329. * Retrieves a list of names for all Connections configured and/or loaded
  330. *
  331. * @return array
  332. */
  333. public function getConnectionNames()
  334. {
  335. $configuredConnections = array_keys($this->configuration['dbal']);
  336. $loadedConnections = array_keys($this->connections);
  337. return array_merge($configuredConnections, $loadedConnections);
  338. }
  339. /**
  340. * Retrieve Cache Instance based on its name. If no argument is provided,
  341. * it will attempt to get the default Instance.
  342. * If Cache Instance name could not be found, NameNotFoundException is thrown.
  343. *
  344. * @throws \Bisna\Exception\NameNotFoundException
  345. *
  346. * @param string $cacheName Optional Cache Instance name
  347. *
  348. * @return \Doctrine\Common\Cache\Cache Cache Instance
  349. */
  350. public function getCacheInstance($cacheName = null)
  351. {
  352. $cacheName = $cacheName ?: $this->defaultCacheInstance;
  353. // Check if Cache Instance has not yet been initialized
  354. if ( ! isset($this->cacheInstances[$cacheName])) {
  355. // Check if Cache Instance is configured
  356. if ( ! isset($this->configuration['cache'][$cacheName])) {
  357. throw new Exception\NameNotFoundException("Unable to find Doctrine Cache Instance '{$cacheName}'.");
  358. }
  359. $this->cacheInstances[$cacheName] = $this->startCacheInstance($this->configuration['cache'][$cacheName]);
  360. unset($this->configuration['cache'][$cacheName]);
  361. }
  362. return $this->cacheInstances[$cacheName];
  363. }
  364. /**
  365. * Retrieves a list of names for all cache instances configured
  366. *
  367. * @return array
  368. */
  369. public function getCacheInstanceNames()
  370. {
  371. $configuredInstances = array_keys($this->configuration['cache']);
  372. $loadedInstances = array_keys($this->cacheInstances);
  373. return array_merge($configuredInstances, $loadedInstances);
  374. }
  375. /**
  376. * Retrieve ODM DocumentManager based on its name. If no argument provided,
  377. * it will attempt to get the default DocumentManager.
  378. * If ODM DocumentManager name could not be found, NameNotFoundException is thrown.
  379. *
  380. * @throws \Core\Application\Exception\NameNotFoundException
  381. * @param string $dmName Optional ODM DocumentManager name
  382. * @return \Doctrine\ODM\MongoDB\DocumentManager
  383. */
  384. public function getDocumentManager($dmName = null)
  385. {
  386. $dmName = $dmName ?: $this->defaultDocumentManager;
  387. // Check if ORM Entity Manager has not yet been initialized
  388. if ( ! isset($this->documentManagers[$dmName])) {
  389. // Check if ORM EntityManager is configured
  390. if ( ! isset($this->configuration['odm'][$dmName])) {
  391. throw new \Core\Application\Exception\NameNotFoundException("Unable to find Doctrine ODM DocumentManager '{$dmName}'.");
  392. }
  393. $this->documentManagers[$dmName] = $this->startODMDocumentManager($this->configuration['odm'][$dmName]);
  394. unset($this->configuration['odm'][$dmName]);
  395. }
  396. return $this->documentManagers[$dmName];
  397. }
  398. /**
  399. * Retrieve ORM EntityManager based on its name. If no argument provided,
  400. * it will attempt to get the default EntityManager.
  401. * If ORM EntityManager name could not be found, NameNotFoundException is thrown.
  402. *
  403. * @throws \Bisna\Exception\NameNotFoundException
  404. *
  405. * @param string $emName Optional ORM EntityManager name
  406. *
  407. * @return \Doctrine\ORM\EntityManager ORM EntityManager
  408. */
  409. public function getEntityManager($emName = null)
  410. {
  411. $emName = $emName ?: $this->defaultEntityManager;
  412. // Check if ORM Entity Manager has not yet been initialized
  413. if ( ! isset($this->entityManagers[$emName])) {
  414. // Check if ORM EntityManager is configured
  415. if ( ! isset($this->configuration['orm'][$emName])) {
  416. throw new Exception\NameNotFoundException("Unable to find Doctrine ORM EntityManager '{$emName}'.");
  417. }
  418. $this->entityManagers[$emName] = $this->startORMEntityManager($this->configuration['orm'][$emName]);
  419. unset($this->configuration['orm'][$emName]);
  420. }
  421. return $this->entityManagers[$emName];
  422. }
  423. /**
  424. * Retrieves a list of names for all Entity Managers configured and/or loaded
  425. *
  426. * @return array
  427. */
  428. public function getEntityManagerNames()
  429. {
  430. $configuredEMs = array_keys($this->configuration['orm']);
  431. $loadedEMs = array_keys($this->entityManagers);
  432. return array_merge($configuredEMs, $loadedEMs);
  433. }
  434. /**
  435. * Initialize the DBAL Connection.
  436. *
  437. * @param array $config DBAL Connection configuration.
  438. *
  439. * @return \Doctrine\DBAL\Connection
  440. */
  441. private function startDBALConnection(array $config = array())
  442. {
  443. $connection = \Doctrine\DBAL\DriverManager::getConnection(
  444. $config['parameters'],
  445. $this->startDBALConfiguration($config),
  446. $this->startDBALEventManager($config)
  447. );
  448. // Type mappings
  449. if (isset($config['typeMapping'])) {
  450. foreach ($config['typeMapping'] as $dbType => $doctrineType) {
  451. $connection->getDatabasePlatform()->registerDoctrineTypeMapping($dbType, $doctrineType);
  452. }
  453. }
  454. return $connection;
  455. }
  456. /**
  457. * Initialize the DBAL Configuration.
  458. *
  459. * @param array $config DBAL Connection configuration.
  460. *
  461. * @return \Doctrine\DBAL\Configuration
  462. */
  463. private function startDBALConfiguration(array $config = array())
  464. {
  465. $configClass = $config['configurationClass'];
  466. $configuration = new $configClass();
  467. // SQL Logger configuration
  468. if ( ! empty($config['sqlLoggerClass'])) {
  469. $sqlLoggerClass = $config['sqlLoggerClass'];
  470. if ( !empty($config['sqlLoggerParams']) ) {
  471. $configuration->setSQLLogger(new $sqlLoggerClass($config['sqlLoggerParams']));
  472. } else {
  473. $configuration->setSQLLogger(new $sqlLoggerClass());
  474. }
  475. }
  476. //DBAL Types configuration
  477. $types = $config['types'];
  478. foreach ($types as $name => $className) {
  479. if (Type::hasType($name)) {
  480. Type::overrideType($name, $className);
  481. } else {
  482. Type::addType($name, $className);
  483. }
  484. }
  485. return $configuration;
  486. }
  487. /**
  488. * Initialize the EventManager.
  489. *
  490. * @param array $config DBAL Connection configuration.
  491. *
  492. * @return \Doctrine\Common\EventManager
  493. */
  494. private function startDBALEventManager(array $config = array())
  495. {
  496. $eventManagerClass = $config['eventManagerClass'];
  497. $eventManager = new $eventManagerClass();
  498. // Event Subscribers configuration
  499. foreach ($config['eventSubscribers'] as $subscriber) {
  500. if ($subscriber) {
  501. $eventManager->addEventSubscriber(new $subscriber());
  502. }
  503. }
  504. return $eventManager;
  505. }
  506. /**
  507. * Initialize Cache Instance.
  508. *
  509. * @param array $config Cache Instance configuration.
  510. *
  511. * @return \Doctrine\Common\Cache\Cache
  512. */
  513. private function startCacheInstance(array $config = array())
  514. {
  515. $adapterClass = $config['adapterClass'];
  516. // FilesystemCache (extending abstract FileCache class) expects the directory as a parameter in the constructor
  517. if( $adapterClass == 'Doctrine\Common\Cache\FilesystemCache') {
  518. $directory = isset($config['options']['directory']) ? $config['options']['directory'] : '/tmp/doctrine';
  519. $extension = isset($config['options']['extension']) ? $config['options']['extension'] : null;
  520. $adapter = new $adapterClass($directory, $extension);
  521. } else {
  522. $adapter = new $adapterClass();
  523. }
  524. // Define namespace for cache
  525. if (isset($config['namespace']) && ! empty($config['namespace'])) {
  526. $adapter->setNamespace($config['namespace']);
  527. }
  528. if (method_exists($adapter, 'initialize')) {
  529. $adapter->initialize($config);
  530. } else if ($adapter instanceof \Doctrine\Common\Cache\CouchbaseCache) {
  531. // Couchbase configuration
  532. $hosts = isset($config['options']['hosts']) ? $config['options']['hosts'] : array('localhost');
  533. $user = isset($config['options']['user']) ? $config['options']['user'] : '';
  534. $password = isset($config['options']['password']) ? $config['options']['password'] : '';
  535. $bucket = isset($config['options']['bucket']) ? $config['options']['bucket'] : 'default';
  536. $persistent = isset($config['options']['persistent']) ? $config['options']['persistent'] : true;
  537. // Prevent stupid PHP error of missing extension (if other driver is being used)
  538. $couchbaseClassName = 'Couchbase';
  539. $couchbase = new $couchbaseClassName($hosts, $user, $password, $bucket, $persistent);
  540. $adapter->setCouchbase($couchbase);
  541. } else if ($adapter instanceof \Doctrine\Common\Cache\MemcacheCache) {
  542. // Prevent stupid PHP error of missing extension (if other driver is being used)
  543. $memcacheClassName = 'Memcache';
  544. $memcache = new $memcacheClassName();
  545. // Default server configuration
  546. $defaultServer = array(
  547. 'host' => 'localhost',
  548. 'port' => 11211,
  549. 'persistent' => true,
  550. 'weight' => 1,
  551. 'timeout' => 1,
  552. 'retryInterval' => 15,
  553. 'status' => true
  554. );
  555. if (isset($config['options']['servers'])) {
  556. foreach ($config['options']['servers'] as $server) {
  557. $server = array_replace_recursive($defaultServer, $server);
  558. $memcache->addServer(
  559. $server['host'],
  560. $server['port'],
  561. $server['persistent'],
  562. $server['weight'],
  563. $server['timeout'],
  564. $server['retryInterval'],
  565. $server['status']
  566. );
  567. }
  568. }
  569. $adapter->setMemcache($memcache);
  570. } else if ($adapter instanceof \Doctrine\Common\Cache\MemcachedCache) {
  571. // Prevent stupid PHP error of missing extension (if other driver is being used)
  572. $memcacheClassName = 'Memcached';
  573. $memcache = new $memcacheClassName();
  574. // Default server configuration
  575. $defaultServer = array(
  576. 'host' => 'localhost',
  577. 'port' => 11211,
  578. 'weight' => 1,
  579. );
  580. if (isset($config['options']['servers'])) {
  581. foreach ($config['options']['servers'] as $server) {
  582. $server = array_replace_recursive($defaultServer, $server);
  583. $memcache->addServer(
  584. $server['host'],
  585. $server['port'],
  586. $server['weight']
  587. );
  588. }
  589. }
  590. $adapter->setMemcached($memcache);
  591. } else if ($adapter instanceof \Doctrine\Common\Cache\RedisCache) {
  592. // Prevent stupid PHP error of missing extension (if other driver is being used)
  593. $redisClassName = 'Redis';
  594. $redis = new $redisClassName();
  595. // Default server configuration
  596. $defaultServer = array(
  597. 'host' => 'localhost',
  598. 'port' => 6379,
  599. 'timeout' => 0,
  600. 'persistent' => false,
  601. 'persistentId' => null,
  602. 'prefix' => null,
  603. 'password' => null,
  604. 'database' => 0,
  605. );
  606. $server = isset($config['options'])
  607. ? array_replace_recursive($defaultServer, $config['options'])
  608. : $defaultServer;
  609. if (isset($server['persistent']) && $server['persistent']) {
  610. $redis->pconnect(
  611. $server['host'],
  612. $server['port'],
  613. $server['timeout'],
  614. isset($server['persistentId']) ? $server['persistentId'] : null
  615. );
  616. } else {
  617. $redis->connect(
  618. $server['host'],
  619. $server['port'],
  620. $server['timeout']
  621. );
  622. }
  623. if (isset($server['password'])) {
  624. $redis->auth($server['password']);
  625. }
  626. if (isset($server['prefix'])) {
  627. $redis->setOption(\Redis::OPT_PREFIX, $server['prefix']);
  628. }
  629. $redis->select($server['database']);
  630. $adapter->setRedis($redis);
  631. }
  632. return $adapter;
  633. }
  634. /**
  635. * Initialize the ODM Document Manager
  636. *
  637. * @param array $config
  638. * @return \Doctrine\ODM\MongoDB\DocumentManager
  639. */
  640. private function startODMDocumentManager(array $config = array())
  641. {
  642. return \Doctrine\ODM\MongoDB\DocumentManager::create(
  643. new \Doctrine\MongoDB\Connection($config['connectionString']),
  644. $this->startODMConfiguration($config)
  645. );
  646. }
  647. /**
  648. * Initialize ORM EntityManager.
  649. *
  650. * @param array $config ORM EntityManager configuration.
  651. *
  652. * @return \Doctrine\ORM\EntityManager
  653. */
  654. private function startORMEntityManager(array $config = array())
  655. {
  656. if (isset($config['entityManagerClass'])) {
  657. $entityManagerClass = $config['entityManagerClass'];
  658. } else {
  659. $entityManagerClass = '\Doctrine\ORM\EntityManager';
  660. }
  661. return $entityManagerClass::create(
  662. $this->getConnection($config['connection']),
  663. $this->startORMConfiguration($config)
  664. );
  665. }
  666. /**
  667. * Initialize ODM Configuration.
  668. *
  669. * @param array $config ODM DocumentManager configuration.
  670. * @return \Doctrine\ODM\MongoDB\Configuration
  671. */
  672. private function startODMConfiguration(array $config = array())
  673. {
  674. $configClass = $config['configurationClass'];
  675. $configuration = new $configClass();
  676. $configuration = new \Doctrine\ODM\MongoDB\Configuration();
  677. // Entity Namespaces configuration
  678. foreach ($config['documentNamespaces'] as $alias => $namespace) {
  679. $configuration->addDocumentNamespace($alias, $namespace);
  680. }
  681. // Proxy configuration
  682. $configuration->setAutoGenerateProxyClasses(
  683. $config['proxy']['autoGenerateClasses'] === true ||
  684. ! in_array($config['proxy']['autoGenerateClasses'], array("0", "false", false))
  685. );
  686. $configuration->setProxyNamespace($config['proxy']['namespace']);
  687. $configuration->setProxyDir($config['proxy']['dir']);
  688. $configuration->setHydratorDir($config['hydrator']['dir']);
  689. $configuration->setHydratorNamespace($config['hydrator']['namespace']);
  690. // Cache configuration
  691. $configuration->setMetadataCacheImpl($this->getCacheInstance($config['metadataCache']));
  692. // Metadata configuration
  693. $configuration->setMetadataDriverImpl($this->startODMMetadata($config['metadataDrivers']));
  694. if (isset($config['defaultDb'])) {
  695. $configuration->setDefaultDB($config['defaultDb']);
  696. }
  697. if (isset($config['environment'])) {
  698. $configuration->setDefaultDB($config['environment']);
  699. }
  700. return $configuration;
  701. }
  702. /**
  703. * Initialize ORM Configuration.
  704. *
  705. * @param array $config ORM EntityManager configuration.
  706. *
  707. * @return \Doctrine\ORM\Configuration
  708. */
  709. private function startORMConfiguration(array $config = array())
  710. {
  711. $configClass = $config['configurationClass'];
  712. $configuration = new $configClass();
  713. $configuration = new \Doctrine\ORM\Configuration();
  714. // Entity Namespaces configuration
  715. foreach ($config['entityNamespaces'] as $alias => $namespace) {
  716. $configuration->addEntityNamespace($alias, $namespace);
  717. }
  718. // Proxy configuration
  719. $configuration->setAutoGenerateProxyClasses(
  720. $config['proxy']['autoGenerateClasses'] === true ||
  721. ! in_array($config['proxy']['autoGenerateClasses'], array("0", "false", false))
  722. );
  723. $configuration->setProxyNamespace($config['proxy']['namespace']);
  724. $configuration->setProxyDir($config['proxy']['dir']);
  725. // Cache configuration
  726. $configuration->setMetadataCacheImpl($this->getCacheInstance($config['metadataCache']));
  727. $configuration->setResultCacheImpl($this->getCacheInstance($config['resultCache']));
  728. $configuration->setQueryCacheImpl($this->getCacheInstance($config['queryCache']));
  729. // SecondLevelCache configuration
  730. if(isset($config['secondLevelCache']) && method_exists($configuration, 'setSecondLevelCacheEnabled')) {
  731. $configuration->setSecondLevelCacheEnabled(
  732. $config['secondLevelCache']['enabled'] === true ||
  733. !in_array($config['secondLevelCache']['enabled'], array("0", "false", false))
  734. );
  735. if ($configuration->isSecondLevelCacheEnabled()) {
  736. $regionsConfigurationClass = $config['secondLevelCache']['regionsConfigurationClass'];
  737. $factoryClass = $config['secondLevelCache']['cacheFactoryClass'];
  738. $factory = new $factoryClass(new $regionsConfigurationClass(), $this->getCacheInstance($config['secondLevelCache']['cache']));
  739. $configuration->getSecondLevelCacheConfiguration()->setCacheFactory($factory);
  740. if (isset($config['secondLevelCache']['loggerClass'])) {
  741. $loggerClass = $config['secondLevelCache']['loggerClass'];
  742. $configuration->getSecondLevelCacheConfiguration()->setCacheLogger(new $loggerClass());
  743. }
  744. }
  745. }
  746. // Metadata configuration
  747. $configuration->setMetadataDriverImpl($this->startORMMetadata($config['metadataDrivers']));
  748. //Filters http://doctrine-orm.readthedocs.org/en/latest/reference/filters.html#configuration
  749. if(isset($config['filters'])){
  750. foreach ($config['filters'] as $name => $className) {
  751. $configuration->addFilter($name, $className);
  752. }
  753. }
  754. // DQL Functions configuration
  755. $dqlFunctions = $config['DQLFunctions'];
  756. foreach ($dqlFunctions['datetime'] as $name => $className) {
  757. $configuration->addCustomDatetimeFunction($name, $className);
  758. }
  759. foreach ($dqlFunctions['numeric'] as $name => $className) {
  760. $configuration->addCustomNumericFunction($name, $className);
  761. }
  762. foreach ($dqlFunctions['string'] as $name => $className) {
  763. $configuration->addCustomStringFunction($name, $className);
  764. }
  765. // Repository Class configuration
  766. if (isset($config['defaultRepositoryClass'])) {
  767. $configuration->setDefaultRepositoryClassName($config['defaultRepositoryClass']);
  768. }
  769. // Naming strategy for ORM
  770. $configuration->setNamingStrategy(new $config['namingStrategyClass']);
  771. return $configuration;
  772. }
  773. /**
  774. * Initialize ODM Metadata drivers.
  775. *
  776. * @param array $config ODM Mapping drivers.
  777. * @return \Doctrine\ODM\MongoDB\Mapping\Driver\DriverChain
  778. */
  779. private function startODMMetadata(array $config = array())
  780. {
  781. $metadataDriver = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
  782. // Default metadata driver configuration
  783. $defaultMetadataDriver = array(
  784. 'adapterClass' => 'Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver',
  785. 'mappingNamespace' => '',
  786. 'mappingDirs' => array(),
  787. 'annotationReaderClass' => 'Doctrine\Common\Annotations\AnnotationReader',
  788. 'annotationReaderCache' => $this->defaultCacheInstance,
  789. 'annotationReaderNamespaces' => array()
  790. );
  791. // Setup ODM AnnotationRegistry
  792. if (isset($config['annotationRegistry'])) {
  793. $this->startAnnotationRegistry($config['annotationRegistry']);
  794. }
  795. foreach ($config['drivers'] as $driver) {
  796. $driver = array_replace_recursive($defaultMetadataDriver, $driver);
  797. if (method_exists($driver['adapterClass'], 'registerAnnotationClasses')) {
  798. $driver['adapterClass']::registerAnnotationClasses();
  799. }
  800. $reflClass = new \ReflectionClass($driver['adapterClass']);
  801. $nestedDriver = null;
  802. if (
  803. $reflClass->getName() == 'Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver' ||
  804. $reflClass->isSubclassOf('Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver')
  805. ) {
  806. $annotationReaderClass = $driver['annotationReaderClass'];
  807. $annotationReader = new $annotationReaderClass();
  808. if (method_exists($annotationReader, 'setDefaultAnnotationNamespace')) {
  809. $annotationReader->setDefaultAnnotationNamespace('Doctrine\ODM\MongoDB\Mapping\\');
  810. }
  811. if (method_exists($annotationReader, 'setAnnotationNamespaceAlias')) {
  812. $driver['annotationReaderNamespaces']['ODM'] = 'Doctrine\ODM\MongoDB\Mapping\\';
  813. foreach ($driver['annotationReaderNamespaces'] as $alias => $namespace) {
  814. $annotationReader->setAnnotationNamespaceAlias($namespace, $alias);
  815. }
  816. }
  817. $indexedReader = new \Doctrine\Common\Annotations\CachedReader(
  818. new \Doctrine\Common\Annotations\IndexedReader($annotationReader),
  819. $this->getCacheInstance($driver['annotationReaderCache'])
  820. );
  821. $nestedDriver = $reflClass->newInstance($indexedReader, $driver['mappingDirs']);
  822. } else {
  823. $nestedDriver = $reflClass->newInstance($driver['mappingDirs']);
  824. }
  825. $metadataDriver->addDriver($nestedDriver, $driver['mappingNamespace']);
  826. }
  827. if (($drivers = $metadataDriver->getDrivers()) && count($drivers) == 1) {
  828. reset($drivers);
  829. $metadataDriver = $drivers[key($drivers)];
  830. }
  831. return $metadataDriver;
  832. }
  833. /**
  834. * Initialize ORM Metadata drivers.
  835. *
  836. * @param array $config ORM Mapping drivers.
  837. *
  838. * @return \Doctrine\ORM\Mapping\Driver\DriverChain
  839. */
  840. private function startORMMetadata(array $config = array())
  841. {
  842. $metadataDriver = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
  843. // Default metadata driver configuration
  844. $defaultMetadataDriver = array(
  845. 'adapterClass' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
  846. 'mappingNamespace' => '',
  847. 'mappingDirs' => array(),
  848. 'annotationReaderClass' => 'Doctrine\Common\Annotations\AnnotationReader',
  849. 'annotationReaderCache' => $this->defaultCacheInstance,
  850. 'annotationReaderNamespaces' => array()
  851. );
  852. // Setup AnnotationRegistry
  853. if (isset($config['annotationRegistry'])) {
  854. $this->startAnnotationRegistry($config['annotationRegistry']);
  855. }
  856. foreach ($config['drivers'] as $driver) {
  857. $driver = array_replace_recursive($defaultMetadataDriver, $driver);
  858. $reflClass = new \ReflectionClass($driver['adapterClass']);
  859. $nestedDriver = null;
  860. if (
  861. $reflClass->getName() == 'Doctrine\ORM\Mapping\Driver\AnnotationDriver' ||
  862. $reflClass->isSubclassOf('Doctrine\ORM\Mapping\Driver\AnnotationDriver')
  863. ) {
  864. $annotationReaderClass = $driver['annotationReaderClass'];
  865. $annotationReader = new $annotationReaderClass();
  866. // For Doctrine >= 2.2
  867. if (method_exists($annotationReader, 'addNamespace')) {
  868. $annotationReader->addNamespace('Doctrine\ORM\Mapping');
  869. }
  870. if (method_exists($annotationReader, 'setDefaultAnnotationNamespace')) {
  871. $annotationReader->setDefaultAnnotationNamespace('Doctrine\ORM\Mapping\\');
  872. }
  873. if (method_exists($annotationReader, 'setAnnotationNamespaceAlias')) {
  874. $driver['annotationReaderNamespaces']['ORM'] = 'Doctrine\ORM\Mapping\\';
  875. foreach ($driver['annotationReaderNamespaces'] as $alias => $namespace) {
  876. $annotationReader->setAnnotationNamespaceAlias($namespace, $alias);
  877. }
  878. }
  879. $indexedReader = new \Doctrine\Common\Annotations\CachedReader(
  880. new \Doctrine\Common\Annotations\IndexedReader($annotationReader),
  881. $this->getCacheInstance($driver['annotationReaderCache'])
  882. );
  883. $nestedDriver = $reflClass->newInstance($indexedReader, $driver['mappingDirs']);
  884. } else {
  885. $nestedDriver = $reflClass->newInstance($driver['mappingDirs']);
  886. }
  887. $metadataDriver->addDriver($nestedDriver, $driver['mappingNamespace']);
  888. }
  889. if (($drivers = $metadataDriver->getDrivers()) && count($drivers) == 1) {
  890. reset($drivers);
  891. $metadataDriver = $drivers[key($drivers)];
  892. }
  893. return $metadataDriver;
  894. }
  895. /**
  896. * Initialize ORM Metadata Annotation Registry driver
  897. *
  898. * @param array $config ORM Annotation Registry configuration.
  899. */
  900. private function startAnnotationRegistry($config)
  901. {
  902. // Load annotations from Files
  903. if (isset($config['annotationFiles']) && is_array($config['annotationFiles'])) {
  904. foreach($config['annotationFiles'] as $file) {
  905. AnnotationRegistry::registerFile($file);
  906. }
  907. }
  908. // Load annotation namespaces
  909. if (isset($config['annotationNamespaces']) && is_array($config['annotationNamespaces'])) {
  910. foreach($config['annotationNamespaces'] as $annotationNamespace) {
  911. AnnotationRegistry::registerAutoloadNamespace(
  912. $annotationNamespace['namespace']
  913. , isset($annotationNamespace['includePath']) ? $annotationNamespace['includePath'] : null
  914. );
  915. }
  916. }
  917. }
  918. }