Completed
Push — 2.1 ( fdad1c...481970 )
by
unknown
19:03 queued 05:08
created

DbTarget   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 84.62%

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 4
dl 0
loc 67
ccs 22
cts 26
cp 0.8462
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 5 1
C export() 0 34 7
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\log;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\db\Connection;
13
use yii\db\Exception;
14
use yii\di\Instance;
15
use yii\helpers\VarDumper;
16
17
/**
18
 * DbTarget stores log messages in a database table.
19
 *
20
 * The database connection is specified by [[db]]. Database schema could be initialized by applying migration:
21
 *
22
 * ```
23
 * yii migrate --migrationPath=@yii/log/migrations/
24
 * ```
25
 *
26
 * If you don't want to use migration and need SQL instead, files for all databases are in migrations directory.
27
 *
28
 * You may change the name of the table used to store the data by setting [[logTable]].
29
 *
30
 * @author Qiang Xue <[email protected]>
31
 * @since 2.0
32
 */
33
class DbTarget extends Target
34
{
35
    /**
36
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
37
     * After the DbTarget object is created, if you want to change this property, you should only assign it
38
     * with a DB connection object.
39
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
40
     */
41
    public $db = 'db';
42
    /**
43
     * @var string name of the DB table to store cache content. Defaults to "log".
44
     */
45
    public $logTable = '{{%log}}';
46
47
48
    /**
49
     * Initializes the DbTarget component.
50
     * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
51
     * @throws InvalidConfigException if [[db]] is invalid.
52
     */
53 6
    public function init()
54
    {
55 6
        parent::init();
56 6
        $this->db = Instance::ensure($this->db, Connection::class);
57 6
    }
58
59
    /**
60
     * Stores log messages to DB.
61
     * Starting from version 2.0.14, this method throws LogRuntimeException in case the log can not be exported.
62
     * @throws Exception
63
     * @throws LogRuntimeException
64
     */
65 6
    public function export()
66
    {
67 6
        if ($this->db->getTransaction()) {
68
            // create new database connection, if there is an open transaction
69
            // to ensure insert statement is not affected by a rollback
70 3
            $this->db = clone $this->db;
71
        }
72
73 6
        $tableName = $this->db->quoteTableName($this->logTable);
74 6
        $sql = "INSERT INTO $tableName ([[level]], [[category]], [[log_time]], [[prefix]], [[message]])
75
                VALUES (:level, :category, :log_time, :prefix, :message)";
76 6
        $command = $this->db->createCommand($sql);
77 6
        foreach ($this->messages as $message) {
78 6
            [$level, $text, $context] = $message;
0 ignored issues
show
Bug introduced by
The variable $level does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Bug introduced by
The variable $text does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $context does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
79 6
            if (!is_string($text)) {
80
                // exceptions may not be serializable if in the call stack somewhere is a Closure
81
                if ($text instanceof \Throwable || $text instanceof \Exception) {
82
                    $text = (string) $text;
83
                } else {
84
                    $text = VarDumper::export($text);
85
                }
86
            }
87 6
            if ($command->bindValues([
88 6
                    ':level' => $level,
89 6
                    ':category' => $context['category'],
90 6
                    ':log_time' => $context['time'],
91 6
                    ':prefix' => $this->getMessagePrefix($message),
92 6
                    ':message' => $text,
93 6
                ])->execute() > 0) {
94 6
                continue;
95
            }
96
            throw new LogRuntimeException('Unable to export log through database!');
97
        }
98 6
    }
99
}
100