Completed
Branch master (a2888f)
by Joao
08:30 queued 04:22
created

src/Database/BaseDBAccess.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace ByJG\AnyDataset\Database;
4
5
use ByJG\AnyDataset\AnyDatasetContext;
6
use ByJG\AnyDataset\Exception\NotImplementedException;
7
use ByJG\AnyDataset\LogHandler;
8
use ByJG\AnyDataset\Repository\CachedDBDataset;
9
use ByJG\AnyDataset\Repository\DBDataset;
10
use ByJG\AnyDataset\Repository\IteratorInterface;
11
use ByJG\Cache\CacheEngineInterface;
12
13
abstract class BaseDBAccess
14
{
15
16
    /**
17
     * @var DBDataset
18
     */
19
    protected $_db = null;
20
    protected $_cachedDb = null;
21
22
    /**
23
     * Wrapper for SQLHelper
24
     *
25
     * @var SQLHelper
26
     */
27
    protected $_sqlhelper = null;
28
29
    /**
30
     * Base Class Constructor. Don't must be override.
31
     *
32
     */
33
    public function __construct()
34
    {
35
        // Nothing Here
36
    }
37
38
    /**
39
     * This method must be overrided and the return must be a valid DBDataset name.
40
     *
41
     * @return string
42
     */
43
    public abstract function getDataBaseName();
0 ignored issues
show
The abstract declaration must precede the visibility declaration
Loading history...
44
45
    /**
46
     * @return CacheEngineInterface
47
     * @throws NotImplementedException
48
     */
49
    public function getCacheEngine()
50
    {
51
        throw new NotImplementedException('You have to implement the cache engine in order to use the Cache');
52
    }
53
54
    /**
55
     * Create a instance of DBDataset to connect database
56
     * @param bool $cache
57
     * @return DBDataset
58
     * @throws NotImplementedException
59
     */
60
    protected function getDBDataset($cache = false)
61
    {
62
        if (is_null($this->_db)) {
63
            $this->_db = new DBDataset($this->getDataBaseName());
64
        }
65
66
        if ($cache === true) {
67
68
            if (is_null($this->_cachedDb)) {
69
                $this->_cachedDb = new CachedDBDataset($this->_db, $this->getCacheEngine());
70
            }
71
72
            return $this->_cachedDb;
73
        }
74
75
        return $this->_db;
76
    }
77
78
    /**
79
     * Execute a SQL and dont wait for a response.
80
     * @param string $sql
81
     * @param string $param
82
     * @param bool $getId
83
     * @return int|null
84
     */
85
    protected function executeSQL($sql, $param = null, $getId = false)
86
    {
87
        $dbfunction = $this->getDbFunctions();
88
89
        $debug = AnyDatasetContext::getInstance()->getDebug();
90
        $start = 0;
91 View Code Duplication
        if ($debug) {
92
            $log = LogHandler::getInstance();
93
            $log->debug("Class name: " . get_class($this));
94
            $log->debug("SQL: " . $sql);
95
            if (!is_null($param)) {
96
                $s = "";
97
                foreach ($param as $key => $value) {
98
                    if ($s != "") {
99
                        $s .= ", ";
100
                    }
101
                    $s .= "[$key]=$value";
102
                }
103
                $log->debug("Params: $s");
104
            }
105
            $start = microtime(true);
106
        }
107
108
        if ($getId) {
109
            $id = $dbfunction->executeAndGetInsertedId($this->getDBDataset(), $sql, $param);
110
        } else {
111
            $id = null;
112
            $this->getDBDataset()->execSQL($sql, $param);
113
        }
114
115 View Code Duplication
        if ($debug) {
116
            $end = microtime(true);
117
            $log->debug("Execution time: " . ($end - $start) . " seconds ");
118
        }
119
120
        return $id;
121
    }
122
123
    /**
124
     * Execulte SELECT SQL Query
125
     *
126
     * @param string $sql
127
     * @param array $param
128
     * @param int $ttl
129
     * @return IteratorInterface
130
     */
131
    protected function getIterator($sql, $param = null, $ttl = -1)
132
    {
133
        $db = $this->getDBDataset($ttl > 0);
134
135
        $debug = AnyDatasetContext::getInstance()->getDebug();
136
        $start = 0;
137 View Code Duplication
        if ($debug) {
138
            $log = LogHandler::getInstance();
139
            $log->debug("Class name: " . get_class($this));
140
            $log->debug("SQL: " . $sql);
141
            if (!is_null($param)) {
142
                $s = "";
143
                foreach ($param as $key => $value) {
144
                    if ($s != "") {
145
                        $s .= ", ";
146
                    }
147
                    $s .= "[$key]=$value";
148
                }
149
                $log->debug("Params: $s");
150
            }
151
            $start = microtime(true);
152
        }
153
        $it = $db->getIterator($sql, $param, $ttl);
154 View Code Duplication
        if ($debug) {
155
            $end = microtime(true);
156
            $log->debug("Execution Time: " . ($end - $start) . " segundos ");
157
        }
158
        return $it;
159
    }
160
161
    protected function getScalar($sql, $param = null)
162
    {
163
        $this->getDBDataset();
164
165
        $debug = AnyDatasetContext::getInstance()->getDebug();
166
        $start = 0;
167 View Code Duplication
        if ($debug) {
168
            $log = LogHandler::getInstance();
169
            $log->debug("Class name: " . get_class($this));
170
            $log->debug("SQL: " . $sql);
171
            if (!is_null($param)) {
172
                $s = "";
173
                foreach ($param as $key => $value) {
174
                    if ($s != "") {
175
                        $s .= ", ";
176
                    }
177
                    $s .= "[$key]=$value";
178
                }
179
                $log->debug("Params: $s");
180
            }
181
            $start = microtime(true);
182
        }
183
        $scalar = $this->_db->getScalar($sql, $param);
184 View Code Duplication
        if ($debug) {
185
            $end = microtime(true);
186
            $log->debug("Execution Time: " . ($end - $start) . " segundos ");
187
        }
188
        return $scalar;
189
    }
190
191
    /**
192
     * Get a SQLHelper object
193
     *
194
     * @return SQLHelper
195
     */
196
    public function getSQLHelper()
197
    {
198
        $this->getDBDataset();
199
200
        if (is_null($this->_sqlhelper)) {
201
            $this->_sqlhelper = new SQLHelper($this->_db);
202
        }
203
204
        return $this->_sqlhelper;
205
    }
206
207
    /**
208
     * Get an Interator from an ID. Ideal for get data from PK
209
     *
210
     * @param string $tablename
211
     * @param string $key
212
     * @param string $value
213
     * @return IteratorInterface
214
     */
215
    protected function getIteratorbyId($tablename, $key, $value)
216
    {
217
        $sql = "select * from $tablename where $key = [[$key]] ";
218
        $param = array();
219
        $param[$key] = $value;
220
        return $this->getIterator($sql, $param);
221
    }
222
223
    /**
224
     * Get an Array from an existing Iterator
225
     *
226
     * @param IteratorInterface $it
227
     * @param string $key
228
     * @param string $value
229
     * @param string $firstElement
230
     * @return array
231
     */
232
    public static function getArrayFromIterator(IteratorInterface $it, $key, $value, $firstElement = "-- Selecione --")
233
    {
234
        $retArray = array();
235
        if ($firstElement != "") {
236
            $retArray[""] = $firstElement;
237
        }
238
        while ($it->hasNext()) {
239
            $sr = $it->moveNext();
240
            $retArray[$sr->getField(strtolower($key))] = $sr->getField(strtolower($value));
241
        }
242
        return $retArray;
243
    }
244
245
    /**
246
     *
247
     * @param IteratorInterface $it
248
     * @param string $name
249
     * @param array $fields
250
     * @param bool $echoToBrowser
251
     * @return string
252
     */
253
    public static function saveToCSV($it, $name = "data.csv", $fields = null, $echoToBrowser = true)
254
    {
255
        if ($echoToBrowser) {
256
            ob_clean();
257
258
            header("Content-Type: text/csv;");
259
            header("Content-Disposition: attachment; filename=$name");
260
        }
261
262
        $first = true;
263
        $line = "";
264
        foreach ($it as $sr) {
265
            if ($first) {
266
                $first = false;
267
268
                if (is_null($fields)) {
269
                    $fields = $sr->getFieldNames();
270
                }
271
272
                $line .= '"' . implode('","', $fields) . '"' . "\n";
273
            }
274
275
            $raw = array();
276
            foreach ($fields as $field) {
277
                $raw[] = $sr->getField($field);
278
            }
279
            $line .= '"' . implode('","', array_values($raw)) . '"' . "\n";
280
281
            if ($echoToBrowser) {
282
                echo $line;
283
                $line = "";
284
            }
285
        }
286
287
        if (!$echoToBrowser) {
288
            return $line;
289
        }
290
        
291
        return null;
292
    }
293
294
    /**
295
     * Get a IDbFunctions class containing specific database operations
296
     * @return DBFunctionsInterface
297
     */
298
    public function getDbFunctions()
299
    {
300
        return $this->getDBDataset()->getDbFunctions();
301
    }
302
303
    public function beginTransaction()
304
    {
305
        $this->getDBDataset()->beginTransaction();
306
    }
307
308
    public function commitTransaction()
309
    {
310
        $this->getDBDataset()->commitTransaction();
311
    }
312
313
    public function rollbackTransaction()
314
    {
315
        $this->getDBDataset()->rollbackTransaction();
316
    }
317
318
    public function getObjectDbDataSet()
319
    {
320
        return $this->_db;
321
    }
322
323
    public function joinTransactionContext(BaseDBAccess $dal)
324
    {
325
        if (is_null($dal->getObjectDbDataSet())) {
326
            throw new \Exception('Transaction not initialized');
327
        }
328
        $this->_db = $dal->getObjectDbDataSet();
329
    }
330
}
331