Passed
Push — master ( 7ff0ed...264bfe )
by Sheldon
03:28
created

JsonLoader::putContent()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 2
dl 0
loc 11
rs 9.9
c 0
b 0
f 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: sheldon
5
 * Date: 18-6-12
6
 * Time: 下午4:08.
7
 */
8
9
namespace MiotApi\Util\Jsoner;
10
11
use MiotApi\Exception\JsonException;
12
13
class JsonLoader
14
{
15
    /**
16
     * Use redis or file ?
17
     */
18
    const USE_REDIS = true;
19
20
    /**
21
     * Creating JSON file from data.
22
     *
23
     * @param string $data → JSON data
24
     * @param string $file → path to the file
25
     *
26
     * @throws JsonException
27
     *
28
     * @return array
29
     */
30
    public static function dataToFile($data, $file)
31
    {
32
        $array = json_decode($data, true);
33
34
        return self::arrayToFile($array, $file);
35
    }
36
37
    /**
38
     * Creating JSON file from array.
39
     *
40
     * @param array  $array → array to be converted to JSON
41
     * @param string $file  → path to the file
42
     *
43
     * @throws JsonException
44
     *
45
     * @return array
46
     */
47
    public static function arrayToFile($array, $file)
48
    {
49
        self::createDirectory($file);
50
        $lastError = JsonLastError::check();
51
        $json = json_encode($lastError ? $lastError : $array, JSON_PRETTY_PRINT);
52
        self::saveFile($file, $json);
53
        if (is_null($lastError)) {
54
            return $array;
55
        } else {
56
            throw new JsonException($lastError['message'].' '.$file);
57
        }
58
    }
59
60
    /**
61
     * Create directory recursively if it doesn't exist.
62
     *
63
     *
64
     * @param string $file → path to the directory
65
     *
66
     * @throws JsonException → couldn't create directory
67
     */
68
    private static function createDirectory($file)
69
    {
70
        $basename = is_string($file) ? basename($file) : '';
0 ignored issues
show
introduced by
The condition is_string($file) is always true.
Loading history...
71
        $path = str_replace($basename, '', $file);
72
        if (!empty($path) && !is_dir($path)) {
73
            if (!mkdir($path, 0755, true)) {
74
                $message = 'Could not create directory in';
75
76
                throw new JsonException($message.' '.$path);
77
            }
78
        }
79
    }
80
81
    /**
82
     * Save file.
83
     *
84
     *
85
     * @param string $file → path to the file
86
     * @param string $json → json string
87
     *
88
     * @throws JsonException → couldn't create file
89
     */
90
    private static function saveFile($file, $json)
91
    {
92
        if (self::putContent($file, $json) === false) {
0 ignored issues
show
Bug Best Practice introduced by
The method MiotApi\Util\Jsoner\JsonLoader::putContent() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

92
        if (self::/** @scrutinizer ignore-call */ putContent($file, $json) === false) {
Loading history...
93
            $message = 'Could not create file in';
94
95
            throw new JsonException($message.' '.$file);
96
        }
97
    }
98
99
    /**
100
     * Save to array the JSON file content.
101
     *
102
     * @param string $file → path or external url to JSON file
103
     *
104
     * @throws JsonException
105
     *
106
     * @return array|false
107
     */
108
    public static function fileToArray($file)
109
    {
110
        if (!is_file($file) && !filter_var($file, FILTER_VALIDATE_URL)) {
111
            self::arrayToFile([], $file);
112
        }
113
        $json = self::getContent($file);
0 ignored issues
show
Bug Best Practice introduced by
The method MiotApi\Util\Jsoner\JsonLoader::getContent() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

113
        /** @scrutinizer ignore-call */ 
114
        $json = self::getContent($file);
Loading history...
114
        $array = json_decode($json, true);
115
        $lastError = JsonLastError::check();
116
117
        return $array === null || !is_null($lastError) ? false : $array;
118
    }
119
120
    private function putContent($file, $json)
121
    {
122
        if (self::USE_REDIS) {
123
            if (method_exists(Redis::class, 'connection')) {
0 ignored issues
show
Bug introduced by
The type MiotApi\Util\Jsoner\Redis was not found. Did you mean Redis? If so, make sure to prefix the type with \.
Loading history...
124
                $redis = Redis::connection();
125
126
                $file = str_replace(Jsoner::getCacheDir(), 'miot_json_cache:', $file);
127
                $file = str_replace(['/', '\\'], ':', $file);
128
                return $redis->set($file, $json);
129
            } else {
130
                return file_put_contents($file, $json);
131
            }
132
        }
133
    }
134
135
    private function getContent($file)
136
    {
137
        if (self::USE_REDIS) {
138
            if (method_exists(Redis::class, 'connection')) {
139
                $redis = Redis::connection();
140
141
                $file = str_replace(Jsoner::getCacheDir(), 'miot_json_cache:', $file);
142
                $file = str_replace(['/', '\\'], ':', $file);
143
                return $redis->get($file);
144
            } else {
145
                return file_get_contents($file);
146
            }
147
        }
148
    }
149
}
150