Completed
Branch feature/pre-split (67216b)
by Anton
03:28
created

RenameTable::execute()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
c 0
b 0
f 0
cc 3
eloc 11
nc 3
nop 1
rs 9.4285
1
<?php
2
/**
3
 * Spiral Framework.
4
 *
5
 * @license   MIT
6
 * @author    Anton Titov (Wolfy-J)
7
 */
8
namespace Spiral\Migrations\Operations\Table;
9
10
use Spiral\Database\Entities\AbstractHandler;
11
use Spiral\Migrations\CapsuleInterface;
12
use Spiral\Migrations\Exceptions\Operations\TableException;
13
use Spiral\Migrations\Operations\TableOperation;
14
15
class RenameTable extends TableOperation
16
{
17
    /**
18
     * @var string
19
     */
20
    private $newName = '';
21
22
    /**
23
     * @param string|null $database
24
     * @param string      $table
25
     * @param string      $newName
26
     */
27
    public function __construct($database, string $table, string $newName)
28
    {
29
        parent::__construct($database, $table);
30
        $this->newName = $newName;
31
    }
32
33
    /**
34
     * {@inheritdoc}
35
     */
36
    public function execute(CapsuleInterface $capsule)
37
    {
38
        $schema = $capsule->getSchema($this->getTable(), $this->getDatabase());
39
        $database = $this->database ?? '[default]';
40
41
        if (!$schema->exists()) {
42
            throw new TableException(
43
                "Unable to rename table '{$database}'.'{$this->getTable()}', table does not exists"
44
            );
45
        }
46
47
        if ($capsule->getDatabase($this->getDatabase())->hasTable($this->newName)) {
48
            throw new TableException(
49
                "Unable to rename table '{$database}'.'{$this->getTable()}', table '{$this->newName}' already exists"
50
            );
51
        }
52
53
        $schema->setName($this->newName);
54
        $schema->save(AbstractHandler::DO_ALL);
55
    }
56
}