Test Failed
Push — master ( d9cbc5...ae0313 )
by Pierre
32:05
created

Stations::tableExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 10
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 13
rs 9.9332
1
<?php
2
3
namespace App\Component\Migration\Metro;
4
5
use App\Component\Model\Orm\Orm;
6
use App\Component\Db\Migration;
7
use App\Model\Repository\Metro\Stations as StationsRepository;
8
use Nymfonya\Component\Container;
9
use SplFileObject;
10
11
class Stations extends Migration
12
{
13
    const MIG_FIELDS = [
14
        'id', 'lon', 'lat', 'name', 'h'
15
    ];
16
    const CSV_FIXTURE = '/../../../../../assets/model/metro/stations.csv';
17
    const MEM_LIM = 'memory_limit';
18
19
    /**
20
     * repository
21
     *
22
     * @var Orm
23
     */
24
    protected $repository;
25
26
    /**
27
     * instanciate
28
     *
29
     * @param Container $container
30
     */
31
    public function __construct(Container $container)
32
    {
33
        parent::__construct($container);
34
        $this->repository = new StationsRepository($container);
35
        $this->fromOrm($this->repository);
36
    }
37
38
    /**
39
     * check if migration can run
40
     *
41
     * @return boolean
42
     */
43
    protected function canMigrate(): bool
44
    {
45
        return (!$this->tableExists());
46
    }
47
48
    /**
49
     * create table
50
     *
51
     * @return Migration
52
     */
53
    protected function runCreate(): Migration
54
    {
55
        if (!$this->tableExists()) {
56
            $sql = sprintf(
57
                'CREATE TABLE `%s` (
58
                    `id` bigint(20) NOT NULL,
59
                    `lon` double NOT NULL,
60
                    `lat` double NOT NULL,
61
                    `name` varchar(150) NOT NULL,
62
                    `h` varchar(16) NOT NULL
63
                  ) ENGINE=InnoDB DEFAULT CHARSET=utf8',
64
                $this->repository->getTable()
65
            );
66
            $this->run($sql);
67
        }
68
        return $this;
69
    }
70
71
    /**
72
     * insert into table
73
     *
74
     * @return Migration
75
     */
76
    protected function runInsert(): Migration
77
    {
78
        $ml = ini_get(self::MEM_LIM);
79
        ini_set(self::MEM_LIM, '8M');
80
        if ($this->tableExists()) {
81
            $stream = new SplFileObject(
82
                __DIR__ . self::CSV_FIXTURE
83
            );
84
            $stream->setFlags(
85
                SplFileObject::READ_CSV |
86
                    SplFileObject::SKIP_EMPTY |
87
                    SplFileObject::READ_AHEAD |
88
                    SplFileObject::DROP_NEW_LINE
89
            );
90
            while (false === $stream->eof()) {
91
                $csvData = $stream->fgetcsv();
92
                if (!empty($csvData)) {
93
                    $data = array_combine(self::MIG_FIELDS, $csvData);
94
                    $this->repository->resetBuilder();
95
                    $this->repository->insert($data);
0 ignored issues
show
Bug introduced by
It seems like $data can also be of type false; however, parameter $columns of App\Component\Model\Orm\Orm::insert() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

95
                    $this->repository->insert(/** @scrutinizer ignore-type */ $data);
Loading history...
96
                    $this->run(
97
                        $this->repository->getSql(),
98
                        $this->repository->getBuilderValues()
99
                    );
100
                }
101
                unset($csvData);
102
            }
103
            $stream = null;
104
            unset($stream, $lines);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $lines seems to be never defined.
Loading history...
105
        }
106
        ini_set(self::MEM_LIM, $ml);
107
        return $this;
108
    }
109
110
    /**
111
     * index table
112
     *
113
     * @return Migration
114
     */
115
    protected function runIndex(): Migration
116
    {
117
        $pkey = $this->repository->getPrimary();
118
        $sqlIndex = sprintf(
119
            'ALTER TABLE `%s`'
120
                . 'ADD PRIMARY KEY (`%s`),'
121
                . 'ADD KEY `%s` (`%s`),'
122
                . 'ADD KEY `name` (`name`),'
123
                . 'ADD KEY `h` (`h`)',
124
            $this->repository->getTable(),
125
            $pkey,
126
            $pkey,
127
            $pkey
128
        );
129
        $this->run($sqlIndex);
130
        $sqlAutoinc = sprintf('ALTER TABLE `%s`'
131
            . 'MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, '
132
            . 'AUTO_INCREMENT=1', $this->repository->getTable());
133
        $this->run($sqlAutoinc);
134
        return $this;
135
    }
136
137
    /**
138
     * return true if table exists
139
     *
140
     * @return boolean
141
     */
142
    protected function tableExists(): bool
143
    {
144
        $sqlWhere = " WHERE table_schema = '%s' AND table_name = '%s';";
145
        $sql = sprintf(
146
            "SELECT count(*) as counter FROM %s " . $sqlWhere,
147
            'information_schema.tables',
148
            $this->repository->getDatabase(),
149
            $this->repository->getTable()
150
        );
151
        $this->run($sql)->hydrate();
152
        $result = $this->getRowset()[0];
153
        $counter = (int) $result['counter'];
154
        return ($counter > 0);
155
    }
156
157
    /**
158
     * drop table if exists
159
     *
160
     * @return boolean
161
     */
162
    protected function dropTable(): bool
163
    {
164
        if (!$this->tableExists()) {
165
            return false;
166
        }
167
        $sql = 'DROP TABLE ' . $this->repository->getTable() . ';';
168
        $this->run($sql);
169
        return true;
170
    }
171
}
172