OrmSchemaProvider.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\Migrations\Provider;
  4. use Doctrine\DBAL\Schema\Schema;
  5. use Doctrine\Migrations\Provider\Exception\NoMappingFound;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use Doctrine\ORM\Mapping\ClassMetadata;
  8. use Doctrine\ORM\Tools\SchemaTool;
  9. use function count;
  10. use function usort;
  11. /**
  12. * The OrmSchemaProvider class is responsible for creating a Doctrine\DBAL\Schema\Schema instance from the mapping
  13. * information provided by the Doctrine ORM. This is then used to diff against your current database schema to produce
  14. * a migration to bring your database in sync with the ORM mapping information.
  15. *
  16. * @internal
  17. */
  18. final class OrmSchemaProvider implements SchemaProvider
  19. {
  20. /** @var EntityManagerInterface */
  21. private $entityManager;
  22. public function __construct(EntityManagerInterface $em)
  23. {
  24. $this->entityManager = $em;
  25. }
  26. /**
  27. * @throws NoMappingFound
  28. */
  29. public function createSchema(): Schema
  30. {
  31. $metadata = $this->entityManager->getMetadataFactory()->getAllMetadata();
  32. if (count($metadata) === 0) {
  33. throw NoMappingFound::new();
  34. }
  35. usort($metadata, static function (ClassMetadata $a, ClassMetadata $b): int {
  36. return $a->getTableName() <=> $b->getTableName();
  37. });
  38. $tool = new SchemaTool($this->entityManager);
  39. return $tool->getSchemaFromMetadata($metadata);
  40. }
  41. }