Completed
Push — master ( a8c375...9d1763 )
by
unknown
15s
created

QueryDebuggerTask::run()   C

Complexity

Conditions 7
Paths 2

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 34
rs 6.7272
cc 7
eloc 18
nc 2
nop 0
1
<?php
2
3
namespace App\Containers\Debugger\Tasks;
4
5
use App;
6
use App\Ship\Parents\Tasks\Task;
7
use DateTimeInterface;
8
use DB;
9
use Illuminate\Support\Facades\Config;
10
use Log;
11
12
/**
13
 * Class QueryDebuggerTask.
14
 *
15
 * @author  Mahmoud Zalt <[email protected]>
16
 */
17
class QueryDebuggerTask extends Task
18
{
19
20
    /**
21
     * Write the DB queries in the Log and Display them in the
22
     * terminal (in case you want to see them while executing the tests).
23
     */
24
    public function run()
25
    {
26
        $debuggerEnabled = Config::get('debugger.queries.debug');
27
28
        if ($debuggerEnabled) {
29
30
            $consoleOutputEnabled = Config::get('debugger.queries.output.console');
31
            $logOutputEnabled = Config::get('debugger.queries.output.log');
32
33
            DB::listen(function ($event) use ($consoleOutputEnabled, $logOutputEnabled) {
34
                $bindings = $event->bindings;
35
                // We need to transform all bindings to a readable value the same fashion 
36
                // as the one used in \Illuminate\Database\Connection::prepareBindings(array $bindings)
37
                foreach ($bindings as $key => $value) {
38
                    if ($value instanceof DateTimeInterface) {
39
                        $bindings[$key] = $value->format(DB::getQueryGrammar()->getDateFormat());
40
                    } elseif (is_bool($value)) {
41
                        $bindings[$key] = (int) $value;
42
                    }
43
                }
44
                $fullQuery = vsprintf(str_replace(['%', '?'], ['%%', '%s'], $event->sql), $bindings);
45
46
                $result = $event->connectionName . ' (' . $event->time . '): ' . $fullQuery;
47
48
                if ($consoleOutputEnabled) {
49
                    dump($result);
50
                }
51
52
                if ($logOutputEnabled) {
53
                    Log::info($result);
54
                }
55
            });
56
        }
57
    }
58
59
}
60