DoctrineCommand.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. <?php
  2. namespace Doctrine\Bundle\DoctrineBundle\Command;
  3. use Doctrine\DBAL\Connection;
  4. use Doctrine\DBAL\Sharding\PoolingShardConnection;
  5. use Doctrine\ORM\EntityManager;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Doctrine\ORM\Tools\EntityGenerator;
  8. use Doctrine\Persistence\ManagerRegistry;
  9. use LogicException;
  10. use Symfony\Component\Console\Command\Command;
  11. use function sprintf;
  12. /**
  13. * Base class for Doctrine console commands to extend from.
  14. *
  15. * @internal
  16. */
  17. abstract class DoctrineCommand extends Command
  18. {
  19. /** @var ManagerRegistry */
  20. private $doctrine;
  21. public function __construct(ManagerRegistry $doctrine)
  22. {
  23. parent::__construct();
  24. $this->doctrine = $doctrine;
  25. }
  26. /**
  27. * get a doctrine entity generator
  28. *
  29. * @return EntityGenerator
  30. */
  31. protected function getEntityGenerator()
  32. {
  33. $entityGenerator = new EntityGenerator();
  34. $entityGenerator->setGenerateAnnotations(false);
  35. $entityGenerator->setGenerateStubMethods(true);
  36. $entityGenerator->setRegenerateEntityIfExists(false);
  37. $entityGenerator->setUpdateEntityIfExists(true);
  38. $entityGenerator->setNumSpaces(4);
  39. $entityGenerator->setAnnotationPrefix('ORM\\');
  40. return $entityGenerator;
  41. }
  42. /**
  43. * Get a doctrine entity manager by symfony name.
  44. *
  45. * @param string $name
  46. * @param int|null $shardId
  47. *
  48. * @return EntityManager
  49. */
  50. protected function getEntityManager($name, $shardId = null)
  51. {
  52. $manager = $this->getDoctrine()->getManager($name);
  53. if ($shardId) {
  54. if (! $manager instanceof EntityManagerInterface) {
  55. throw new LogicException(sprintf('Sharding is supported only in EntityManager of instance "%s".', EntityManagerInterface::class));
  56. }
  57. $connection = $manager->getConnection();
  58. if (! $connection instanceof PoolingShardConnection) {
  59. throw new LogicException(sprintf("Connection of EntityManager '%s' must implement shards configuration.", $name));
  60. }
  61. $connection->connect($shardId);
  62. }
  63. return $manager;
  64. }
  65. /**
  66. * Get a doctrine dbal connection by symfony name.
  67. *
  68. * @param string $name
  69. *
  70. * @return Connection
  71. */
  72. protected function getDoctrineConnection($name)
  73. {
  74. return $this->getDoctrine()->getConnection($name);
  75. }
  76. /**
  77. * @return ManagerRegistry
  78. */
  79. protected function getDoctrine()
  80. {
  81. return $this->doctrine;
  82. }
  83. }