FileQueryWriter.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. declare(strict_types=1);
  3. namespace Doctrine\Migrations;
  4. use DateTimeImmutable;
  5. use DateTimeInterface;
  6. use Doctrine\Migrations\Generator\FileBuilder;
  7. use Doctrine\Migrations\Query\Query;
  8. use Psr\Log\LoggerInterface;
  9. use function file_put_contents;
  10. use function is_dir;
  11. use function realpath;
  12. /**
  13. * The FileQueryWriter class is responsible for writing migration SQL queries to a file on disk.
  14. *
  15. * @internal
  16. */
  17. final class FileQueryWriter implements QueryWriter
  18. {
  19. /** @var FileBuilder */
  20. private $migrationFileBuilder;
  21. /** @var LoggerInterface */
  22. private $logger;
  23. public function __construct(
  24. FileBuilder $migrationFileBuilder,
  25. LoggerInterface $logger
  26. ) {
  27. $this->migrationFileBuilder = $migrationFileBuilder;
  28. $this->logger = $logger;
  29. }
  30. /**
  31. * @param array<string,Query[]> $queriesByVersion
  32. */
  33. public function write(
  34. string $path,
  35. string $direction,
  36. array $queriesByVersion,
  37. ?DateTimeInterface $now = null
  38. ): bool {
  39. $now = $now ?? new DateTimeImmutable();
  40. $string = $this->migrationFileBuilder
  41. ->buildMigrationFile($queriesByVersion, $direction, $now);
  42. $path = $this->buildMigrationFilePath($path, $now);
  43. $this->logger->info('Writing migration file to "{path}"', ['path' => $path]);
  44. return file_put_contents($path, $string) !== false;
  45. }
  46. private function buildMigrationFilePath(string $path, DateTimeInterface $now): string
  47. {
  48. if (is_dir($path)) {
  49. $path = realpath($path);
  50. $path .= '/doctrine_migration_' . $now->format('YmdHis') . '.sql';
  51. }
  52. return $path;
  53. }
  54. }