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 * @param mixed $data The data to check
44 * @return boolean
45 */
46 static function isJSON($data) {
47 if (!is_scalar($data)) {
48 return false;
49 } else {
50 json_decode($data, true);
51
52 return json_last_error() === JSON_ERROR_NONE;
53 }
54 }
55
56 /**
57 * Checks if the supplied string is a valid IPv4 IP
58 *
59 * @author Art <a.molcanovas@gmail.com>
60 * @param string $input The input
61 * @return bool
62 */
63 static function is_ipv4_ip($input) {
64 if (!is_scalar($input)) {
65 return false;
66 } else {
67 $e = explode('.', explode('/', $input)[0]);
68
69 if (count($e) != 4) {
70 return false;
71 } else {
72 foreach ($e as $v) {
73 if (!is_numeric($v)) {
74 return false;
75 } else {
76 $v = (int)$v;
77
78 if ($v < 0 || $v > 255) {
79 return false;
80 }
81 }
82 }
83 }
84
85 return true;
86 }
87 }
88
89 /**
90 * Makes output scalar. If $input is already scalar, simply returns it; otherwise uses a function specified in
91 * $prettify_method to make the output scalar
92 *
93 * @param mixed $input The input to scalarise
94 * @param int $prettify_method Function to use to make output scalar if $input isn't already scalar. See class
95 * M_* constants.
96 * @return string
97 */
98 static function scalarOutput($input, $prettify_method = self::M_PRINT_R) {
99 if (is_scalar($input)) {
100 return $input;
101 } else {
102 switch ($prettify_method) {
103 case self::M_JSON:
104 return json_encode($input);
105 case self::M_SERIALIZE:
106 return serialize($input);
107 default:
108 return print_r($input, true);
109 }
110 }
111 }
112
113 /**
114 * Typecasts a variable to float or int if it's numeric
115 *
116 * @author Art <a.molcanovas@gmail.com>
117 * @param mixed $var The variable
118 * @param boolean $boolMode Whether we're checking for boolean mode FULLTEXT search values
119 * @return int|float|mixed
120 */
121 static function makeNumeric($var, $boolMode = false) {
122 if (is_numeric($var)) {
123 if ($boolMode) {
124 $first = substr($var, 0, 1);
125 if ($first == '-' || $first == '+') {
126 return $var;
127 }
128 }
129
130 if (stripos($var, '.') === false) {
131 $var = (int)$var;
132 } else {
133 $var = (float)$var;
134 }
135 }
136
137 return $var;
138 }
139
140 }