AbstractHelper::createTableLike()   B
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 37
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
c 0
b 0
f 0
rs 8.5806
cc 4
eloc 21
nc 3
nop 2
1
<?php
2
3
namespace Graze\DataDb\Helper;
4
5
use Graze\DataDb\Dialect\DialectInterface;
6
use Graze\DataDb\TableNodeInterface;
7
use Graze\DataFile\Helper\OptionalLoggerTrait;
8
use InvalidArgumentException;
9
use Psr\Log\LoggerAwareInterface;
10
use Psr\Log\LogLevel;
11
12
abstract class AbstractHelper implements HelperInterface, LoggerAwareInterface
13
{
14
    use OptionalLoggerTrait;
15
16
    /**
17
     * @var DialectInterface
18
     */
19
    protected $dialect;
20
21
    /**
22
     * @param TableNodeInterface $first
23
     * @param TableNodeInterface $second
24
     */
25
    private function assertSameAdapter(TableNodeInterface $first, TableNodeInterface $second)
26
    {
27
        if ($first->getAdapter() !== $second->getAdapter()) {
28
            throw new InvalidArgumentException(sprintf(
29
                "The adapter is different for: %s and %s",
30
                $first->getFullName(),
31
                $second->getFullName()
32
            ));
33
        }
34
    }
35
36
    /**
37
     * @param TableNodeInterface $newTable
38
     * @param TableNodeInterface $oldTable
39
     *
40
     * @return bool
41
     */
42
    public function createTableLike(TableNodeInterface $newTable, TableNodeInterface $oldTable)
43
    {
44
        $this->assertSameAdapter($newTable, $oldTable);
45
46
        $this->log(LogLevel::INFO, "Creating Table {new} like {old}", [
47
            'new' => $newTable->getFullName(),
48
            'old' => $oldTable->getFullName(),
49
        ]);
50
51
        $db = $newTable->getAdapter();
52
        list ($sql, $params) = $this->dialect->getCreateTableLike($oldTable, $newTable);
53
        $db->query($sql, $params);
54
55
        if (count($newTable->getColumns()) > 0) {
56
            $original = array_keys($this->describeTable($newTable));
57
58
            if (count($original) > count($newTable->getColumns())) {
59
                $diff = array_diff($original, $newTable->getColumns());
60
61
                $this->log(
62
                    LogLevel::INFO,
63
                    "Table Definition is different to original table, Dropping columns: {columns} from {table}",
64
                    [
65
                        'columns' => implode(',', $diff),
66
                        'table'   => $newTable->getFullName(),
67
                    ]
68
                );
69
70
                foreach ($diff as $column) {
71
                    list ($sql, $params) = $this->dialect->getDropColumn($newTable, $column);
72
                    $db->query(trim($sql), $params);
73
                }
74
            }
75
        }
76
77
        return true;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return true; (boolean) is incompatible with the return type declared by the interface Graze\DataDb\Helper\Help...erface::createTableLike of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
78
    }
79
80
    /**
81
     * @param TableNodeInterface $table
82
     * @param array              $columns [[:column, :type, :nullable, ::primary, :index]]
83
     *
84
     * @return bool
85
     */
86
    abstract public function createTable(TableNodeInterface $table, array $columns);
87
88
    /**
89
     * @param TableNodeInterface $table
90
     *
91
     * @return array [:column => [:schema, :table, :column, :type, :nullable, :primary, :index]]
92
     */
93
    abstract public function describeTable(TableNodeInterface $table);
94
95
    /**
96
     * Produce the create syntax for a table
97
     *
98
     * @param TableNodeInterface $table
99
     *
100
     * @return string
101
     */
102
    abstract public function getCreateSyntax(TableNodeInterface $table);
103
104
    /**
105
     * @param TableNodeInterface $table
106
     *
107
     * @return bool
108
     */
109
    public function doesTableExist(TableNodeInterface $table)
110
    {
111
        $db = $table->getAdapter();
112
        list($sql, $params) = $this->dialect->getDoesTableExist($table);
113
        $tableName = $db->fetchOne(trim($sql), $params);
114
115
        return $tableName == $table->getTable();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $tableName == $table->getTable(); (boolean) is incompatible with the return type declared by the interface Graze\DataDb\Helper\Help...terface::doesTableExist of type string.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
116
    }
117
118
    /**
119
     * Delete from $source table by joining to $join table
120
     *
121
     * @param TableNodeInterface $source
122
     * @param TableNodeInterface $join
123
     * @param string             $on
124
     * @param string             $where
125
     *
126
     * @return mixed
127
     */
128
    public function deleteTableJoin(
129
        TableNodeInterface $source,
130
        TableNodeInterface $join,
131
        $on,
132
        $where = null
133
    ) {
134
        $this->assertSameAdapter($source, $join);
135
136
        $this->log(LogLevel::INFO, "Deleting entries from table {table} with a join to {join}", [
137
            'table' => $source->getFullName(),
138
            'join'  => $join->getFullName(),
139
        ]);
140
141
        $db = $source->getAdapter();
142
143
        if ($source->getSoftDeleted()) {
144
            $this->log(LogLevel::INFO, "Deletion table {table} uses soft deleted, updating", [
145
                'table' => $source->getFullName(),
146
            ]);
147
148
            list($sql, $params) = $this->dialect->getDeleteTableJoinSoftDelete($source, $join, $on, $where);
149
        } else {
150
            list($sql, $params) = $this->dialect->getDeleteTableJoin($source, $join, $on, $where);
151
        }
152
153
        return $db->query(trim($sql), $params);
154
    }
155
156
    /**
157
     * Delete from a table with a where configuration
158
     *
159
     * @param TableNodeInterface $table
160
     * @param string|null        $where
161
     *
162
     * @return mixed
163
     */
164
    public function deleteFromTable(TableNodeInterface $table, $where = null)
165
    {
166
        $this->log(LogLevel::INFO, "Deleting entries from table {table}", [
167
            'table' => $table->getFullName(),
168
        ]);
169
170
        if ($table->getSoftDeleted()) {
171
            $this->log(LogLevel::INFO, "Deletion table {table} uses soft deleted, updating", [
172
                'table' => $table->getFullName(),
173
            ]);
174
175
            list ($sql, $params) = $this->dialect->getDeleteFromTableSoftDelete($table, $where);
176
        } else {
177
            list ($sql, $params) = $this->dialect->getDeleteFromTable($table, $where);
178
        }
179
180
        $db = $table->getAdapter();
181
        return $db->query(trim($sql), $params);
182
    }
183
184
    /**
185
     * Copy the contents of a table into another  table
186
     *
187
     * @param TableNodeInterface $from
188
     * @param TableNodeInterface $to
189
     *
190
     * @return mixed
191
     */
192
    public function copyTable(TableNodeInterface $from, TableNodeInterface $to)
193
    {
194
        $this->assertSameAdapter($from, $to);
195
196
        $this->log(LogLevel::INFO, "Copying the contents of table {from} to {to}", [
197
            'from' => $from->getFullName(),
198
            'to'   => $to->getFullName(),
199
        ]);
200
201
        list ($sql, $params) = $this->dialect->getCopyTable($from, $to);
202
203
        $db = $to->getAdapter();
204
        return $db->query(trim($sql), $params);
205
    }
206
}
207