ConnectionFactory.php 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /*
  3. * This file is part of the Doctrine Bundle
  4. *
  5. * The code was originally distributed inside the Symfony framework.
  6. *
  7. * (c) Fabien Potencier <fabien@symfony.com>
  8. * (c) Doctrine Project, Benjamin Eberlei <kontakt@beberlei.de>
  9. *
  10. * For the full copyright and license information, please view the LICENSE
  11. * file that was distributed with this source code.
  12. */
  13. namespace Doctrine\Bundle\DoctrineBundle;
  14. use Doctrine\Common\EventManager;
  15. use Doctrine\DBAL\Configuration;
  16. use Doctrine\DBAL\DriverManager;
  17. use Doctrine\DBAL\Types\Type;
  18. /**
  19. * Connection
  20. */
  21. class ConnectionFactory
  22. {
  23. private $typesConfig = array();
  24. private $commentedTypes = array();
  25. private $initialized = false;
  26. /**
  27. * Construct.
  28. *
  29. * @param array $typesConfig
  30. */
  31. public function __construct(array $typesConfig)
  32. {
  33. $this->typesConfig = $typesConfig;
  34. }
  35. /**
  36. * Create a connection by name.
  37. *
  38. * @param array $params
  39. * @param Configuration $config
  40. * @param EventManager $eventManager
  41. *
  42. * @return \Doctrine\DBAL\Connection
  43. */
  44. public function createConnection(array $params, Configuration $config = null, EventManager $eventManager = null, array $mappingTypes = array())
  45. {
  46. if (!$this->initialized) {
  47. $this->initializeTypes();
  48. $this->initialized = true;
  49. }
  50. $connection = DriverManager::getConnection($params, $config, $eventManager);
  51. if (!empty($mappingTypes)) {
  52. $platform = $connection->getDatabasePlatform();
  53. foreach ($mappingTypes as $dbType => $doctrineType) {
  54. $platform->registerDoctrineTypeMapping($dbType, $doctrineType);
  55. }
  56. foreach ($this->commentedTypes as $type) {
  57. $platform->markDoctrineTypeCommented(Type::getType($type));
  58. }
  59. }
  60. return $connection;
  61. }
  62. /**
  63. * initialize the types
  64. */
  65. private function initializeTypes()
  66. {
  67. foreach ($this->typesConfig as $type => $typeConfig) {
  68. if (Type::hasType($type)) {
  69. Type::overrideType($type, $typeConfig['class']);
  70. } else {
  71. Type::addType($type, $typeConfig['class']);
  72. }
  73. if ($typeConfig['commented']) {
  74. $this->commentedTypes[] = $type;
  75. }
  76. }
  77. }
  78. }