Passed
Push — master ( a357e7...195a07 )
by Anton
04:22 queued 01:11
created

JSON   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 61
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 7
lcom 0
cbo 2
dl 0
loc 61
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A parse() 0 4 1
A stringify() 0 4 1
A load() 0 6 2
A save() 0 6 2
A output() 0 6 1
1
<?php
2
3
/**
4
 * @package Framework\JSON
5
 * @author Anton Romanov
6
 * @copyright Copyright (c) 2015-2016, Anton Romanov
7
 * @link http://cadmium-cms.com
8
 */
9
10
namespace {
11
12
	abstract class JSON {
13
14
		/**
15
		 * Parse a string as JSON
16
		 *
17
		 * @return the JSON value or null on failure
18
		 */
19
20
		public static function parse(string $string) {
21
22
			return json_decode($string, true);
23
		}
24
25
		/**
26
		 * Convert a JSON value to a string
27
		 *
28
		 * @return the string or false on failure
29
		 */
30
31
		public static function stringify($value) {
32
33
			return json_encode($value, (JSON_PRETTY_PRINT | JSON_PARTIAL_OUTPUT_ON_ERROR));
34
		}
35
36
		/**
37
		 * Load a JSON value from a file
38
		 *
39
		 * @return the JSON value or null on failure
40
		 */
41
42
		public static function load(string $file_name) {
43
44
			if (false === ($contents = Explorer::getContents($file_name))) return null;
45
46
			return self::parse($contents);
47
		}
48
49
		/**
50
		 * Save a JSON value into a file
51
		 *
52
		 * @return the number of bytes that were written to the file or false on failure
53
		 */
54
55
		public static function save(string $file_name, $value) {
56
57
			if (false === ($value = self::stringify($value))) return false;
58
59
			return Explorer::putContents($file_name, $value);
60
		}
61
62
		/**
63
		 * Output JSON
64
		 */
65
66
		public static function output($value) {
67
68
			Headers::sendNoCache(); Headers::sendStatus(STATUS_CODE_200); Headers::sendContent(MIME_TYPE_JSON);
69
70
			echo self::stringify($value);
71
		}
72
	}
73
}
74