Passed
Pull Request — master (#65)
by Arman
03:48
created

TableFactory   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 72
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 7 2
A checkTableExists() 0 9 2
A rename() 0 4 1
A drop() 0 4 1
A get() 0 7 2
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.7.0
13
 */
14
15
namespace Quantum\Factory;
16
17
use Quantum\Exceptions\MigrationException;
18
use Quantum\Libraries\Database\Schema\Table;
19
use Quantum\Libraries\Database\Database;
20
21
/**
22
 * Class TableFactory
23
 * @package Quantum\Factory
24
 */
25
class TableFactory
26
{
27
28
    /**
29
     * Creates new table
30
     * @param string $name
31
     * @return Table
32
     * @throws Quantum\Exceptions\MigrationException
33
     */
34
    public function create(string $name): Table
35
    {
36
        if ($this->checkTableExists($name)) {
37
            throw MigrationException::tableAlreadyExists($name);
38
        }
39
40
        return (new Table($name))->setAction(Table::CREATE);
41
    }
42
43
    /**
44
     * Get the table
45
     * @param string $name
46
     * @param int $action
47
     * @return Table
48
     * @throws Quantum\Exceptions\MigrationException
49
     */
50
    public function get(string $name, int $action = Table::ALTER): Table
51
    {
52
        if (!$this->checkTableExists($name)) {
53
            throw MigrationException::tableDoesnotExists($name);
54
        }
55
56
        return (new Table($name))->setAction($action);
57
    }
58
59
    /**
60
     * Renames the table
61
     * @param string $oldName
62
     * @param string $newName
63
     * @return bool
64
     */
65
    public function rename(string $oldName, string $newName): bool
66
    {
67
        $this->get($oldName)->setAction(Table::RENAME, ['newName' => $newName]);
68
        return true;
69
    }
70
71
    /**
72
     * Drops the table
73
     * @param string $name
74
     * @return bool
75
     */
76
    public function drop(string $name): bool
77
    {
78
        $this->get($name)->setAction(Table::DROP);
79
        return true;
80
    }
81
   
82
    /**
83
     * Checks if the DB table exists
84
     * @param string $name
85
     * @return bool
86
     * @throws \Quantum\Exceptions\DatabaseException
87
     */
88
    public function checkTableExists(string $name): bool
89
    {
90
        try {
91
            Database::query('SELECT 1 FROM ' . $name);
92
        } catch (\PDOException $e) {
93
            return false;
94
        }
95
96
        return true;
97
    }
98
99
}
100