Completed
Push — master ( 1857e6...d96bec )
by Joao
03:02
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();
44
45
    /**
46
     * @return CacheEngineInterface
47
     */
48
    public function getCacheEngine()
49
    {
50
        throw new NotImplementedException('You have to implement the cache engine in order to use the Cache');
51
    }
52
53
    /**
54
     * Create a instance of DBDataset to connect database
55
     * @return DBDataset
56
     */
57
    protected function getDBDataset($cache = false)
58
    {
59
        if (is_null($this->_db)) {
60
            $this->_db = new DBDataset($this->getDataBaseName());
61
        }
62
63
        if ($cache === true) {
64
65
            if (is_null($this->_cachedDb)) {
66
                $this->_cachedDb = new CachedDBDataset($this->_db, $this->getCacheEngine());
67
            }
68
69
            return $this->_cachedDb;
70
        }
71
72
        return $this->_db;
73
    }
74
75
    /**
76
     * Execute a SQL and dont wait for a response.
77
     * @param string $sql
78
     * @param string $param
79
     * @param bool getId
80
     */
81
    protected function executeSQL($sql, $param = null, $getId = false)
82
    {
83
        $dbfunction = $this->getDbFunctions();
84
85
        $debug = AnyDatasetContext::getInstance()->getDebug();
86
        $start = 0;
87 View Code Duplication
        if ($debug) {
88
            $log = LogHandler::getInstance();
89
            $log->debug("Class name: " . get_class($this));
90
            $log->debug("SQL: " . $sql);
91
            if (!is_null($param)) {
92
                $s = "";
93
                foreach ($param as $key => $value) {
94
                    if ($s != "") {
95
                        $s .= ", ";
96
                    }
97
                    $s .= "[$key]=$value";
98
                }
99
                $log->debug("Params: $s");
100
            }
101
            $start = microtime(true);
102
        }
103
104
        if ($getId) {
105
            $id = $dbfunction->executeAndGetInsertedId($this->getDBDataset(), $sql, $param);
106
        } else {
107
            $id = null;
108
            $this->getDBDataset()->execSQL($sql, $param);
109
        }
110
111 View Code Duplication
        if ($debug) {
112
            $end = microtime(true);
113
            $log->debug("Execution time: " . ($end - $start) . " seconds ");
114
        }
115
116
        return $id;
117
    }
118
119
    /**
120
     * Execulte SELECT SQL Query
121
     *
122
     * @param string $sql
123
     * @param array $param
124
     * @return IteratorInterface
125
     */
126
    protected function getIterator($sql, $param = null, $ttl = -1)
127
    {
128
        $db = $this->getDBDataset($ttl > 0);
129
130
        $debug = AnyDatasetContext::getInstance()->getDebug();
131
        $start = 0;
132 View Code Duplication
        if ($debug) {
133
            $log = LogHandler::getInstance();
134
            $log->debug("Class name: " . get_class($this));
135
            $log->debug("SQL: " . $sql);
136
            if (!is_null($param)) {
137
                $s = "";
138
                foreach ($param as $key => $value) {
139
                    if ($s != "") {
140
                        $s .= ", ";
141
                    }
142
                    $s .= "[$key]=$value";
143
                }
144
                $log->debug("Params: $s");
145
            }
146
            $start = microtime(true);
147
        }
148
        $it = $db->getIterator($sql, $param, $ttl);
149 View Code Duplication
        if ($debug) {
150
            $end = microtime(true);
151
            $log->debug("Execution Time: " . ($end - $start) . " segundos ");
152
        }
153
        return $it;
154
    }
155
156
    protected function getScalar($sql, $param = null)
157
    {
158
        $this->getDBDataset();
159
160
        $debug = AnyDatasetContext::getInstance()->getDebug();
161
        $start = 0;
162 View Code Duplication
        if ($debug) {
163
            $log = LogHandler::getInstance();
164
            $log->debug("Class name: " . get_class($this));
165
            $log->debug("SQL: " . $sql);
166
            if (!is_null($param)) {
167
                $s = "";
168
                foreach ($param as $key => $value) {
169
                    if ($s != "") {
170
                        $s .= ", ";
171
                    }
172
                    $s .= "[$key]=$value";
173
                }
174
                $log->debug("Params: $s");
175
            }
176
            $start = microtime(true);
177
        }
178
        $scalar = $this->_db->getScalar($sql, $param);
179 View Code Duplication
        if ($debug) {
180
            $end = microtime(true);
181
            $log->debug("Execution Time: " . ($end - $start) . " segundos ");
182
        }
183
        return $scalar;
184
    }
185
186
    /**
187
     * Get a SQLHelper object
188
     *
189
     * @return SQLHelper
190
     */
191
    public function getSQLHelper()
192
    {
193
        $this->getDBDataset();
194
195
        if (is_null($this->_sqlhelper)) {
196
            $this->_sqlhelper = new SQLHelper($this->_db);
197
        }
198
199
        return $this->_sqlhelper;
200
    }
201
202
    /**
203
     * Get an Interator from an ID. Ideal for get data from PK
204
     *
205
     * @param string $tablename
206
     * @param string $key
207
     * @param string $value
208
     * @return IteratorInterface
209
     */
210
    protected function getIteratorbyId($tablename, $key, $value)
211
    {
212
        $sql = "select * from $tablename where $key = [[$key]] ";
213
        $param = array();
214
        $param[$key] = $value;
215
        return $this->getIterator($sql, $param);
216
    }
217
218
    /**
219
     * Get an Array from an existing Iterator
220
     *
221
     * @param IteratorInterface $it
222
     * @param string $key
223
     * @param string $value
224
     * @return array()
0 ignored issues
show
The doc-type array() could not be parsed: Expected "|" or "end of type", but got "(" at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
225
     */
226
    public static function getArrayFromIterator(IteratorInterface $it, $key, $value, $firstElement = "-- Selecione --")
227
    {
228
        $retArray = array();
229
        if ($firstElement != "") {
230
            $retArray[""] = $firstElement;
231
        }
232
        while ($it->hasNext()) {
233
            $sr = $it->moveNext();
234
            $retArray[$sr->getField(strtolower($key))] = $sr->getField(strtolower($value));
235
        }
236
        return $retArray;
237
    }
238
239
    /**
240
     *
241
     * @param IteratorInterface $it
242
     * @param string $name
243
     * @param array fields
244
     * @param bool $echoToBrowser
245
     */
246
    public static function saveToCSV($it, $name = "data.csv", $fields = null, $echoToBrowser = true)
247
    {
248
        if ($echoToBrowser) {
249
            ob_clean();
250
251
            header("Content-Type: text/csv;");
252
            header("Content-Disposition: attachment; filename=$name");
253
        }
254
255
        $first = true;
256
        $line = "";
257
        foreach ($it as $sr) {
258
            if ($first) {
259
                $first = false;
260
261
                if (is_null($fields)) {
262
                    $fields = $sr->getFieldNames();
263
                }
264
265
                $line .= '"' . implode('","', $fields) . '"' . "\n";
266
            }
267
268
            $raw = array();
269
            foreach ($fields as $field) {
270
                $raw[] = $sr->getField($field);
271
            }
272
            $line .= '"' . implode('","', array_values($raw)) . '"' . "\n";
273
274
            if ($echoToBrowser) {
275
                echo $line;
276
                $line = "";
277
            }
278
        }
279
280
        if (!$echoToBrowser) {
281
            return $line;
282
        }
283
    }
284
285
    /**
286
     * Get a IDbFunctions class containing specific database operations
287
     * @return DBFunctionsInterface
288
     */
289
    public function getDbFunctions()
290
    {
291
        return $this->getDBDataset()->getDbFunctions();
292
    }
293
294
    public function beginTransaction()
295
    {
296
        $this->getDBDataset()->beginTransaction();
297
    }
298
299
    public function commitTransaction()
300
    {
301
        $this->getDBDataset()->commitTransaction();
302
    }
303
304
    public function rollbackTransaction()
305
    {
306
        $this->getDBDataset()->rollbackTransaction();
307
    }
308
309
    public function getObjectDbDataSet()
310
    {
311
        return $this->_db;
312
    }
313
314
    public function joinTransactionContext(BaseDBAccess $dal)
315
    {
316
        if (is_null($dal->getObjectDbDataSet())) {
317
            throw new \Exception('Transaction not initialized');
318
        }
319
        $this->_db = $dal->getObjectDbDataSet();
320
    }
321
}
322