DoctrineCommand.php 2.2 KB

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