Checks if the types of the passed arguments in a function/method call are compatible.
1 | <?php |
||||||
2 | |||||||
3 | /* |
||||||
4 | * This file is part of the Ocrend Framewok 3 package. |
||||||
5 | * |
||||||
6 | * (c) Ocrend Software <[email protected]> |
||||||
7 | * |
||||||
8 | * For the full copyright and license information, please view the LICENSE |
||||||
9 | * file that was distributed with this source code. |
||||||
10 | */ |
||||||
11 | |||||||
12 | namespace Ocrend\Kernel\Helpers; |
||||||
13 | |||||||
14 | /** |
||||||
15 | * Funciones reutilizables dentro del sistema. |
||||||
16 | * |
||||||
17 | * @author Brayan Narváez <[email protected]> |
||||||
18 | */ |
||||||
19 | |||||||
20 | final class Functions extends \Twig_Extension { |
||||||
21 | |||||||
22 | /** |
||||||
23 | * Verifica parte de una fecha, método privado usado en str_to_time |
||||||
24 | * |
||||||
25 | * @param int $index: Índice del arreglo |
||||||
26 | * @param array $detail: Arreglo |
||||||
27 | * @param int $max: Valor a comparar |
||||||
28 | * |
||||||
29 | * @return bool con el resultado de la comparación |
||||||
30 | */ |
||||||
31 | private static function check_str_to_time(int $index, array $detail, int $max) : bool { |
||||||
32 | return !array_key_exists($index,$detail) || !is_numeric($detail[$index]) || intval($detail[$index]) < $max; |
||||||
33 | } |
||||||
34 | |||||||
35 | /** |
||||||
36 | * Verifica la fecha completa |
||||||
37 | * |
||||||
38 | * @param array $detail: Arreglo |
||||||
39 | * |
||||||
40 | * @return bool |
||||||
41 | */ |
||||||
42 | private static function check_time(array $detail) : bool { |
||||||
43 | return self::check_str_to_time(0,$detail,1) || self::check_str_to_time(1,$detail,1) || intval($detail[1]) > 12 || self::check_str_to_time(2,$detail,1970); |
||||||
44 | } |
||||||
45 | |||||||
46 | /** |
||||||
47 | * Redirecciona a una URL |
||||||
48 | * |
||||||
49 | * @param string $url: Sitio a donde redireccionará, si no se pasa, por defecto |
||||||
50 | * se redirecciona a la URL principal del sitio |
||||||
51 | * |
||||||
52 | * @return void |
||||||
53 | */ |
||||||
54 | public static function redir($url = null) { |
||||||
55 | global $config; |
||||||
56 | |||||||
57 | if (null == $url) { |
||||||
58 | $url = $config['build']['url']; |
||||||
59 | } |
||||||
60 | |||||||
61 | \Symfony\Component\HttpFoundation\RedirectResponse::create($url)->send(); |
||||||
62 | } |
||||||
63 | |||||||
64 | /** |
||||||
65 | * Calcula el porcentaje de una cantidad |
||||||
66 | * |
||||||
67 | * @param float $por: El porcentaje a evaluar, por ejemplo 1, 20, 30 % sin el "%", sólamente el número |
||||||
68 | * @param float $n: El número al cual se le quiere sacar el porcentaje |
||||||
69 | * |
||||||
70 | * @return float con el porcentaje correspondiente |
||||||
71 | */ |
||||||
72 | public static function percent(float $por, float $n) : float { |
||||||
73 | return $n*($por/100); |
||||||
74 | } |
||||||
75 | |||||||
76 | /** |
||||||
77 | * Da unidades de peso a un integer según sea su tamaño asumida en bytes |
||||||
78 | * |
||||||
79 | * @param int $size: Un entero que representa el tamaño a convertir |
||||||
80 | * |
||||||
81 | * @return string del tamaño $size convertido a la unidad más adecuada |
||||||
82 | */ |
||||||
83 | public static function convert(int $size) : string { |
||||||
84 | $unit = array('bytes', 'kb', 'mb', 'gb', 'tb', 'pb'); |
||||||
85 | return round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i]; |
||||||
86 | } |
||||||
87 | |||||||
88 | /** |
||||||
89 | * Retorna la URL de un gravatar, según el email |
||||||
90 | * |
||||||
91 | * @param string $email: El email del usuario a extraer el gravatar |
||||||
92 | * @param int $size: El tamaño del gravatar |
||||||
93 | * @return string con la URl |
||||||
94 | */ |
||||||
95 | public static function get_gravatar(string $email, int $size = 35) : string { |
||||||
96 | return 'http://www.gravatar.com/avatar/' . md5($email) . '?s=' . (int) abs($size) . '?d=robohash'; |
||||||
97 | } |
||||||
98 | |||||||
99 | |||||||
100 | /** |
||||||
101 | * Alias de Empty, más completo |
||||||
102 | * |
||||||
103 | * @param mixed $var: Variable a analizar |
||||||
104 | * |
||||||
105 | * @return bool con true si está vacío, false si no, un espacio en blanco cuenta como vacío |
||||||
106 | */ |
||||||
107 | public static function emp($var) : bool { |
||||||
108 | return (null === $var || empty(trim(str_replace(' ','',$var)))); |
||||||
109 | } |
||||||
110 | |||||||
111 | //------------------------------------------------ |
||||||
112 | |||||||
113 | /** |
||||||
114 | * Aanaliza que TODOS los elementos de un arreglo estén llenos, útil para analizar por ejemplo que todos los elementos de un formulario esté llenos |
||||||
115 | * pasando como parámetro $_POST |
||||||
116 | * |
||||||
117 | * @param array $array, arreglo a analizar |
||||||
118 | * |
||||||
119 | * @return bool con true si están todos llenos, false si al menos uno está vacío |
||||||
120 | */ |
||||||
121 | public static function all_full(array $array) : bool { |
||||||
122 | foreach($array as $e) { |
||||||
123 | if(self::emp($e) and $e != '0') { |
||||||
124 | return false; |
||||||
125 | } |
||||||
126 | } |
||||||
127 | return true; |
||||||
128 | } |
||||||
129 | |||||||
130 | /** |
||||||
131 | * Alias de Empty() pero soporta más de un parámetro (infinitos) |
||||||
132 | * |
||||||
133 | * @return bool con true si al menos uno está vacío, false si todos están llenos |
||||||
134 | */ |
||||||
135 | public static function e() : bool { |
||||||
136 | for ($i = 0, $nargs = func_num_args(); $i < $nargs; $i++) { |
||||||
137 | if(self::emp(func_get_arg($i)) && func_get_arg($i) != '0') { |
||||||
138 | return true; |
||||||
139 | } |
||||||
140 | } |
||||||
141 | |||||||
142 | return false; |
||||||
143 | } |
||||||
144 | |||||||
145 | |||||||
146 | /** |
||||||
147 | * Alias de date() pero devuele días y meses en español |
||||||
148 | * |
||||||
149 | * @param string $format: Formato de salida (igual que en date()) |
||||||
150 | * @param int $time: Tiempo, por defecto es time() (igual que en date()) |
||||||
151 | * |
||||||
152 | * @return string con la fecha en formato humano (y en español) |
||||||
153 | */ |
||||||
154 | public static function fecha(string $format, int $time = 0) : string { |
||||||
155 | $date = date($format,$time == 0 ? time() : $time); |
||||||
156 | $cambios = array( |
||||||
157 | 'Monday'=> 'Lunes', |
||||||
158 | 'Tuesday'=> 'Martes', |
||||||
159 | 'Wednesday'=> 'Miércoles', |
||||||
160 | 'Thursday'=> 'Jueves', |
||||||
161 | 'Friday'=> 'Viernes', |
||||||
162 | 'Saturday'=> 'Sábado', |
||||||
163 | 'Sunday'=> 'Domingo', |
||||||
164 | 'January'=> 'Enero', |
||||||
165 | 'February'=> 'Febrero', |
||||||
166 | 'March'=> 'Marzo', |
||||||
167 | 'April'=> 'Abril', |
||||||
168 | 'May'=> 'Mayo', |
||||||
169 | 'June'=> 'Junio', |
||||||
170 | 'July'=> 'Julio', |
||||||
171 | 'August'=> 'Agosto', |
||||||
172 | 'September'=> 'Septiembre', |
||||||
173 | 'October'=> 'Octubre', |
||||||
174 | 'November'=> 'Noviembre', |
||||||
175 | 'December'=> 'Diciembre', |
||||||
176 | 'Mon'=> 'Lun', |
||||||
177 | 'Tue'=> 'Mar', |
||||||
178 | 'Wed'=> 'Mie', |
||||||
179 | 'Thu'=> 'Jue', |
||||||
180 | 'Fri'=> 'Vie', |
||||||
181 | 'Sat'=> 'Sab', |
||||||
182 | 'Sun'=> 'Dom', |
||||||
183 | 'Jan'=> 'Ene', |
||||||
184 | 'Aug'=> 'Ago', |
||||||
185 | 'Apr'=> 'Abr', |
||||||
186 | 'Dec'=> 'Dic' |
||||||
187 | ); |
||||||
188 | return str_replace(array_keys($cambios), array_values($cambios), $date); |
||||||
189 | } |
||||||
190 | |||||||
191 | /** |
||||||
192 | * Devuelve la etiqueta <base> html adecuada para que los assets carguen desde allí. |
||||||
193 | * Se adapta a la configuración del dominio en general. |
||||||
194 | * |
||||||
195 | * @return string <base href="ruta" /> |
||||||
196 | */ |
||||||
197 | public static function base_assets() : string { |
||||||
198 | global $config, $http; |
||||||
199 | |||||||
200 | # Revisar protocolo |
||||||
201 | $https = 'http://'; |
||||||
202 | if($config['router']['ssl']) { |
||||||
203 | # Revisar el protocolo |
||||||
204 | if(true == $http->server->get('HTTPS') |
||||||
205 | || $http->server->get('HTTPS') == 'on' |
||||||
206 | || $http->server->get('HTTPS') == 1) { |
||||||
207 | $https = 'https://'; |
||||||
208 | } |
||||||
209 | } |
||||||
210 | |||||||
211 | # Revisar el path |
||||||
212 | $path = $config['router']['path']; |
||||||
213 | if('/' != substr($path, -1)) { |
||||||
214 | $path .= '/'; |
||||||
215 | } |
||||||
216 | |||||||
217 | # Revisar subdominio |
||||||
218 | $www = substr($http->server->get('SERVER_NAME'), 0, 2); |
||||||
219 | $base = $path; |
||||||
220 | if (strtolower($www) == 'www') { |
||||||
221 | $base = 'www.' . $path; |
||||||
222 | } |
||||||
223 | |||||||
224 | return '<base href="' . $https . $base . '" />'; |
||||||
225 | } |
||||||
226 | |||||||
227 | /** |
||||||
228 | * Obtiene el último día de un mes específico |
||||||
229 | * |
||||||
230 | * @param int $mes: Mes (1 a 12) |
||||||
231 | * @param int $anio: Año (1975 a 2xxx) |
||||||
232 | * |
||||||
233 | * @return string con el número del día |
||||||
234 | */ |
||||||
235 | public static function last_day_month(int $mes, int $anio) : string { |
||||||
236 | return date('d', (mktime(0,0,0,$mes + 1, 1, $anio) - 1)); |
||||||
237 | } |
||||||
238 | |||||||
239 | /** |
||||||
240 | * Pone un cero a la izquierda si la cifra es menor a diez |
||||||
241 | * |
||||||
242 | * @param int $num: cifra |
||||||
243 | * |
||||||
244 | * @return string cifra con cero a la izquirda |
||||||
245 | */ |
||||||
246 | public static function cero_izq(int $num) : string { |
||||||
247 | return (string) ($num < 10 ? '0' . $num : $num); |
||||||
248 | } |
||||||
249 | |||||||
250 | /** |
||||||
251 | * Devuelve el timestamp de una fecha, y null si su formato es incorrecto. |
||||||
252 | * |
||||||
253 | * @param string|null $fecha: Fecha con formato dd/mm/yy |
||||||
254 | * @param string $hora: Hora de inicio de la $fecha |
||||||
255 | * |
||||||
256 | * @return int|null con el timestamp |
||||||
257 | */ |
||||||
258 | public static function str_to_time($fecha, string $hora = '00:00:00') { |
||||||
259 | $detail = explode('/',$fecha ?? ''); |
||||||
260 | |||||||
261 | // Formato de día incorrecto, mes y año incorrectos |
||||||
262 | if(self::check_time($detail)) { |
||||||
263 | return null; |
||||||
264 | } |
||||||
265 | |||||||
266 | // Verificar días según año y mes |
||||||
267 | $day = intval($detail[0]); |
||||||
268 | $month = intval($detail[1]); |
||||||
269 | $year = intval($detail[2]); |
||||||
270 | |||||||
271 | // Veriricar dia según mes |
||||||
272 | if ($day > self::last_day_month($month, $year)) { |
||||||
273 | return null; |
||||||
274 | } |
||||||
275 | |||||||
276 | return strtotime($detail[0] . '-' . $detail[1] . '-' . $detail[2] . ' ' . $hora); |
||||||
277 | } |
||||||
278 | |||||||
279 | /** |
||||||
280 | * Devuelve la fecha en format dd/mm/yyy desde el principio de la semana, mes o año actual. |
||||||
281 | * |
||||||
282 | * @param int $desde: Desde donde |
||||||
283 | * |
||||||
284 | * @return mixed |
||||||
285 | */ |
||||||
286 | public static function desde_date(int $desde) { |
||||||
287 | # Obtener esta fecha |
||||||
288 | $hoy = date('d/m/Y/D', time()); |
||||||
289 | $hoy = explode('/', $hoy); |
||||||
290 | |||||||
291 | # Arreglo de condiciones y subcondiciones |
||||||
292 | $fecha = array( |
||||||
293 | 1 => date('d/m/Y', time()), |
||||||
294 | 2 => date('d/m/Y', time() - (60*60*24)), |
||||||
295 | 3 => array( |
||||||
296 | 'Mon' => $hoy[0], |
||||||
297 | 'Tue' => intval($hoy[0]) - 1, |
||||||
298 | 'Wed' => intval($hoy[0]) - 2, |
||||||
299 | 'Thu' => intval($hoy[0]) - 3, |
||||||
300 | 'Fri' => intval($hoy[0]) - 4, |
||||||
301 | 'Sat' => intval($hoy[0]) - 5, |
||||||
302 | 'Sun' => intval($hoy[0]) - 6 |
||||||
303 | ), |
||||||
304 | 4 => '01/'. self::cero_izq($hoy[1]) .'/' . $hoy[2], |
||||||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||||||
305 | 5 => '01/01/' . $hoy[2] |
||||||
306 | ); |
||||||
307 | |||||||
308 | if($desde == 3) { |
||||||
309 | # Dia actual |
||||||
310 | $dia = $fecha[3][$hoy[3]]; |
||||||
311 | |||||||
312 | # Mes anterior y posiblemente, año también. |
||||||
313 | if($dia == 0) { |
||||||
314 | # Restante de la fecha |
||||||
315 | $real_fecha = self::last_day_month($hoy[1],$hoy[2]) .'/'. self::cero_izq($hoy[1] - 1) .'/'; |
||||||
0 ignored issues
–
show
$hoy[2] of type string is incompatible with the type integer expected by parameter $anio of Ocrend\Kernel\Helpers\Functions::last_day_month() .
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
Loading history...
$hoy[1] of type string is incompatible with the type integer expected by parameter $mes of Ocrend\Kernel\Helpers\Functions::last_day_month() .
(
Ignorable by Annotation
)
If this is a false-positive, you can also ignore this issue in your code via the
Loading history...
|
|||||||
316 | |||||||
317 | # Verificamos si estamos en enero |
||||||
318 | if($hoy[1] == 1) { |
||||||
319 | return $real_fecha . ($hoy[2] - 1); |
||||||
320 | } |
||||||
321 | |||||||
322 | # Si no es enero, es el año actual |
||||||
323 | return $real_fecha . $hoy[2]; |
||||||
324 | } |
||||||
325 | |||||||
326 | return self::cero_izq($dia) .'/'. self::cero_izq($hoy[1]) .'/' . $hoy[2]; |
||||||
327 | } else if(array_key_exists($desde,$fecha)) { |
||||||
328 | return $fecha[$desde]; |
||||||
329 | } |
||||||
330 | |||||||
331 | throw new \RuntimeException('Problema con el valor $desde en desde_date()'); |
||||||
332 | } |
||||||
333 | |||||||
334 | /** |
||||||
335 | * Obtiene el tiempo actual |
||||||
336 | * |
||||||
337 | * @return int devuelve time() |
||||||
338 | */ |
||||||
339 | public static function timestamp() : int { |
||||||
340 | return time(); |
||||||
341 | } |
||||||
342 | |||||||
343 | /** |
||||||
344 | * Se obtiene de Twig_Extension y sirve para que cada función esté disponible como etiqueta en twig |
||||||
345 | * |
||||||
346 | * @return array con todas las funciones con sus respectivos nombres de acceso en plantillas twig |
||||||
347 | */ |
||||||
348 | public function getFunctions() : array { |
||||||
349 | return array( |
||||||
350 | new \Twig_Function('percent', array($this, 'percent')), |
||||||
351 | new \Twig_Function('convert', array($this, 'convert')), |
||||||
352 | new \Twig_Function('get_gravatar', array($this, 'get_gravatar')), |
||||||
353 | new \Twig_Function('emp', array($this, 'emp')), |
||||||
354 | new \Twig_Function('e_dynamic', array($this, 'e')), |
||||||
355 | new \Twig_Function('all_full', array($this, 'all_full')), |
||||||
356 | new \Twig_Function('fecha', array($this, 'fecha')), |
||||||
357 | new \Twig_Function('base_assets', array($this, 'base_assets')), |
||||||
358 | new \Twig_Function('timestamp', array($this, 'timestamp')), |
||||||
359 | new \Twig_Function('desde_date', array($this, 'desde_date')), |
||||||
360 | new \Twig_Function('cero_izq', array($this, 'cero_izq')), |
||||||
361 | new \Twig_Function('last_day_month', array($this, 'last_day_month')), |
||||||
362 | new \Twig_Function('str_to_time', array($this, 'str_to_time')), |
||||||
363 | new \Twig_Function('desde_date', array($this, 'desde_date')) |
||||||
364 | ); |
||||||
365 | } |
||||||
366 | |||||||
367 | /** |
||||||
368 | * Identificador único para la extensión de twig |
||||||
369 | * |
||||||
370 | * @return string con el nombre de la extensión |
||||||
371 | */ |
||||||
372 | public function getName() : string { |
||||||
373 | return 'ocrend_framework_func_class'; |
||||||
374 | } |
||||||
375 | } |
||||||
376 |