1 <?php
2
3 namespace Alo\Statics;
4
5 if(!defined('GEN_START')) {
6 http_response_code(404);
7 die();
8 }
9
10 /**
11 * Format validation statics
12 *
13 * @author Art <a.molcanovas@gmail.com>
14 * @package Statics
15 */
16 class Format {
17
18 /**
19 * Defines an method as "serialize"
20 *
21 * @var int
22 */
23 const M_SERIALIZE = 0;
24
25 /**
26 * Defines a method as "json_encode"
27 *
28 * @var int
29 */
30 const M_JSON = 1;
31
32 /**
33 * Defines a method as "print_r"
34 *
35 * @var int
36 */
37 const M_PRINT_R = 2;
38
39 /**
40 * Checks whether the data is valid JSON
41 *
42 * @author Art <a.molcanovas@gmail.com>
43 *
44 * @param mixed $data The data to check
45 *
46 * @return boolean
47 */
48 static function isJSON($data) {
49 if(!is_scalar($data)) {
50 return false;
51 } else {
52 json_decode($data, true);
53
54 return json_last_error() === JSON_ERROR_NONE;
55 }
56 }
57
58 /**
59 * Checks if the supplied string is a valid IPv4 IP
60 *
61 * @author Art <a.molcanovas@gmail.com>
62 *
63 * @param string $input The input
64 *
65 * @return bool
66 */
67 static function is_ipv4_ip($input) {
68 if(!is_scalar($input)) {
69 return false;
70 } else {
71 $e = explode('.', explode('/', $input)[0]);
72
73 if(count($e) != 4) {
74 return false;
75 } else {
76 foreach($e as $v) {
77 if(!is_numeric($v)) {
78 return false;
79 } else {
80 $v = (int)$v;
81
82 if($v < 0 || $v > 255) {
83 return false;
84 }
85 }
86 }
87 }
88
89 return true;
90 }
91 }
92
93 /**
94 * Makes output scalar. If $input is already scalar, simply returns it; otherwise uses a function specified in
95 * $prettify_method to make the output scalar
96 *
97 * @param mixed $input The input to scalarise
98 * @param int $prettify_method Function to use to make output scalar if $input isn't already scalar. See class
99 * M_* constants.
100 *
101 * @return string
102 */
103 static function scalarOutput($input, $prettify_method = self::M_PRINT_R) {
104 if(is_scalar($input)) {
105 return $input;
106 } else {
107 switch($prettify_method) {
108 case self::M_JSON:
109 return json_encode($input);
110 case self::M_SERIALIZE:
111 return serialize($input);
112 default:
113 return print_r($input, true);
114 }
115 }
116 }
117
118 /**
119 * Typecasts a variable to float or int if it's numeric
120 *
121 * @author Art <a.molcanovas@gmail.com>
122 *
123 * @param mixed $var The variable
124 * @param boolean $boolMode Whether we're checking for boolean mode FULLTEXT search values
125 *
126 * @return int|float|mixed
127 */
128 static function makeNumeric($var, $boolMode = false) {
129 if(is_numeric($var)) {
130 if($boolMode) {
131 $first = substr($var, 0, 1);
132 if($first == '-' || $first == '+') {
133 return $var;
134 }
135 }
136
137 if(stripos($var, '.') === false) {
138 $var = (int)$var;
139 } else {
140 $var = (float)$var;
141 }
142 }
143
144 return $var;
145 }
146
147 }