Issues (40)

Security Analysis    no request data  

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

src/JsonFileStore.php (12 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of the webmozart/key-value-store package.
5
 *
6
 * (c) Bernhard Schussek <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Webmozart\KeyValueStore;
13
14
use stdClass;
15
use Webmozart\Assert\Assert;
16
use Webmozart\Json\DecodingFailedException;
17
use Webmozart\Json\EncodingFailedException;
18
use Webmozart\Json\FileNotFoundException;
19
use Webmozart\Json\IOException;
20
use Webmozart\Json\JsonDecoder;
21
use Webmozart\Json\JsonEncoder;
22
use Webmozart\KeyValueStore\Api\CountableStore;
23
use Webmozart\KeyValueStore\Api\NoSuchKeyException;
24
use Webmozart\KeyValueStore\Api\ReadException;
25
use Webmozart\KeyValueStore\Api\SortableStore;
26
use Webmozart\KeyValueStore\Api\UnsupportedValueException;
27
use Webmozart\KeyValueStore\Api\WriteException;
28
use Webmozart\KeyValueStore\Util\KeyUtil;
29
use Webmozart\KeyValueStore\Util\Serializer;
30
31
/**
32
 * A key-value store backed by a JSON file.
33
 *
34
 * @since  1.0
35
 *
36
 * @author Bernhard Schussek <[email protected]>
37
 */
38
class JsonFileStore implements SortableStore, CountableStore
39
{
40
    /**
41
     * Flag: Disable serialization of strings.
42
     */
43
    const NO_SERIALIZE_STRINGS = 1;
44
45
    /**
46
     * Flag: Disable serialization of arrays.
47
     */
48
    const NO_SERIALIZE_ARRAYS = 2;
49
50
    /**
51
     * Flag: Escape ">" and "<".
52
     */
53
    const ESCAPE_GT_LT = 4;
54
55
    /**
56
     * Flag: Escape "&".
57
     */
58
    const ESCAPE_AMPERSAND = 8;
59
60
    /**
61
     * Flag: Escape single quotes.
62
     */
63
    const ESCAPE_SINGLE_QUOTE = 16;
64
65
    /**
66
     * Flag: Escape double quotes.
67
     */
68
    const ESCAPE_DOUBLE_QUOTE = 32;
69
70
    /**
71
     * Flag: Don't escape forward slashes.
72
     */
73
    const NO_ESCAPE_SLASH = 64;
74
75
    /**
76
     * Flag: Don't escape Unicode characters.
77
     */
78
    const NO_ESCAPE_UNICODE = 128;
79
80
    /**
81
     * Flag: Format the JSON nicely.
82
     */
83
    const PRETTY_PRINT = 256;
84
85
    /**
86
     * Flag: Terminate the JSON with a line feed.
87
     */
88
    const TERMINATE_WITH_LINE_FEED = 512;
89
90
    /**
91
     * This seems to be the biggest float supported by json_encode()/json_decode().
92
     */
93
    const MAX_FLOAT = 1.0E+14;
94
95
    /**
96
     * @var string
97
     */
98
    private $path;
99
100
    /**
101
     * @var int
102
     */
103
    private $flags;
104
105
    /**
106
     * @var JsonEncoder
107
     */
108
    private $encoder;
109
110
    /**
111
     * @var JsonDecoder
112
     */
113
    private $decoder;
114
115 115
    public function __construct($path, $flags = 0)
116
    {
117 115
        Assert::string($path, 'The path must be a string. Got: %s');
118 115
        Assert::notEmpty($path, 'The path must not be empty.');
119 115
        Assert::integer($flags, 'The flags must be an integer. Got: %s');
120
121 115
        $this->path = $path;
122 115
        $this->flags = $flags;
123
124 115
        $this->encoder = new JsonEncoder();
125 115
        $this->encoder->setEscapeGtLt($this->flags & self::ESCAPE_GT_LT);
0 ignored issues
show
$this->flags & self::ESCAPE_GT_LT is of type integer, but the function expects a boolean.

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...
126 115
        $this->encoder->setEscapeAmpersand($this->flags & self::ESCAPE_AMPERSAND);
0 ignored issues
show
$this->flags & self::ESCAPE_AMPERSAND is of type integer, but the function expects a boolean.

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...
127 115
        $this->encoder->setEscapeSingleQuote($this->flags & self::ESCAPE_SINGLE_QUOTE);
0 ignored issues
show
$this->flags & self::ESCAPE_SINGLE_QUOTE is of type integer, but the function expects a boolean.

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...
128 115
        $this->encoder->setEscapeDoubleQuote($this->flags & self::ESCAPE_DOUBLE_QUOTE);
0 ignored issues
show
$this->flags & self::ESCAPE_DOUBLE_QUOTE is of type integer, but the function expects a boolean.

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...
129 115
        $this->encoder->setEscapeSlash(!($this->flags & self::NO_ESCAPE_SLASH));
130 115
        $this->encoder->setEscapeUnicode(!($this->flags & self::NO_ESCAPE_UNICODE));
131 115
        $this->encoder->setPrettyPrinting($this->flags & self::PRETTY_PRINT);
0 ignored issues
show
$this->flags & self::PRETTY_PRINT is of type integer, but the function expects a boolean.

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...
132 115
        $this->encoder->setTerminateWithLineFeed($this->flags & self::TERMINATE_WITH_LINE_FEED);
0 ignored issues
show
$this->flags & self::TERMINATE_WITH_LINE_FEED is of type integer, but the function expects a boolean.

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...
133
134 115
        $this->decoder = new JsonDecoder();
135 115
        $this->decoder->setObjectDecoding(JsonDecoder::ASSOC_ARRAY);
136 115
    }
137
138
    /**
139
     * {@inheritdoc}
140
     */
141 85
    public function set($key, $value)
142
    {
143 85
        KeyUtil::validate($key);
144
145 83
        if (is_float($value) && $value > self::MAX_FLOAT) {
146 1
            throw new UnsupportedValueException('The JSON file store cannot handle floats larger than 1.0E+14.');
147
        }
148
149 82
        $data = $this->load();
150 82
        $data[$key] = $this->serializeValue($value);
151
152 80
        $this->save($data);
153 76
    }
154
155
    /**
156
     * {@inheritdoc}
157
     */
158 25 View Code Duplication
    public function get($key, $default = null)
0 ignored issues
show
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...
159
    {
160 25
        KeyUtil::validate($key);
161
162 23
        $data = $this->load();
163
164 21
        if (!array_key_exists($key, $data)) {
165 1
            return $default;
166
        }
167
168 20
        return $this->unserializeValue($data[$key]);
169
    }
170
171
    /**
172
     * {@inheritdoc}
173
     */
174 32 View Code Duplication
    public function getOrFail($key)
0 ignored issues
show
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...
175
    {
176 32
        KeyUtil::validate($key);
177
178 30
        $data = $this->load();
179
180 28
        if (!array_key_exists($key, $data)) {
181 1
            throw NoSuchKeyException::forKey($key);
182
        }
183
184 27
        return $this->unserializeValue($data[$key]);
185
    }
186
187
    /**
188
     * {@inheritdoc}
189
     */
190 15
    public function getMultiple(array $keys, $default = null)
191
    {
192 15
        $values = array();
193 15
        $data = $this->load();
194
195 13
        foreach ($keys as $key) {
196 13
            KeyUtil::validate($key);
197
198 13
            if (array_key_exists($key, $data)) {
199 13
                $value = $this->unserializeValue($data[$key]);
200
            } else {
201 1
                $value = $default;
202
            }
203
204 12
            $values[$key] = $value;
205
        }
206
207 10
        return $values;
208
    }
209
210
    /**
211
     * {@inheritdoc}
212
     */
213 32
    public function getMultipleOrFail(array $keys)
214
    {
215 32
        $values = array();
216 32
        $data = $this->load();
217
218 30
        foreach ($keys as $key) {
219 30
            KeyUtil::validate($key);
220
221 30
            if (!array_key_exists($key, $data)) {
222 1
                throw NoSuchKeyException::forKey($key);
223
            }
224
225 30
            $values[$key] = $this->unserializeValue($data[$key]);
226
        }
227
228 26
        return $values;
229
    }
230
231
    /**
232
     * {@inheritdoc}
233
     */
234 11 View Code Duplication
    public function remove($key)
0 ignored issues
show
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...
235
    {
236 11
        KeyUtil::validate($key);
237
238 9
        $data = $this->load();
239
240 9
        if (!array_key_exists($key, $data)) {
241 7
            return false;
242
        }
243
244 9
        unset($data[$key]);
245
246 9
        $this->save($data);
247
248 8
        return true;
249
    }
250
251
    /**
252
     * {@inheritdoc}
253
     */
254 28
    public function exists($key)
255
    {
256 28
        KeyUtil::validate($key);
257
258 26
        $data = $this->load();
259
260 25
        return array_key_exists($key, $data);
261
    }
262
263
    /**
264
     * {@inheritdoc}
265
     */
266 115
    public function clear()
267
    {
268 115
        $this->save(new stdClass());
269 115
    }
270
271
    /**
272
     * {@inheritdoc}
273
     */
274 10
    public function keys()
275
    {
276 10
        return array_keys($this->load());
277
    }
278
279
    /**
280
     * {@inheritdoc}
281
     */
282 8
    public function sort($flags = SORT_REGULAR)
283
    {
284 8
        $data = $this->load();
285
286 7
        ksort($data, $flags);
287
288 7
        $this->save($data);
289 6
    }
290
291
    /**
292
     * {@inheritdoc}
293
     */
294 2
    public function count()
295
    {
296 2
        $data = $this->load();
297
298 1
        return count($data);
299
    }
300
301 102
    private function load()
302
    {
303
        try {
304 102
            return $this->decoder->decodeFile($this->path);
305 95
        } catch (FileNotFoundException $e) {
306 83
            return array();
307 12
        } catch (DecodingFailedException $e) {
308 4
            throw new ReadException($e->getMessage(), 0, $e);
309 8
        } catch (IOException $e) {
310 8
            throw new ReadException($e->getMessage(), 0, $e);
311
        }
312
    }
313
314 115
    private function save($data)
315
    {
316
        try {
317 115
            $this->encoder->encodeFile($data, $this->path);
318 7
        } catch (EncodingFailedException $e) {
319 3
            if (JSON_ERROR_UTF8 === $e->getCode()) {
320 3
                throw UnsupportedValueException::forType('binary', $this);
321
            }
322
323
            throw new WriteException($e->getMessage(), 0, $e);
324 4
        } catch (IOException $e) {
325 4
            throw new WriteException($e->getMessage(), 0, $e);
326
        }
327 115
    }
328
329 82
    private function serializeValue($value)
0 ignored issues
show
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
330
    {
331
        // Serialize if we have a string and string serialization is enabled...
332 82
        $serializeValue = (is_string($value) && !($this->flags & self::NO_SERIALIZE_STRINGS))
333
            // or we have an array and array serialization is enabled...
334 36
            || (is_array($value) && !($this->flags & self::NO_SERIALIZE_ARRAYS))
335
            // or we have any other non-scalar, non-null value
336 82
            || (null !== $value && !is_scalar($value) && !is_array($value));
337
338 82
        if ($serializeValue) {
339 56
            return Serializer::serialize($value);
340
        }
341
342
        // If we have an array and array serialization is disabled, serialize
343
        // its entries if necessary
344 28
        if (is_array($value)) {
345 1
            return array_map(array($this, 'serializeValue'), $value);
346
        }
347
348 28
        return $value;
349
    }
350
351 61
    private function unserializeValue($value)
0 ignored issues
show
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
352
    {
353
        // Unserialize value if it is a string...
354 61
        $unserializeValue = is_string($value) && (
355
            // and string serialization is enabled
356 49
            !($this->flags & self::NO_SERIALIZE_STRINGS)
357
            // or the string contains a serialized object
358 15
            || 'O:' === ($prefix = substr($value, 0, 2))
359
            // or the string contains a serialized array when array
360
            // serialization is enabled
361 61
            || ('a:' === $prefix && !($this->flags & self::NO_SERIALIZE_ARRAYS))
0 ignored issues
show
The variable $prefix 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...
362
        );
363
364 61
        if ($unserializeValue) {
365 35
            return Serializer::unserialize($value);
366
        }
367
368 28
        if (is_array($value)) {
369 1
            return array_map(array($this, 'unserializeValue'), $value);
370
        }
371
372 28
        return $value;
373
    }
374
}
375