Completed
Push — master ( 598fe1...4a905b )
by Michael
03:41
created

CommonSqlQueries::getDeleteFromTableWithOwnerID()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
ccs 0
cts 10
cp 0
rs 9.4285
cc 1
eloc 7
nc 1
nop 2
crap 2
1
<?php
2
declare(strict_types = 1);
3
/**
4
 * Contains CommonSqlQueries class.
5
 *
6
 * PHP version 7.0+
7
 *
8
 * LICENSE:
9
 * This file is part of Yet Another Php Eve Api Library also know as Yapeal
10
 * which can be used to access the Eve Online API data and place it into a
11
 * database.
12
 * Copyright (C) 2014-2016 Michael Cummings
13
 *
14
 * This program is free software: you can redistribute it and/or modify it
15
 * under the terms of the GNU Lesser General Public License as published by the
16
 * Free Software Foundation, either version 3 of the License, or (at your
17
 * option) any later version.
18
 *
19
 * This program is distributed in the hope that it will be useful, but WITHOUT
20
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
21
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
22
 * for more details.
23
 *
24
 * You should have received a copy of the GNU Lesser General Public License
25
 * along with this program. If not, see
26
 * <http://spdx.org/licenses/LGPL-3.0.html>.
27
 *
28
 * You should be able to find a copy of this license in the COPYING-LESSER.md
29
 * file. A copy of the GNU GPL should also be available in the COPYING.md file.
30
 *
31
 * @copyright 2014-2016 Michael Cummings
32
 * @license   http://www.gnu.org/copyleft/lesser.html GNU LGPL
33
 * @author    Michael Cummings <[email protected]>
34
 */
35
namespace Yapeal\Sql;
36
37
use Yapeal\DicAwareInterface;
38
use Yapeal\DicAwareTrait;
39
use Yapeal\Event\YEMAwareInterface;
40
use Yapeal\Event\YEMAwareTrait;
41
use Yapeal\FileSystem\CommonFileHandlingTrait;
42
43
/**
44
 * Class CommonSqlQueries
45
 *
46
 * @method string getAccountCorporationIDsExcludingCorporationKeys()
47
 * @method string getActiveApis()
48
 * @method string getActiveMailBodiesWithOwnerID($ownerID)
49
 * @method string getActiveRegisteredAccountStatus($mask)
50
 * @method string getActiveRegisteredCharacters($mask)
51
 * @method string getActiveRegisteredCorporations($mask)
52
 * @method string getActiveRegisteredKeys()
53
 * @method string getActiveStarbaseTowers($mask, $ownerID)
54
 * @method string getApiLock($hash)
55
 * @method string getApiLockRelease($hash)
56
 * @method string getCreateAddOrModifyColumnProcedure()
57
 * @method string getDeleteFromTable($tableName)
58
 * @method string getDeleteFromTableWithKeyID($tableName, $keyID)
59
 * @method string getDeleteFromTableWithOwnerID($tableName, $ownerID)
60
 * @method string getDropAddOrModifyColumnProcedure()
61
 * @method string getMemberCorporationIDsExcludingAccountCorporations()
62
 * @method string getUtilLatestDatabaseVersion()
63
 * @method string getUtilLatestDatabaseVersionUpdate()
64
 * @method string initialization()
65
 */
66
class CommonSqlQueries implements DicAwareInterface, YEMAwareInterface
67
{
68
    use CommonFileHandlingTrait, DicAwareTrait, SqlSubsTrait, YEMAwareTrait;
69
    /**
70
     * @param string $databaseName
71
     * @param string $tablePrefix
72
     */
73
    public function __construct($databaseName, $tablePrefix)
74
    {
75
        $this->databaseName = $databaseName;
76
        $this->tablePrefix = $tablePrefix;
77
    }
78
    /**
79
     * @param string $name
80
     * @param array  $arguments
81
     *
82
     * @return mixed
83
     * @throws \InvalidArgumentException
84
     * @throws \DomainException
85
     * @throws \BadMethodCallException
86
     * @throws \LogicException
87
     */
88
    public function __call(string $name, array $arguments = [])
89
    {
90
        $fileNames = explode(',',
91
            sprintf('%1$s%2$s.%3$s.sql,%1$s%2$s.sql',
92
                $this->getDic()['Yapeal.Sql.dir'] . 'queries/',
93
                $name,
94
                $this->getDic()['Yapeal.Sql.platform']));
95
        foreach ($fileNames as $fileName) {
96
            if ($this->isCachedSql($fileName)) {
97
                return $this->getCachedSql($fileName);
98
            }
99
            if (!is_readable($fileName) || !is_file($fileName)) {
100
                continue;
101
            }
102
            $sql = $this->safeFileRead($fileName);
103
            if (false === $sql) {
104
                continue;
105
            }
106
            return $this->processSql($fileName, $sql, $arguments);
107
        }
108
        $mess = 'Unknown method ' . $name;
109
        throw new \BadMethodCallException($mess);
110
    }
111
    /**
112
     * @param string   $tableName
113
     * @param string[] $columnNameList
114
     * @param int      $rowCount
115
     *
116
     * @return string
117
     * @throws \LogicException
118
     */
119
    public function getUpsert(string $tableName, array $columnNameList, int $rowCount): string
120
    {
121
        $replacements = $this->getReplacements();
122
        $replacements['{tableName}'] = $tableName;
123
        $replacements['{columnNames}'] = implode('","', $columnNameList);
124
        $rowPrototype = '(' . implode(',', array_fill(0, count($columnNameList), '?')) . ')';
125
        $replacements['{rowset}'] = implode(',', array_fill(0, $rowCount, $rowPrototype));
126
        $updates = [];
127
        foreach ($columnNameList as $column) {
128
            $updates[] = sprintf('"%1$s"=VALUES("%1$s")', $column);
129
        }
130
        $replacements['{updates}'] = implode(',', $updates);
131
        /** @noinspection SqlResolve */
132
        $sql = 'INSERT INTO "{schema}"."{tablePrefix}{tableName}" ("{columnNames}") VALUES {rowset} ON DUPLICATE KEY UPDATE {updates}';
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 135 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
133
        return str_replace(array_keys($replacements), array_values($replacements), $sql);
134
    }
135
    /**
136
     * @param array <string, string> $columns
137
     *
138
     * @return string
139
     * @throws \LogicException
140
     */
141
    public function getUtilCachedUntilExpires(array $columns): string
142
    {
143
        $replacements = $this->getReplacements();
144
        $where = [];
145
        // I.E. "apiName" = 'accountBalance'
146
        foreach ($columns as $key => $value) {
147
            $where[] = sprintf('"%1$s" = \'%2$s\'', $key, $value);
148
        }
149
        $replacements['{where}'] = implode(' AND ', $where);
150
        /** @noinspection SqlResolve */
151
        $sql = 'SELECT "expires" FROM "{schema}"."{tablePrefix}utilCachedUntil" WHERE {WHERE};';
152
        return str_replace(array_keys($replacements), array_values($replacements), $sql);
153
    }
154
    /**
155
     * @var string $databaseName
156
     */
157
    protected $databaseName;
158
    /**
159
     * @var string $tablePrefix
160
     */
161
    protected $tablePrefix;
162
    /**
163
     * @param string $fileName
164
     * @param string $sql
165
     */
166
    private function cacheSqlQuery(string $fileName, string $sql)
167
    {
168
        $this->sqlCache[$fileName] = $sql;
169
    }
170
    /**
171
     * @param string $fileName
172
     *
173
     * @return string
174
     */
175
    private function getCachedSql(string $fileName): string
176
    {
177
        return $this->sqlCache[$fileName];
178
    }
179
    /**
180
     * @return array
181
     * @throws \LogicException
182
     */
183
    private function getReplacements()
184
    {
185
        if (null === $this->replacements) {
186
            $this->replacements = $this->getSqlSubs($this->getDic());
187
        }
188
        return $this->replacements;
189
    }
190
    /**
191
     * @param string $fileName
192
     *
193
     * @return bool
194
     */
195
    private function isCachedSql(string $fileName): bool
196
    {
197
        return array_key_exists($fileName, $this->sqlCache);
198
    }
199
    /**
200
     * @param string $fileName
201
     *
202
     * @param string $sql
203
     * @param array  $arguments
204
     *
205
     * @return string
206
     * @throws \LogicException
207
     */
208
    private function processSql(string $fileName, string $sql, array $arguments)
209
    {
210
        $sql = $this->getCleanedUpSql($sql, $this->getReplacements());
211
        if (0 !== count($arguments)) {
212
            $sql = vsprintf($sql, $arguments);
213
        } else {
214
            $this->cacheSqlQuery($fileName, $sql);
215
        }
216
        return $sql;
217
    }
218
    /**
219
     * @var array $replacements Holds a list of Sql section replacement pairs.
220
     */
221
    private $replacements;
222
    /**
223
     * @var array sqlCache
224
     */
225
    private $sqlCache = [];
226
}
227