Completed
Push — master ( 5af85c...a1d55c )
by Michael
02:04
created

JsonDecodeFile::call()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 4
rs 10
1
<?php
2
3
namespace Schnittstabil\JsonDecodeFile;
4
5
use KHerGe\File\File;
6
use KHerGe\File\FileException;
7
use Seld\JsonLint\JsonParser;
8
use Seld\JsonLint\ParsingException;
9
use duncan3dc\Bom\Util as BomUtil;
10
11
/**
12
 * Read and decode JSON files.
13
 */
14
class JsonDecodeFile
15
{
16
    /**
17
     * Reads entire file into a string.
18
     *
19
     * @param string $path the file path
20
     *
21
     * @return string the read data
22
     *
23
     * @throws FileException
24
     */
25
    protected static function readFile($path)
26
    {
27
        $file = new File($path, 'r');
28
        $size = $file->getSize();
29
30
        if ($size === 0) {
31
            return '';
32
        }
33
34
        return $file->fread($size);
0 ignored issues
show
Bug introduced by
The method fread() does not seem to exist on object<KHerGe\File\File>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
35
    }
36
37
    /**
38
     * Converts JSON encoded string into a PHP variable.
39
     *
40
     * @param string $json  JSON string
41
     * @param bool   $assoc returned objects will be converted into associative arrays
42
     *
43
     * @return mixed the value encoded in json in appropriate PHP type
44
     *
45
     * @throws ParsingException
46
     *
47
     * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
48
     */
49
    protected static function parse($json, $assoc = false)
50
    {
51
        $falgs = JsonParser::DETECT_KEY_CONFLICTS;
52
53
        if ($assoc) {
54
            $falgs |= JsonParser::PARSE_TO_ASSOC;
55
        }
56
57
        $parser = new JsonParser();
58
59
        return $parser->parse($json, $falgs);
60
    }
61
62
    /**
63
     * Read and decode a JSON file.
64
     *
65
     * @see http://php.net/manual/en/function.json-decode.php json_decode documentation
66
     *
67
     * @param string $path  the file path
68
     * @param bool   $assoc returned objects will be converted into associative arrays
69
     *
70
     * @return mixed the value encoded in json in appropriate PHP type
71
     *
72
     * @throws FileException
73
     * @throws ParsingException
74
     *
75
     * @SuppressWarnings(PHPMD.BooleanArgumentFlag)
76
     * @SuppressWarnings(PHPMD.StaticAccess)
77
     */
78
    public static function call($path, $assoc = false)
79
    {
80
        return self::parse(BomUtil::removeBom(self::readFile($path)), $assoc);
81
    }
82
}
83