Completed
Pull Request — release-2.1 (#4306)
by Jeremy
07:13
created

sqlite_cache::getVersion()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Simple Machines Forum (SMF)
5
 *
6
 * @package SMF
7
 * @author Simple Machines http://www.simplemachines.org
8
 * @copyright 2017 Simple Machines and individual contributors
9
 * @license http://www.simplemachines.org/about/smf/license.php BSD
10
 *
11
 * @version 2.1 Beta 4
12
 */
13
14
if (!defined('SMF'))
15
	die('Hacking attempt...');
16
17
/**
18
 * SQLite Cache API class
19
 * @package cacheAPI
20
 */
21
class sqlite_cache extends cache_api
22
{
23
	/**
24
	 * @var string The path to the current $cachedir directory.
25
	 */
26
	private $cachedir = null;
27
28
	/**
29
	 * @var SQLite3
30
	 */
31
	private $cacheDB = null;
32
33
	/**
34
	 * @var int
35
	 */
36
	private $cacheTime = 0;
37
38
	public function __construct()
39
	{
40
		parent::__construct();
41
42
		// Set our default cachedir.
43
		$this->setCachedir();
44
	}
45
46
	/**
47
	 * {@inheritDoc}
48
	 */
49
	public function connect()
50
	{
51
52
		$database = $this->cachedir . '/' . 'SQLite3Cache.db3';
53
		$this->cacheDB = new SQLite3($database);
54
		$this->cacheDB->busyTimeout(1000);
55
		if (filesize($database) == 0)
56
		{
57
			$this->cacheDB->exec('CREATE TABLE cache (key text unique, value blob, ttl int);');
58
			$this->cacheDB->exec('CREATE INDEX ttls ON cache(ttl);');
59
		}
60
		$this->cacheTime = time();
61
62
	}
63
64
	/**
65
	 * {@inheritDoc}
66
	 */
67 View Code Duplication
	public function isSupported($test = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
68
	{
69
		$supported = class_exists("SQLite3") && is_writable($this->cachedir);
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal SQLite3 does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
70
71
		if ($test)
72
			return $supported;
73
74
		return parent::isSupported() && $supported;
75
	}
76
77
	/**
78
	 * {@inheritDoc}
79
	 */
80
	public function getData($key, $ttl = null)
81
	{
82
		$ttl = time() - $ttl;
83
		$query = 'SELECT value FROM cache WHERE key = \'' . $this->cacheDB->escapeString($key) . '\' AND ttl >= ' . $ttl . ' LIMIT 1';
84
		$result = $this->cacheDB->query($query);
85
86
		$value = null;
87
		while ($res = $result->fetchArray(SQLITE3_ASSOC))
88
			$value = $res['value'];
89
90
		return !empty($value) ? $value : null;
91
	}
92
93
	/**
94
	 * {@inheritDoc}
95
	 */
96
	public function putData($key, $value, $ttl = null)
97
	{
98
99
		$ttl = $this->cacheTime + $ttl;
100
		$query = 'REPLACE INTO cache VALUES (\'' . $this->cacheDB->escapeString($key) . '\', \'' . $this->cacheDB->escapeString($value) . '\', ' . $this->cacheDB->escapeString($ttl) . ');';
101
		$result = $this->cacheDB->exec($query);
102
103
		return $result;
104
	}
105
106
	/**
107
	 * {@inheritDoc}
108
	 */
109
	public function cleanCache($type = '')
110
	{
111
112
		$query = 'DELETE FROM cache;';
113
		$result = $this->cacheDB->exec($query);
114
115
		return $result;
116
	}
117
118
	/**
119
	 * {@inheritDoc}
120
	 */
121 View Code Duplication
	public function cacheSettings(array &$config_vars)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
122
	{
123
		global $context, $txt;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
124
125
		$config_vars[] = $txt['cache_sqlite_settings'];
126
		$config_vars[] = array('cachedir_sqlite', $txt['cachedir_sqlite'], 'file', 'text', 36, 'cache_sqlite_cachedir');
127
128
		if (!isset($context['settings_post_javascript']))
129
			$context['settings_post_javascript'] = '';
130
131
		$context['settings_post_javascript'] .= '
132
			$("#cache_accelerator").change(function (e) {
133
				var cache_type = e.currentTarget.value;
134
				$("#cachedir_sqlite").prop("disabled", cache_type != "sqlite");
135
			});';
136
	}
137
138
	/**
139
	 * Sets the $cachedir or uses the SMF default $cachedir..
140
	 *
141
	 * @access public
142
	 *
143
	 * @param string $dir A valid path
0 ignored issues
show
Documentation introduced by
Should the type for parameter $dir not be string|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
144
	 *
145
	 * @return boolean If this was successful or not.
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|null?

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...
146
	 */
147 View Code Duplication
	public function setCachedir($dir = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
148
	{
149
		global $cachedir_sqlite;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
150
151
		// If its invalid, use SMF's.
152
		if (is_null($dir) || !is_writable($dir))
153
			$this->cachedir = $cachedir_sqlite;
154
		else
155
			$this->cachedir = $dir;
156
	}
157
158
	/**
159
	 * {@inheritDoc}
160
	 */
161
	public function getVersion()
162
	{
163
		$temp = $this->cacheDB->version();
164
		return $temp['versionString'];
165
	}
166
}
167
168
?>