Configuration.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. *
  15. * This software consists of voluntary contributions made by many individuals
  16. * and is licensed under the LGPL. For more information, see
  17. * <http://www.doctrine-project.org>.
  18. */
  19. namespace Doctrine\DBAL\Migrations\Configuration;
  20. use Doctrine\DBAL\Connection;
  21. use Doctrine\DBAL\Connections\MasterSlaveConnection;
  22. use Doctrine\DBAL\Migrations\Finder\MigrationDeepFinderInterface;
  23. use Doctrine\DBAL\Migrations\MigrationException;
  24. use Doctrine\DBAL\Migrations\OutputWriter;
  25. use Doctrine\DBAL\Migrations\Version;
  26. use Doctrine\DBAL\Migrations\Finder\MigrationFinderInterface;
  27. use Doctrine\DBAL\Migrations\Finder\RecursiveRegexFinder;
  28. use Doctrine\DBAL\Schema\Column;
  29. use Doctrine\DBAL\Schema\Table;
  30. use Doctrine\DBAL\Types\Type;
  31. /**
  32. * Default Migration Configuration object used for configuring an instance of
  33. * the Migration class. Set the connection, version table name, register migration
  34. * classes/versions, etc.
  35. *
  36. * @license http://www.opensource.org/licenses/lgpl-license.php LGPL
  37. * @link www.doctrine-project.org
  38. * @since 2.0
  39. * @author Jonathan H. Wage <jonwage@gmail.com>
  40. */
  41. class Configuration
  42. {
  43. /**
  44. * Configure versions to be organized by year.
  45. */
  46. const VERSIONS_ORGANIZATION_BY_YEAR = 'year';
  47. /**
  48. * Configure versions to be organized by year and month.
  49. *
  50. * @var string
  51. */
  52. const VERSIONS_ORGANIZATION_BY_YEAR_AND_MONTH = 'year_and_month';
  53. /**
  54. * The date format for new version numbers
  55. */
  56. const VERSION_FORMAT = 'YmdHis';
  57. /**
  58. * Name of this set of migrations
  59. *
  60. * @var string
  61. */
  62. private $name;
  63. /**
  64. * Flag for whether or not the migration table has been created
  65. *
  66. * @var boolean
  67. */
  68. private $migrationTableCreated = false;
  69. /**
  70. * Connection instance to use for migrations
  71. *
  72. * @var Connection
  73. */
  74. private $connection;
  75. /**
  76. * OutputWriter instance for writing output during migrations
  77. *
  78. * @var OutputWriter
  79. */
  80. private $outputWriter;
  81. /**
  82. * The migration finder implementation -- used to load migrations from a
  83. * directory.
  84. *
  85. * @var MigrationFinderInterface
  86. */
  87. private $migrationFinder;
  88. /**
  89. * The migration table name to track versions in
  90. *
  91. * @var string
  92. */
  93. private $migrationsTableName = 'doctrine_migration_versions';
  94. /**
  95. * The migration column name to track versions in
  96. *
  97. * @var string
  98. */
  99. private $migrationsColumnName = 'version';
  100. /**
  101. * The path to a directory where new migration classes will be written
  102. *
  103. * @var string
  104. */
  105. private $migrationsDirectory;
  106. /**
  107. * Namespace the migration classes live in
  108. *
  109. * @var string
  110. */
  111. private $migrationsNamespace;
  112. /**
  113. * Array of the registered migrations
  114. *
  115. * @var Version[]
  116. */
  117. private $migrations = [];
  118. /**
  119. * Versions are organized by year.
  120. *
  121. * @var boolean
  122. */
  123. private $migrationsAreOrganizedByYear = false;
  124. /**
  125. * Versions are organized by year and month.
  126. *
  127. * @var boolean
  128. */
  129. private $migrationsAreOrganizedByYearAndMonth = false;
  130. /**
  131. * Construct a migration configuration object.
  132. *
  133. * @param Connection $connection A Connection instance
  134. * @param OutputWriter $outputWriter A OutputWriter instance
  135. * @param MigrationFinderInterface $finder Migration files finder
  136. */
  137. public function __construct(Connection $connection, OutputWriter $outputWriter = null, MigrationFinderInterface $finder = null)
  138. {
  139. $this->connection = $connection;
  140. if ($outputWriter === null) {
  141. $outputWriter = new OutputWriter();
  142. }
  143. $this->outputWriter = $outputWriter;
  144. if ($finder === null) {
  145. $finder = new RecursiveRegexFinder();
  146. }
  147. $this->migrationFinder = $finder;
  148. }
  149. /**
  150. * @return bool
  151. */
  152. public function areMigrationsOrganizedByYear()
  153. {
  154. return $this->migrationsAreOrganizedByYear;
  155. }
  156. /**
  157. * @return bool
  158. */
  159. public function areMigrationsOrganizedByYearAndMonth()
  160. {
  161. return $this->migrationsAreOrganizedByYearAndMonth;
  162. }
  163. /**
  164. * Validation that this instance has all the required properties configured
  165. *
  166. * @throws MigrationException
  167. */
  168. public function validate()
  169. {
  170. if (!$this->migrationsNamespace) {
  171. throw MigrationException::migrationsNamespaceRequired();
  172. }
  173. if (!$this->migrationsDirectory) {
  174. throw MigrationException::migrationsDirectoryRequired();
  175. }
  176. }
  177. /**
  178. * Set the name of this set of migrations
  179. *
  180. * @param string $name The name of this set of migrations
  181. */
  182. public function setName($name)
  183. {
  184. $this->name = $name;
  185. }
  186. /**
  187. * Returns the name of this set of migrations
  188. *
  189. * @return string $name The name of this set of migrations
  190. */
  191. public function getName()
  192. {
  193. return $this->name;
  194. }
  195. /**
  196. * Sets the output writer.
  197. *
  198. * @param OutputWriter $outputWriter
  199. */
  200. public function setOutputWriter(OutputWriter $outputWriter)
  201. {
  202. $this->outputWriter = $outputWriter;
  203. }
  204. /**
  205. * Returns the OutputWriter instance
  206. *
  207. * @return OutputWriter $outputWriter The OutputWriter instance
  208. */
  209. public function getOutputWriter()
  210. {
  211. return $this->outputWriter;
  212. }
  213. /**
  214. * Returns a timestamp version as a formatted date
  215. *
  216. * @param string $version
  217. *
  218. * @return string The formatted version
  219. * @deprecated
  220. */
  221. public function formatVersion($version)
  222. {
  223. return $this->getDateTime($version);
  224. }
  225. /**
  226. * Returns the datetime of a migration
  227. *
  228. * @param $version
  229. * @return string
  230. */
  231. public function getDateTime($version)
  232. {
  233. $datetime = str_replace('Version', '', $version);
  234. $datetime = \DateTime::createFromFormat('YmdHis', $datetime);
  235. if ($datetime === false) {
  236. return '';
  237. }
  238. return $datetime->format('Y-m-d H:i:s');
  239. }
  240. /**
  241. * Returns the Connection instance
  242. *
  243. * @return Connection $connection The Connection instance
  244. */
  245. public function getConnection()
  246. {
  247. return $this->connection;
  248. }
  249. /**
  250. * Set the migration table name
  251. *
  252. * @param string $tableName The migration table name
  253. */
  254. public function setMigrationsTableName($tableName)
  255. {
  256. $this->migrationsTableName = $tableName;
  257. }
  258. /**
  259. * Returns the migration table name
  260. *
  261. * @return string $migrationsTableName The migration table name
  262. */
  263. public function getMigrationsTableName()
  264. {
  265. return $this->migrationsTableName;
  266. }
  267. /**
  268. * Set the migration column name
  269. *
  270. * @param string $columnName The migration column name
  271. */
  272. public function setMigrationsColumnName($columnName)
  273. {
  274. $this->migrationsColumnName = $columnName;
  275. }
  276. /**
  277. * Returns the migration column name
  278. *
  279. * @return string $migrationsColumnName The migration column name
  280. */
  281. public function getMigrationsColumnName()
  282. {
  283. return $this->migrationsColumnName;
  284. }
  285. /**
  286. * Set the new migrations directory where new migration classes are generated
  287. *
  288. * @param string $migrationsDirectory The new migrations directory
  289. */
  290. public function setMigrationsDirectory($migrationsDirectory)
  291. {
  292. $this->migrationsDirectory = $migrationsDirectory;
  293. }
  294. /**
  295. * Returns the new migrations directory where new migration classes are generated
  296. *
  297. * @return string $migrationsDirectory The new migrations directory
  298. */
  299. public function getMigrationsDirectory()
  300. {
  301. return $this->migrationsDirectory;
  302. }
  303. /**
  304. * Set the migrations namespace
  305. *
  306. * @param string $migrationsNamespace The migrations namespace
  307. */
  308. public function setMigrationsNamespace($migrationsNamespace)
  309. {
  310. $this->migrationsNamespace = $migrationsNamespace;
  311. }
  312. /**
  313. * Returns the migrations namespace
  314. *
  315. * @return string $migrationsNamespace The migrations namespace
  316. */
  317. public function getMigrationsNamespace()
  318. {
  319. return $this->migrationsNamespace;
  320. }
  321. /**
  322. * Set the implementation of the migration finder.
  323. *
  324. * @param MigrationFinderInterface $finder The new migration finder
  325. * @throws MigrationException
  326. */
  327. public function setMigrationsFinder(MigrationFinderInterface $finder)
  328. {
  329. if (($this->migrationsAreOrganizedByYear || $this->migrationsAreOrganizedByYearAndMonth) &&
  330. !($finder instanceof MigrationDeepFinderInterface)) {
  331. throw MigrationException::configurationIncompatibleWithFinder(
  332. 'organize-migrations',
  333. $finder
  334. );
  335. }
  336. $this->migrationFinder = $finder;
  337. }
  338. /**
  339. * Register migrations from a given directory. Recursively finds all files
  340. * with the pattern VersionYYYYMMDDHHMMSS.php as the filename and registers
  341. * them as migrations.
  342. *
  343. * @param string $path The root directory to where some migration classes live.
  344. *
  345. * @return Version[] The array of migrations registered.
  346. */
  347. public function registerMigrationsFromDirectory($path)
  348. {
  349. $this->validate();
  350. return $this->registerMigrations($this->findMigrations($path));
  351. }
  352. /**
  353. * Register a single migration version to be executed by a AbstractMigration
  354. * class.
  355. *
  356. * @param string $version The version of the migration in the format YYYYMMDDHHMMSS.
  357. * @param string $class The migration class to execute for the version.
  358. *
  359. * @return Version
  360. *
  361. * @throws MigrationException
  362. */
  363. public function registerMigration($version, $class)
  364. {
  365. $this->ensureMigrationClassExists($class);
  366. $version = (string) $version;
  367. $class = (string) $class;
  368. if (isset($this->migrations[$version])) {
  369. throw MigrationException::duplicateMigrationVersion($version, get_class($this->migrations[$version]));
  370. }
  371. $version = new Version($this, $version, $class);
  372. $this->migrations[$version->getVersion()] = $version;
  373. ksort($this->migrations, SORT_STRING);
  374. return $version;
  375. }
  376. /**
  377. * Register an array of migrations. Each key of the array is the version and
  378. * the value is the migration class name.
  379. *
  380. *
  381. * @param array $migrations
  382. *
  383. * @return Version[]
  384. */
  385. public function registerMigrations(array $migrations)
  386. {
  387. $versions = [];
  388. foreach ($migrations as $version => $class) {
  389. $versions[] = $this->registerMigration($version, $class);
  390. }
  391. return $versions;
  392. }
  393. /**
  394. * Get the array of registered migration versions.
  395. *
  396. * @return Version[] $migrations
  397. */
  398. public function getMigrations()
  399. {
  400. return $this->migrations;
  401. }
  402. /**
  403. * Returns the Version instance for a given version in the format YYYYMMDDHHMMSS.
  404. *
  405. * @param string $version The version string in the format YYYYMMDDHHMMSS.
  406. *
  407. * @return Version
  408. *
  409. * @throws MigrationException Throws exception if migration version does not exist.
  410. */
  411. public function getVersion($version)
  412. {
  413. if (empty($this->migrations)) {
  414. $this->registerMigrationsFromDirectory($this->getMigrationsDirectory());
  415. }
  416. if (!isset($this->migrations[$version])) {
  417. throw MigrationException::unknownMigrationVersion($version);
  418. }
  419. return $this->migrations[$version];
  420. }
  421. /**
  422. * Check if a version exists.
  423. *
  424. * @param string $version
  425. *
  426. * @return boolean
  427. */
  428. public function hasVersion($version)
  429. {
  430. if (empty($this->migrations)) {
  431. $this->registerMigrationsFromDirectory($this->getMigrationsDirectory());
  432. }
  433. return isset($this->migrations[$version]);
  434. }
  435. /**
  436. * Check if a version has been migrated or not yet
  437. *
  438. * @param Version $version
  439. *
  440. * @return boolean
  441. */
  442. public function hasVersionMigrated(Version $version)
  443. {
  444. $this->connect();
  445. $this->createMigrationTable();
  446. $version = $this->connection->fetchColumn(
  447. "SELECT " . $this->migrationsColumnName . " FROM " . $this->migrationsTableName . " WHERE " . $this->migrationsColumnName . " = ?",
  448. [$version->getVersion()]
  449. );
  450. return $version !== false;
  451. }
  452. /**
  453. * Returns all migrated versions from the versions table, in an array.
  454. *
  455. * @return Version[]
  456. */
  457. public function getMigratedVersions()
  458. {
  459. $this->connect();
  460. $this->createMigrationTable();
  461. $ret = $this->connection->fetchAll("SELECT " . $this->migrationsColumnName . " FROM " . $this->migrationsTableName);
  462. return array_map('current', $ret);
  463. }
  464. /**
  465. * Returns an array of available migration version numbers.
  466. *
  467. * @return array
  468. */
  469. public function getAvailableVersions()
  470. {
  471. $availableVersions = [];
  472. if (empty($this->migrations)) {
  473. $this->registerMigrationsFromDirectory($this->getMigrationsDirectory());
  474. }
  475. foreach ($this->migrations as $migration) {
  476. $availableVersions[] = $migration->getVersion();
  477. }
  478. return $availableVersions;
  479. }
  480. /**
  481. * Returns the current migrated version from the versions table.
  482. *
  483. * @return string
  484. */
  485. public function getCurrentVersion()
  486. {
  487. $this->connect();
  488. $this->createMigrationTable();
  489. if (empty($this->migrations)) {
  490. $this->registerMigrationsFromDirectory($this->getMigrationsDirectory());
  491. }
  492. $where = null;
  493. if (!empty($this->migrations)) {
  494. $migratedVersions = [];
  495. foreach ($this->migrations as $migration) {
  496. $migratedVersions[] = sprintf("'%s'", $migration->getVersion());
  497. }
  498. $where = " WHERE " . $this->migrationsColumnName . " IN (" . implode(', ', $migratedVersions) . ")";
  499. }
  500. $sql = sprintf("SELECT %s FROM %s%s ORDER BY %s DESC",
  501. $this->migrationsColumnName, $this->migrationsTableName, $where, $this->migrationsColumnName
  502. );
  503. $sql = $this->connection->getDatabasePlatform()->modifyLimitQuery($sql, 1);
  504. $result = $this->connection->fetchColumn($sql);
  505. return $result !== false ? (string) $result : '0';
  506. }
  507. /**
  508. * Returns the version prior to the current version.
  509. *
  510. * @return string|null A version string, or null if the current version is
  511. * the first.
  512. */
  513. public function getPrevVersion()
  514. {
  515. return $this->getRelativeVersion($this->getCurrentVersion(), -1);
  516. }
  517. /**
  518. * Returns the version following the current version.
  519. *
  520. * @return string|null A version string, or null if the current version is
  521. * the latest.
  522. */
  523. public function getNextVersion()
  524. {
  525. return $this->getRelativeVersion($this->getCurrentVersion(), 1);
  526. }
  527. /**
  528. * Returns the version with the specified offset to the specified version.
  529. *
  530. * @return string|null A version string, or null if the specified version
  531. * is unknown or the specified delta is not within the
  532. * list of available versions.
  533. */
  534. public function getRelativeVersion($version, $delta)
  535. {
  536. if (empty($this->migrations)) {
  537. $this->registerMigrationsFromDirectory($this->getMigrationsDirectory());
  538. }
  539. $versions = array_map('strval', array_keys($this->migrations));
  540. array_unshift($versions, '0');
  541. $offset = array_search((string)$version, $versions);
  542. if ($offset === false || !isset($versions[$offset + $delta])) {
  543. // Unknown version or delta out of bounds.
  544. return null;
  545. }
  546. return $versions[$offset + $delta];
  547. }
  548. /**
  549. * Returns the version number from an alias.
  550. *
  551. * Supported aliases are:
  552. * - first: The very first version before any migrations have been run.
  553. * - current: The current version.
  554. * - prev: The version prior to the current version.
  555. * - next: The version following the current version.
  556. * - latest: The latest available version.
  557. *
  558. * If an existing version number is specified, it is returned verbatimly.
  559. *
  560. * @return string|null A version number, or null if the specified alias
  561. * does not map to an existing version, e.g. if "next"
  562. * is passed but the current version is already the
  563. * latest.
  564. */
  565. public function resolveVersionAlias($alias)
  566. {
  567. if ($this->hasVersion($alias)) {
  568. return $alias;
  569. }
  570. switch ($alias) {
  571. case 'first':
  572. return '0';
  573. case 'current':
  574. return $this->getCurrentVersion();
  575. case 'prev':
  576. return $this->getPrevVersion();
  577. case 'next':
  578. return $this->getNextVersion();
  579. case 'latest':
  580. return $this->getLatestVersion();
  581. default:
  582. return null;
  583. }
  584. }
  585. /**
  586. * Returns the total number of executed migration versions
  587. *
  588. * @return integer
  589. */
  590. public function getNumberOfExecutedMigrations()
  591. {
  592. $this->connect();
  593. $this->createMigrationTable();
  594. $result = $this->connection->fetchColumn("SELECT COUNT(" . $this->migrationsColumnName . ") FROM " . $this->migrationsTableName);
  595. return $result !== false ? $result : 0;
  596. }
  597. /**
  598. * Returns the total number of available migration versions
  599. *
  600. * @return integer
  601. */
  602. public function getNumberOfAvailableMigrations()
  603. {
  604. if (empty($this->migrations)) {
  605. $this->registerMigrationsFromDirectory($this->getMigrationsDirectory());
  606. }
  607. return count($this->migrations);
  608. }
  609. /**
  610. * Returns the latest available migration version.
  611. *
  612. * @return string The version string in the format YYYYMMDDHHMMSS.
  613. */
  614. public function getLatestVersion()
  615. {
  616. if (empty($this->migrations)) {
  617. $this->registerMigrationsFromDirectory($this->getMigrationsDirectory());
  618. }
  619. $versions = array_keys($this->migrations);
  620. $latest = end($versions);
  621. return $latest !== false ? (string) $latest : '0';
  622. }
  623. /**
  624. * Create the migration table to track migrations with.
  625. *
  626. * @return boolean Whether or not the table was created.
  627. */
  628. public function createMigrationTable()
  629. {
  630. $this->validate();
  631. if ($this->migrationTableCreated) {
  632. return false;
  633. }
  634. $this->connect();
  635. if ($this->connection->getSchemaManager()->tablesExist([$this->migrationsTableName])) {
  636. $this->migrationTableCreated = true;
  637. return false;
  638. }
  639. $columns = [
  640. $this->migrationsColumnName => new Column($this->migrationsColumnName, Type::getType('string'), ['length' => 255]),
  641. ];
  642. $table = new Table($this->migrationsTableName, $columns);
  643. $table->setPrimaryKey([$this->migrationsColumnName]);
  644. $this->connection->getSchemaManager()->createTable($table);
  645. $this->migrationTableCreated = true;
  646. return true;
  647. }
  648. /**
  649. * Returns the array of migrations to executed based on the given direction
  650. * and target version number.
  651. *
  652. * @param string $direction The direction we are migrating.
  653. * @param string $to The version to migrate to.
  654. *
  655. * @return Version[] $migrations The array of migrations we can execute.
  656. */
  657. public function getMigrationsToExecute($direction, $to)
  658. {
  659. if (empty($this->migrations)) {
  660. $this->registerMigrationsFromDirectory($this->getMigrationsDirectory());
  661. }
  662. if ($direction === Version::DIRECTION_DOWN) {
  663. if (count($this->migrations)) {
  664. $allVersions = array_reverse(array_keys($this->migrations));
  665. $classes = array_reverse(array_values($this->migrations));
  666. $allVersions = array_combine($allVersions, $classes);
  667. } else {
  668. $allVersions = [];
  669. }
  670. } else {
  671. $allVersions = $this->migrations;
  672. }
  673. $versions = [];
  674. $migrated = $this->getMigratedVersions();
  675. foreach ($allVersions as $version) {
  676. if ($this->shouldExecuteMigration($direction, $version, $to, $migrated)) {
  677. $versions[$version->getVersion()] = $version;
  678. }
  679. }
  680. return $versions;
  681. }
  682. /**
  683. * Find all the migrations in a given directory.
  684. *
  685. * @param string $path the directory to search.
  686. * @return array
  687. */
  688. protected function findMigrations($path)
  689. {
  690. return $this->migrationFinder->findMigrations($path, $this->getMigrationsNamespace());
  691. }
  692. /**
  693. * @param bool $migrationsAreOrganizedByYear
  694. * @throws MigrationException
  695. */
  696. public function setMigrationsAreOrganizedByYear($migrationsAreOrganizedByYear = true)
  697. {
  698. $this->ensureOrganizeMigrationsIsCompatibleWithFinder();
  699. $this->migrationsAreOrganizedByYear = $migrationsAreOrganizedByYear;
  700. }
  701. /**
  702. * @param bool $migrationsAreOrganizedByYearAndMonth
  703. * @throws MigrationException
  704. */
  705. public function setMigrationsAreOrganizedByYearAndMonth($migrationsAreOrganizedByYearAndMonth = true)
  706. {
  707. $this->ensureOrganizeMigrationsIsCompatibleWithFinder();
  708. $this->migrationsAreOrganizedByYear = $migrationsAreOrganizedByYearAndMonth;
  709. $this->migrationsAreOrganizedByYearAndMonth = $migrationsAreOrganizedByYearAndMonth;
  710. }
  711. /**
  712. * Generate a new migration version. A version is (usually) a datetime string.
  713. *
  714. * @param DateTimeInterface|null $now Defaults to the current time in UTC
  715. * @return string The newly generated version
  716. */
  717. public function generateVersionNumber(\DateTimeInterface $now=null)
  718. {
  719. $now = $now ?: new \DateTime('now', new \DateTimeZone('UTC'));
  720. return $now->format(self::VERSION_FORMAT);
  721. }
  722. /**
  723. * Explicitely opens the database connection. This is done to play nice
  724. * with DBAL's MasterSlaveConnection. Which, in some cases, connects to a
  725. * follower when fetching the executed migrations. If a follower is lagging
  726. * significantly behind that means the migrations system may see unexecuted
  727. * migrations that were actually executed earlier.
  728. *
  729. * @return bool The same value returned from the `connect` method
  730. */
  731. protected function connect()
  732. {
  733. if ($this->connection instanceof MasterSlaveConnection) {
  734. return $this->connection->connect('master');
  735. }
  736. return $this->connection->connect();
  737. }
  738. /**
  739. * @throws MigrationException
  740. */
  741. private function ensureOrganizeMigrationsIsCompatibleWithFinder()
  742. {
  743. if (!($this->migrationFinder instanceof MigrationDeepFinderInterface)) {
  744. throw MigrationException::configurationIncompatibleWithFinder(
  745. 'organize-migrations',
  746. $this->migrationFinder
  747. );
  748. }
  749. }
  750. /**
  751. * Check if we should execute a migration for a given direction and target
  752. * migration version.
  753. *
  754. * @param string $direction The direction we are migrating.
  755. * @param Version $version The Version instance to check.
  756. * @param string $to The version we are migrating to.
  757. * @param array $migrated Migrated versions array.
  758. *
  759. * @return boolean
  760. */
  761. private function shouldExecuteMigration($direction, Version $version, $to, $migrated)
  762. {
  763. if ($direction === Version::DIRECTION_DOWN) {
  764. if (!in_array($version->getVersion(), $migrated)) {
  765. return false;
  766. }
  767. return $version->getVersion() > $to;
  768. }
  769. if ($direction === Version::DIRECTION_UP) {
  770. if (in_array($version->getVersion(), $migrated)) {
  771. return false;
  772. }
  773. return $version->getVersion() <= $to;
  774. }
  775. }
  776. /**
  777. * @param string $class
  778. */
  779. private function ensureMigrationClassExists($class)
  780. {
  781. if ( ! class_exists($class)) {
  782. throw MigrationException::migrationClassNotFound($class, $this->getMigrationsNamespace());
  783. }
  784. }
  785. }