MysqlHelper::isValidExportFormat()   B
last analyzed

Complexity

Conditions 10
Paths 10

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
c 0
b 0
f 0
rs 7.2765
cc 10
eloc 11
nc 10
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Graze\DataDb\Helper;
4
5
use Graze\DataDb\Dialect\DialectInterface;
6
use Graze\DataDb\Dialect\MysqlDialect;
7
use Graze\DataDb\TableNodeInterface;
8
use Graze\DataFile\Format\CsvFormat;
9
use Graze\DataFile\Format\CsvFormatInterface;
10
use Graze\DataFile\Format\FormatInterface;
11
use Psr\Log\LogLevel;
12
13
class MysqlHelper extends AbstractHelper
14
{
15
16
    /**
17
     * MysqlHelper constructor.
18
     *
19
     * @param DialectInterface|null $dialect
20
     */
21
    public function __construct(DialectInterface $dialect = null)
22
    {
23
        $this->dialect = $dialect ?: new MysqlDialect();
24
    }
25
26
    /**
27
     * @param TableNodeInterface $table
28
     * @param array              $columns [[:column, :type, :nullable, ::primary, :index]]
29
     *
30
     * @return bool
31
     */
32 View Code Duplication
    public function createTable(TableNodeInterface $table, array $columns)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
33
    {
34
        $this->log(LogLevel::DEBUG, "Creating Table {table} with columns: {columns}", [
35
            'table'   => $table->getFullName(),
36
            'columns' => implode(',', array_keys($columns)),
37
        ]);
38
39
        $columnStrings = [];
40
        $primary = [];
41
        $indexes = [];
42
43
        foreach ($columns as $column) {
44
            $columnStrings[] = $this->dialect->getColumnDefinition($column);
45
            if ($column['primary']) {
46
                $primary[] = $this->dialect->getPrimaryKeyDefinition($column);
47
            } elseif ($column['index']) {
48
                $indexes[] = $this->dialect->getIndexDefinition($column);
49
            }
50
        }
51
52
        list($sql, $params) = $this->dialect->getCreateTable($table, $columnStrings, $primary, $indexes);
53
        $db = $table->getAdapter();
54
        $db->query(trim($sql), $params);
55
56
        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\HelperInterface::createTable 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...
57
    }
58
59
    /**
60
     * @param TableNodeInterface $table
61
     *
62
     * @return array [:column => [:schema, :table, :column, :type, :nullable, :primary, :index]]
63
     */
64
    public function describeTable(TableNodeInterface $table)
65
    {
66
        list ($sql, $params) = $this->dialect->getDescribeTable($table);
67
68
        $db = $table->getAdapter();
69
        $description = $db->fetchAll(trim($sql), $params);
70
71
        $output = [];
72
73
        foreach ($description as $row) {
74
            $output[$row['Field']] = [
75
                'schema'   => $table->getSchema(),
76
                'table'    => $table->getTable(),
77
                'column'   => $row['Field'],
78
                'type'     => $row['Type'],
79
                'nullable' => (bool) ($row['Null'] == 'YES'),
80
                'primary'  => (bool) (strtoupper($row['Key']) == 'PRI'),
81
                'index'    => (bool) ($row['Key'] != ''),
82
            ];
83
        }
84
85
        return $output;
86
    }
87
88
    /**
89
     * Produce the create syntax for a table
90
     *
91
     * @param TableNodeInterface $table
92
     *
93
     * @return string
94
     */
95
    public function getCreateSyntax(TableNodeInterface $table)
96
    {
97
        list ($sql, $params) = $this->dialect->getCreateSyntax($table);
98
99
        $db = $table->getAdapter();
100
        $result = $db->fetchRow(trim($sql), $params);
101
102
        if ($result) {
103
            return $result['Create Table'];
104
        } else {
105
            return null;
106
        }
107
    }
108
109
    /**
110
     * @return FormatInterface
111
     */
112 View Code Duplication
    public function getDefaultExportFormat()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
113
    {
114
        return new CsvFormat([
115
            CsvFormat::OPTION_DELIMITER    => ',',
116
            CsvFormat::OPTION_NEW_LINE     => "\n",
117
            CsvFormat::OPTION_QUOTE        => "'",
118
            CsvFormat::OPTION_NULL         => 'NULL',
119
            CsvFormat::OPTION_HEADER_ROW   => 1,
120
            CsvFormat::OPTION_ESCAPE       => '\\',
121
            CsvFormat::OPTION_ENCODING     => 'UTF-8',
122
            CsvFormat::OPTION_DOUBLE_QUOTE => false,
123
            CsvFormat::OPTION_BOM          => null,
124
        ]);
125
    }
126
127
    /**
128
     * @return FormatInterface
129
     */
130 View Code Duplication
    public function getDefaultImportFormat()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
131
    {
132
        return new CsvFormat([
133
            CsvFormat::OPTION_DELIMITER    => ',',
134
            CsvFormat::OPTION_NEW_LINE     => "\n",
135
            CsvFormat::OPTION_QUOTE        => '"',
136
            CsvFormat::OPTION_ESCAPE       => '\\',
137
            CsvFormat::OPTION_NULL         => '\\N',
138
            CsvFormat::OPTION_HEADER_ROW   => 0,
139
            CsvFormat::OPTION_DATA_START   => 1,
140
            CsvFormat::OPTION_DOUBLE_QUOTE => false,
141
            CsvFormat::OPTION_ENCODING     => 'UTF-8',
142
            CsvFormat::OPTION_BOM          => null,
143
        ]);
144
    }
145
146
    /**
147
     * @param FormatInterface $format
148
     *
149
     * @return bool
150
     */
151
    public function isValidExportFormat(FormatInterface $format)
152
    {
153
        return ($format->getType() == 'csv'
154
            && $format instanceof CsvFormatInterface
155
            && $format->getDelimiter() == ','
156
            && $format->getNewLine() == "\n"
157
            && $format->getQuote() == "'"
158
            && $format->getNullValue() == 'NULL'
159
            && $format->getEscape() == '\\'
160
            && $format->getEncoding() == 'UTF-8'
161
            && !$format->useDoubleQuotes()
162
            && is_null($format->getBom()));
163
    }
164
165
    /**
166
     * @param FormatInterface $format
167
     *
168
     * @return bool
169
     */
170
    public function isValidImportFormat(FormatInterface $format)
171
    {
172
        return ($format->getType() == 'csv'
173
            && $format instanceof CsvFormatInterface
174
            && $format->getNullValue() == '\\N'
175
            && !$format->useDoubleQuotes()
176
            && $format->getEncoding() == 'UTF-8'
177
            && is_null($format->getBom()));
178
    }
179
}
180