Completed
Push — master ( 6e0700...30b471 )
by Todd
02:33
created

Literal   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 102
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 43.59%

Importance

Changes 0
Metric Value
wmc 13
lcom 1
cbo 0
dl 0
loc 102
ccs 17
cts 39
cp 0.4359
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getValue() 0 11 3
A setValue() 0 5 1
A value() 0 4 1
A __construct() 0 9 4
A driverKey() 0 11 3
A timestamp() 0 9 1
1
<?php
2
/**
3
 * @author Todd Burry <[email protected]>
4
 * @copyright 2009-2014 Vanilla Forums Inc.
5
 * @license MIT
6
 */
7
8
namespace Garden\Db;
9
10
/**
11
 * Represents an string that won't be escaped in queries.
12
 */
13
class Literal {
14
    /// Properties ///
15
16
    /**
17
     * @var array An array that maps driver names to literals.
18
     */
19
    protected $driverValues = [];
20
21
    /// Methods ///
22
23
    /**
24
     * Initialize an instance of the {@link Literal} class.
25
     *
26
     * @param string|array $value Either a string default value or an array in the form
27
     * `['driver' => 'literal']` to specify different literals for different database drivers.
28
     */
29 44
    public function __construct($value) {
30 44
        if (is_string($value)) {
31 44
            $this->driverValues['default'] = $value;
32 44
        } elseif (is_array($value)) {
33
            foreach ($value as $key => $value) {
34
                $this->driverValues[$this->driverKey($key)] = $value;
35
            }
36
        }
37 44
    }
38
39
    /**
40
     * Get the literal value.
41
     *
42
     * @param Db $db The database driver getting the value.
43
     * @param array ...$args Arguments to pass into the literal. This uses **sprintf()** so arguments must already be escaped.
44
     * @return string Returns the value for the specific driver, the default literal, or "null" if there is no default.
45
     */
46 44
    public function getValue(Db $db, ...$args) {
47 44
        $driver = $this->driverKey($db);
48
49 44
        if (isset($this->driverValues[$driver])) {
50
            return sprintf($this->driverValues[$driver], ...$args);
51 44
        } elseif (isset($this->driverValues['default'])) {
52 44
            return sprintf($this->driverValues['default'], ...$args);
53
        } else {
54
            throw new \InvalidArgumentException("No literal for driver '$driver'.", 500);
55
        }
56
    }
57
58
    /**
59
     * Set the literal value.
60
     *
61
     * @param string $value The new value to set.
62
     * @param string|object $driver The name of the database driver to set the value for.
63
     * @return Literal Returns $this for fluent calls.
64
     */
65
    public function setValue($value, $driver = 'default') {
66
        $driver = $this->driverKey($driver);
0 ignored issues
show
Coding Style introduced by
Equals sign not aligned with surrounding assignments; expected 22 spaces but found 1 space

This check looks for multiple assignments in successive lines of code. It will report an issue if the operators are not in a straight line.

To visualize

$a = "a";
$ab = "ab";
$abc = "abc";

will produce issues in the first and second line, while this second example

$a   = "a";
$ab  = "ab";
$abc = "abc";

will produce no issues.

Loading history...
67
        $this->driverValues[$driver] = $value;
68
        return $this;
69
    }
70
71
    /**
72
     * Normalize the driver name for the drivers array.
73
     *
74
     * @param string|object $key The name of the driver or an instance of a database driver.
75
     * @return string Returns the driver name normalized.
0 ignored issues
show
Documentation introduced by
Should the return type not be string[]|string?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
76
     */
77 44
    protected function driverKey($key) {
78 44
        if (is_object($key)) {
79 44
            $key = get_class($key);
80 44
        }
81 44
        $key = strtolower(basename($key));
82
83 44
        if (preg_match('`([az]+)(Db)?$`', $key, $m)) {
84
            $key = $m;
85
        }
86 44
        return $key;
87
    }
88
89
    /**
90
     * Create and return a {@link Literal} object.
91
     *
92
     * @param string|array $value The literal value(s) as passed to {@link Literal::__construct()}.
93
     * @return Literal Thew new literal value.
94
     */
95
    public static function value($value) {
96
        $literal = new Literal($value);
97
        return $literal;
98
    }
99
100
    /**
101
     * Create and return a {@link Literal} object that will query the current unix timesatmp.
102
     *
103
     * @return Literal Returns the timestamp expression.
104
     */
105
    public static function timestamp() {
106
        $literal = new Literal([
107
            MySqlDb::class => 'unix_timestamp()',
108
            SqliteDb::class => "date('now', 'unixepoch')",
109
//            'posgresql' => 'extract(epoch from now())',
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
110
            'default' => time()
111
        ]);
112
        return $literal;
113
    }
114
}
115