Ajde_Db_PDOStatement::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @source http://www.coderholic.com/php-database-query-logging-with-pdo/
4
 * Modified for use with Ajde_Document_Processor_Html_Debugger
5
 */
6
7
/**
8
 * PDOStatement decorator that logs when a PDOStatement is
9
 * executed, and the time it took to run.
10
 */
11
class Ajde_Db_PDOStatement extends PDOStatement
12
{
13
    /**
14
     * @see http://www.php.net/manual/en/book.pdo.php#73568
15
     */
16
    public $dbh;
17
18
    protected function __construct($dbh)
19
    {
20
        $this->dbh = $dbh;
21
    }
22
23
    /**
24
     * When execute is called record the time it takes and
25
     * then log the query.
26
     *
27
     * @param array $input_parameters
28
     *
29
     * @throws Ajde_Db_Exception
30
     * @throws Ajde_Exception
31
     *
32
     * @return PDO result set
33
     */
34
    public function execute($input_parameters = null)
35
    {
36
        $log = ['query' => ''];
37
        if (config('app.debug') === true) {
38
            //$cache = Ajde_Db_Cache::getInstance();
39
            if (count($input_parameters)) {
40
                $log = ['query' => vsprintf(str_replace('?', '%s', $this->queryString), $input_parameters)];
41
            } else {
42
                $log = ['query' => '[PS] '.$this->queryString];
43
            }
44
            // add backtrace
45
            $i = 0;
46
            $source = [];
47
            foreach (array_reverse(debug_backtrace()) as $item) {
48
                try {
49
                    $line = issetor($item['line']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $line is correct as issetor($item['line']) (which targets issetor()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
50
                    $file = issetor($item['file']);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $file is correct as issetor($item['file']) (which targets issetor()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
51
                    $source[] = sprintf('%s. <em>%s</em>%s<strong>%s</strong> (%s on line %s)',
52
                        $i,
53
                        !empty($item['class']) ? $item['class'] : '&lt;unknown class&gt;',
54
                        // Assume of no classname is available, dumped from template.. (naive)
55
                        !empty($item['type']) ? $item['type'] : '::',
56
                        !empty($item['function']) ? $item['function'] : '&lt;unknown function&gt;',
57
                        $file,
58
                        $line);
59
                } catch (Exception $e) {
60
                }
61
62
                $i++;
63
            }
64
            $hash = md5(implode('', $source).microtime());
65
66
            $log['query'] = '<a href="javascript:void(0)" onclick="$(\'#'.$hash.'\').slideToggle(\'fast\');" style="color: black;">'.$log['query'].'</a>';
67
            $log['query'] .= '<div id="'.$hash.'" style="display: none;">'.implode('<br/>', $source).'</div>';
68
        }
69
        // start timer
70
        $start = microtime(true);
71
        try {
72
            //if (!$cache->has($this->queryString . serialize($input_parameters))) {
73
            $result = parent::execute($input_parameters);
74
            //$cache->set($this->queryString . serialize($input_parameters), $result);
75
            //	$log['cache'] = false;
76
            //} else {
77
            //	$result = $cache->get($this->queryString . serialize($input_parameters));
78
            //	$log['cache'] = true;
79
            //}
80
        } catch (Exception $e) {
81
            if (substr_count(strtolower($e->getMessage()), 'integrity constraint violation')) {
82
                throw new Ajde_Db_IntegrityException($e->getMessage());
83 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
84
                if (config('app.debug') === true) {
85
                    if (isset($this->queryString)) {
86
                        dump($this->queryString);
87
                    }
88
                    dump('Go to '.config('app.rootUrl').'?install=1 to install DB');
89
                    throw new Ajde_Db_Exception($e->getMessage());
90
                } else {
91
                    Ajde_Exception_Log::logException($e);
0 ignored issues
show
Documentation introduced by
$e is of type object<Exception>, but the function expects a object<Throwable>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
92
                    die('DB connection problem. <a href="?install=1">Install database?</a>');
93
                }
94
            }
95
        }
96
        $time = microtime(true) - $start;
97
        $log['time'] = round($time * 1000, 0);
98
        Ajde_Db_PDO::$log[] = $log;
99
100
        return $result;
101
    }
102
103
    public static function getEmulatedSql($sql, $PDOValues)
104
    {
105
        // @see http://stackoverflow.com/questions/210564/pdo-prepared-statements/1376838#1376838
106
        $keys = [];
107
        $values = [];
108
        foreach ($PDOValues as $key => $value) {
109
            if (is_string($key)) {
110
                $keys[] = '/:'.$key.'/';
111
            } else {
112
                $keys[] = '/[?]/';
113
            }
114
            if (is_null($value)) {
115
                $values[] = 'NULL';
116
            } elseif (is_numeric($value)) {
117
                $values[] = intval($value);
118
            } elseif ($value instanceof Ajde_Db_Function) {
119
                $values[] = (string) $value;
120
            } else {
121
                $values[] = '"'.$value.'"';
122
            }
123
        }
124
        $query = preg_replace($keys, $values, $sql, -1, $count);
125
126
        return $query;
127
    }
128
}
129