-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathJSONChecker.php
More file actions
136 lines (118 loc) · 3.34 KB
/
Copy pathJSONChecker.php
File metadata and controls
136 lines (118 loc) · 3.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
<?php
namespace JSONRulesChecker;
/**
* Class JSONChecker
* @package JSONRulesChecker
*/
class JSONChecker {
public $rules_keys_number;
public $json_keys_number;
const DEFAULT_REGEX = '/.*/';
/**
* @param \stdClass $json
* @param array $rules
* @param array $result
* @return array
*/
private function check(\stdClass $json, array $rules, $result = array()) {
/**
* go through all rules
*/
foreach($rules as $key => $value) {
$this->rules_keys_number++;
if(isset($json->$key)) {
/**
* if value of json key it's array
* then call this function again
*/
if(is_array($value)) {
$result = array_merge($this->check($json->$key, $value, $result), $result);
}
/**
* check the value using rexex
*/
else {
/**
* if rule an empty
* then replace it with default regex
*/
if($value == '') {
$value = self::DEFAULT_REGEX;
}
/**
* check if rule don't match with json
* then push false to the result array
*/
if(!@preg_match($value, $json->$key)) {
$result[] = false;
}
/**
* if preg_match returned true
* then value match to rules
* then push true to the result array
*/
else {
$result[] = true;
}
}
}
else {
$result[] = false;
}
}
return $result;
}
/**
* @param \stdClass $json
*/
public function countJsonKeys(\stdClass $json) {
foreach($json as $key => $value) {
$this->json_keys_number++;
if(is_object($value)) {
$this->countJsonKeys($value);
}
}
}
/**
* invoke this method when you want to validate json
*
* @param \stdClass $json
* @param array $rules
* @param bool $strict
* @return bool
*/
public static function checkJSON(\stdClass $json, array $rules, $strict = false) {
/**
* create object of this class
*/
$checker = new self();
/**
* main function
* invoke it for json checking
*/
$result_array = $checker->check($json, $rules, array());
$checker->countJsonKeys($json);
/**
* if strict option is true then
* check on strict matching
*/
if($strict) {
if($checker->rules_keys_number != $checker->json_keys_number) {
return false;
}
}
/**
* if we don't found the false in the result_array
* then return true
*/
if(array_search(false, $result_array) === false) {
return true;
}
/**
* else return false
*/
else {
return false;
}
}
}