Browse Source

Rename SchemaManager to SchemaLoader. Clean up static functions and config.

Corey Taylor 4 years ago
parent
commit
ab5a8ea7d9

+ 109 - 0
src/TestSuite/Fixture/SchemaLoader.php

@@ -0,0 +1,109 @@
+<?php
+declare(strict_types=1);
+
+/**
+ * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
+ * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
+ *
+ * Licensed under The MIT License
+ * For full copyright and license information, please see the LICENSE.txt
+ * Redistributions of files must retain the above copyright notice
+ *
+ * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
+ * @since         4.3.0
+ * @license       https://opensource.org/licenses/mit-license.php MIT License
+ */
+namespace Cake\TestSuite\Fixture;
+
+use Cake\Console\ConsoleIo;
+use Cake\Core\InstanceConfigTrait;
+use Cake\Datasource\ConnectionManager;
+use InvalidArgumentException;
+
+/**
+ * Create test database schema from one or more SQL dump files.
+ *
+ * This class can be useful to create test database schema when
+ * your schema is managed by tools external to your CakePHP
+ * application.
+ *
+ * It is not well suited for applications/plugins that need to
+ * support multiple database platforms. You should use migrations
+ * for that instead.
+ */
+class SchemaLoader
+{
+    use InstanceConfigTrait;
+
+    /**
+     * @var \Cake\Console\ConsoleIo
+     */
+    protected $io;
+
+    /**
+     * @var array
+     */
+    protected $_defaultConfig = [
+        'dropTables' => true,
+        'outputLevel' => ConsoleIo::NORMAL,
+    ];
+
+    /**
+     * Constructor.
+     *
+     * @param array<string, mixed> $config Config settings
+     */
+    public function __construct(array $config = [])
+    {
+        $this->setConfig($config);
+
+        $this->io = new ConsoleIo();
+        $this->io->level($this->getConfig('outputLevel'));
+    }
+
+    /**
+     * Import schema from a file, or an array of files.
+     *
+     * @param array<string>|string $files Schema files to load
+     * @param string $connectionName Connection name
+     * @param bool $dropTables Drop all tables prior to loading schema files
+     * @param bool $truncateTables Truncate all tables after loading schema files
+     * @return void
+     */
+    public function loadFiles(
+        $files,
+        string $connectionName,
+        bool $dropTables = true,
+        bool $truncateTables = true
+    ): void {
+        $files = (array)$files;
+
+        // Don't create schema if we are in a phpunit separate process test method.
+        if (empty($files) || isset($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
+            return;
+        }
+
+        $cleaner = new SchemaCleaner($this->io);
+        if ($dropTables) {
+            $cleaner->dropTables($connectionName);
+        }
+
+        $connection = ConnectionManager::get($connectionName);
+        foreach ($files as $file) {
+            if (!file_exists($file)) {
+                throw new InvalidArgumentException("Unable to load schema file `$file`.");
+            }
+
+            $sql = file_get_contents($file);
+            if ($sql === false) {
+                throw new InvalidArgumentException("Unable to load schema file `$file`.");
+            }
+
+            $connection->execute($sql)->closeCursor();
+        }
+
+        if ($truncateTables) {
+            $cleaner->truncateTables($connectionName);
+        }
+    }
+}

+ 0 - 105
src/TestSuite/Fixture/SchemaManager.php

@@ -1,105 +0,0 @@
-<?php
-declare(strict_types=1);
-
-/**
- * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice
- *
- * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- * @since         4.3.0
- * @license       https://opensource.org/licenses/mit-license.php MIT License
- */
-namespace Cake\TestSuite\Fixture;
-
-use Cake\Console\ConsoleIo;
-use Cake\Datasource\ConnectionManager;
-
-/**
- * Create test database schema from one or more SQL dump files.
- *
- * This class can be useful to create test database schema when
- * your schema is managed by tools external to your CakePHP
- * application.
- *
- * It is not well suited for applications/plugins that need to
- * support multiple database platforms. You should use migrations
- * for that instead.
- */
-class SchemaManager
-{
-    /**
-     * @var \Cake\Console\ConsoleIo
-     */
-    protected $io;
-
-    /**
-     * SchemaManager constructor.
-     *
-     * @param bool|null $verbose Output CLI messages.
-     */
-    final public function __construct(?bool $verbose = false)
-    {
-        $this->io = new ConsoleIo();
-        $this->io->level($verbose ? ConsoleIo::NORMAL : ConsoleIo::QUIET);
-    }
-
-    /**
-     * Import the schema from a file, or an array of files.
-     *
-     * This function will drop all tables in the database and then
-     * load the provided schema file(s).
-     *
-     * @param string $connectionName Connection
-     * @param array<string>|string $file File to dump
-     * @param bool|null $verbose Set to true to display messages
-     * @param bool|null $enableDropping Will drop all tables prior to creating the schema (true by default)
-     * @return void
-     * @throws \Exception if the truncation failed
-     * @throws \RuntimeException if the file could not be processed
-     */
-    public static function create(
-        string $connectionName,
-        $file,
-        ?bool $verbose = false,
-        ?bool $enableDropping = true
-    ): void {
-        $files = (array)$file;
-
-        // Don't create schema if we are in a phpunit separate process test method.
-        if (empty($files) || isset($GLOBALS['__PHPUNIT_BOOTSTRAP'])) {
-            return;
-        }
-
-        $stmts = [];
-        foreach ($files as $file) {
-            if (!file_exists($file)) {
-                throw new \RuntimeException('The file ' . $file . ' could not found.');
-            }
-
-            $stmts[] = $sql = file_get_contents($file);
-            if ($sql === false) {
-                throw new \RuntimeException('The file ' . $file . ' could not read.');
-            }
-        }
-
-        $migrator = new static($verbose);
-        $schemaCleaner = new SchemaCleaner($migrator->io);
-
-        if ($enableDropping) {
-            $schemaCleaner->dropTables($connectionName);
-        }
-
-        foreach ($stmts as $stmt) {
-            ConnectionManager::get($connectionName)->execute($stmt);
-        }
-        $migrator->io->success(
-            'Dump of schema in file ' . $file . ' for connection ' . $connectionName . ' successful.'
-        );
-
-        $schemaCleaner->truncateTables($connectionName);
-    }
-}

+ 82 - 0
tests/TestCase/TestSuite/Fixture/SchemaLoaderTest.php

@@ -0,0 +1,82 @@
+<?php
+declare(strict_types=1);
+
+/**
+ * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
+ * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
+ *
+ * Licensed under The MIT License
+ * For full copyright and license information, please see the LICENSE.txt
+ * Redistributions of files must retain the above copyright notice
+ *
+ * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
+ * @since         4.3.0
+ * @license       https://opensource.org/licenses/mit-license.php MIT License
+ */
+namespace Cake\Test\TestCase\TestSuite\Fixture;
+
+use Cake\Database\Schema\TableSchema;
+use Cake\Datasource\ConnectionManager;
+use Cake\TestSuite\Fixture\SchemaCleaner;
+use Cake\TestSuite\Fixture\SchemaLoader;
+use Cake\TestSuite\TestCase;
+use InvalidArgumentException;
+
+class SchemaLoaderTest extends TestCase
+{
+    /**
+     * @var bool|null
+     */
+    protected $restore;
+
+    public function setUp(): void
+    {
+        parent::setUp();
+        $this->restore = $GLOBALS['__PHPUNIT_BOOTSTRAP'];
+        unset($GLOBALS['__PHPUNIT_BOOTSTRAP']);
+    }
+
+    public function tearDown(): void
+    {
+        parent::tearDown();
+        $GLOBALS['__PHPUNIT_BOOTSTRAP'] = $this->restore;
+        (new SchemaCleaner())->dropTables('test', ['schema_loader_test_one', 'schema_loader_test_two']);
+    }
+
+    public function testLoadingFiles(): void
+    {
+        $connection = ConnectionManager::get('test');
+
+        $schemaFiles[] = $this->createSchemaFile('schema_loader_test_one');
+        $schemaFiles[] = $this->createSchemaFile('schema_loader_test_two');
+
+        (new SchemaLoader())->loadFiles($schemaFiles, 'test', false, false);
+
+        $connection = ConnectionManager::get('test');
+        $tables = $connection->getSchemaCollection()->listTables();
+        $this->assertContains('schema_loader_test_one', $tables);
+        $this->assertContains('schema_loader_test_two', $tables);
+    }
+
+    public function testLoadMissingFile(): void
+    {
+        $this->expectException(InvalidArgumentException::class);
+        (new SchemaLoader())->loadFiles('missing_schema_file.sql', 'test', false, false);
+    }
+
+    protected function createSchemaFile(string $tableName): string
+    {
+        $connection = ConnectionManager::get('test');
+
+        $schema = new TableSchema($tableName);
+        $schema
+            ->addColumn('id', 'integer')
+            ->addColumn('name', 'string');
+
+        $query = $schema->createSql($connection)[0];
+        $tmpFile = tempnam(sys_get_temp_dir(), 'SchemaLoaderTest');
+        file_put_contents($tmpFile, $query);
+
+        return $tmpFile;
+    }
+}

+ 0 - 127
tests/TestCase/TestSuite/Fixture/SchemaManagerTest.php

@@ -1,127 +0,0 @@
-<?php
-declare(strict_types=1);
-
-/**
- * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
- * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- *
- * Licensed under The MIT License
- * For full copyright and license information, please see the LICENSE.txt
- * Redistributions of files must retain the above copyright notice
- *
- * @copyright     Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
- * @since         4.3.0
- * @license       https://opensource.org/licenses/mit-license.php MIT License
- */
-namespace Cake\Test\TestCase\TestSuite\Fixture;
-
-use Cake\Database\Schema\TableSchema;
-use Cake\Datasource\ConnectionManager;
-use Cake\TestSuite\Fixture\SchemaCleaner;
-use Cake\TestSuite\Fixture\SchemaManager;
-use Cake\TestSuite\TestCase;
-use RuntimeException;
-
-class SchemaManagerTest extends TestCase
-{
-    /**
-     * @var bool|null
-     */
-    protected $restore;
-
-    public function setUp(): void
-    {
-        parent::setUp();
-        $this->restore = $GLOBALS['__PHPUNIT_BOOTSTRAP'];
-        unset($GLOBALS['__PHPUNIT_BOOTSTRAP']);
-    }
-
-    public function tearDown(): void
-    {
-        parent::tearDown();
-        $GLOBALS['__PHPUNIT_BOOTSTRAP'] = $this->restore;
-    }
-
-    public function testCreateFromOneFile(): void
-    {
-        $connection = ConnectionManager::get('test');
-
-        $tableName = 'test_table_' . rand();
-        (new SchemaCleaner())->dropTables('test', [$tableName]);
-
-        $file = $this->createSchemaFile($tableName);
-
-        SchemaManager::create('test', $file, false, false);
-
-        // Assert that the test table was created
-        $this->assertSame(
-            0,
-            $connection->newQuery()->select('id')->from($tableName)->execute()->count()
-        );
-
-        // Cleanup
-        (new SchemaCleaner())->dropTables('test', [$tableName]);
-    }
-
-    public function testCreateFromMultipleFiles(): void
-    {
-        $connection = ConnectionManager::get('test');
-        $tables = [
-            'test_table_' . rand(),
-            'test_table_' . rand(),
-            'test_table_' . rand(),
-        ];
-
-        (new SchemaCleaner())->dropTables('test', $tables);
-
-        $files = [];
-        foreach ($tables as $table) {
-            $files[] = $this->createSchemaFile($table);
-        }
-
-        SchemaManager::create('test', $files, false, false);
-
-        // Assert that all test tables were created
-        foreach ($tables as $table) {
-            $this->assertSame(
-                0,
-                $connection->newQuery()->select('id')->from($table)->execute()->count()
-            );
-        }
-
-        // Cleanup
-        (new SchemaCleaner())->dropTables('test', $tables);
-    }
-
-    public function testCreateFromNonExistentFile(): void
-    {
-        $this->expectException(RuntimeException::class);
-        SchemaManager::create('test', 'foo');
-    }
-
-    public function testCreateFromCorruptedFile(): void
-    {
-        $query = 'This is no valid SQL';
-        $tmpFile = tempnam(sys_get_temp_dir(), 'SchemaManagerTest');
-        file_put_contents($tmpFile, $query);
-
-        $this->expectException(RuntimeException::class);
-        SchemaManager::create('test', $tmpFile, false, false);
-    }
-
-    private function createSchemaFile(string $tableName): string
-    {
-        $connection = ConnectionManager::get('test');
-
-        $schema = new TableSchema($tableName);
-        $schema
-            ->addColumn('id', 'integer')
-            ->addColumn('name', 'string');
-
-        $query = $schema->createSql($connection)[0];
-        $tmpFile = tempnam(sys_get_temp_dir(), 'SchemaManagerTest');
-        file_put_contents($tmpFile, $query);
-
-        return $tmpFile;
-    }
-}