@@ -28,36 +28,36 @@ discard block |
||
| 28 | 28 | |
| 29 | 29 | class Users extends Models implements IModels { |
| 30 | 30 | /** |
| 31 | - * Característica para establecer conexión con base de datos. |
|
| 32 | - */ |
|
| 31 | + * Característica para establecer conexión con base de datos. |
|
| 32 | + */ |
|
| 33 | 33 | use DBModel; |
| 34 | 34 | |
| 35 | 35 | /** |
| 36 | - * Máximos intentos de inincio de sesión de un usuario |
|
| 37 | - * |
|
| 38 | - * @var int |
|
| 39 | - */ |
|
| 36 | + * Máximos intentos de inincio de sesión de un usuario |
|
| 37 | + * |
|
| 38 | + * @var int |
|
| 39 | + */ |
|
| 40 | 40 | const MAX_ATTEMPTS = 5; |
| 41 | 41 | |
| 42 | 42 | /** |
| 43 | - * Tiempo entre máximos intentos en segundos |
|
| 44 | - * |
|
| 45 | - * @var int |
|
| 46 | - */ |
|
| 43 | + * Tiempo entre máximos intentos en segundos |
|
| 44 | + * |
|
| 45 | + * @var int |
|
| 46 | + */ |
|
| 47 | 47 | const MAX_ATTEMPTS_TIME = 120; # (dos minutos) |
| 48 | 48 | |
| 49 | 49 | /** |
| 50 | - * Log de intentos recientes con la forma 'email' => (int) intentos |
|
| 51 | - * |
|
| 52 | - * @var array |
|
| 53 | - */ |
|
| 50 | + * Log de intentos recientes con la forma 'email' => (int) intentos |
|
| 51 | + * |
|
| 52 | + * @var array |
|
| 53 | + */ |
|
| 54 | 54 | private $recentAttempts = array(); |
| 55 | 55 | |
| 56 | - /** |
|
| 57 | - * Hace un set() a la sesión login_user_recentAttempts con el valor actualizado. |
|
| 58 | - * |
|
| 59 | - * @return void |
|
| 60 | - */ |
|
| 56 | + /** |
|
| 57 | + * Hace un set() a la sesión login_user_recentAttempts con el valor actualizado. |
|
| 58 | + * |
|
| 59 | + * @return void |
|
| 60 | + */ |
|
| 61 | 61 | private function updateSessionAttempts() { |
| 62 | 62 | global $session; |
| 63 | 63 | |
@@ -65,13 +65,13 @@ discard block |
||
| 65 | 65 | } |
| 66 | 66 | |
| 67 | 67 | /** |
| 68 | - * Genera la sesión con el id del usuario que ha iniciado |
|
| 69 | - * |
|
| 70 | - * @param string $pass : Contraseña sin encriptar |
|
| 71 | - * @param string $pass_repeat : Contraseña repetida sin encriptar |
|
| 72 | - * |
|
| 73 | - * @throws ModelsException cuando las contraseñas no coinciden |
|
| 74 | - */ |
|
| 68 | + * Genera la sesión con el id del usuario que ha iniciado |
|
| 69 | + * |
|
| 70 | + * @param string $pass : Contraseña sin encriptar |
|
| 71 | + * @param string $pass_repeat : Contraseña repetida sin encriptar |
|
| 72 | + * |
|
| 73 | + * @throws ModelsException cuando las contraseñas no coinciden |
|
| 74 | + */ |
|
| 75 | 75 | private function checkPassMatch(string $pass, string $pass_repeat) { |
| 76 | 76 | if($pass != $pass_repeat) { |
| 77 | 77 | throw new ModelsException('Las contraseñas no coinciden.'); |
@@ -79,12 +79,12 @@ discard block |
||
| 79 | 79 | } |
| 80 | 80 | |
| 81 | 81 | /** |
| 82 | - * Verifica el email introducido, tanto el formato como su existencia en el sistema |
|
| 83 | - * |
|
| 84 | - * @param string $email: Email del usuario |
|
| 85 | - * |
|
| 86 | - * @throws ModelsException en caso de que no tenga formato válido o ya exista |
|
| 87 | - */ |
|
| 82 | + * Verifica el email introducido, tanto el formato como su existencia en el sistema |
|
| 83 | + * |
|
| 84 | + * @param string $email: Email del usuario |
|
| 85 | + * |
|
| 86 | + * @throws ModelsException en caso de que no tenga formato válido o ya exista |
|
| 87 | + */ |
|
| 88 | 88 | private function checkEmail(string $email) { |
| 89 | 89 | # Formato de email |
| 90 | 90 | if(!Strings::is_email($email)) { |
@@ -99,13 +99,13 @@ discard block |
||
| 99 | 99 | } |
| 100 | 100 | |
| 101 | 101 | /** |
| 102 | - * Restaura los intentos de un usuario al iniciar sesión |
|
| 103 | - * |
|
| 104 | - * @param string $email: Email del usuario a restaurar |
|
| 105 | - * |
|
| 106 | - * @throws ModelsException cuando hay un error de lógica utilizando este método |
|
| 107 | - * @return void |
|
| 108 | - */ |
|
| 102 | + * Restaura los intentos de un usuario al iniciar sesión |
|
| 103 | + * |
|
| 104 | + * @param string $email: Email del usuario a restaurar |
|
| 105 | + * |
|
| 106 | + * @throws ModelsException cuando hay un error de lógica utilizando este método |
|
| 107 | + * @return void |
|
| 108 | + */ |
|
| 109 | 109 | private function restoreAttempts(string $email) { |
| 110 | 110 | if(array_key_exists($email,$this->recentAttempts)) { |
| 111 | 111 | $this->recentAttempts[$email]['attempts'] = 0; |
@@ -118,12 +118,12 @@ discard block |
||
| 118 | 118 | } |
| 119 | 119 | |
| 120 | 120 | /** |
| 121 | - * Genera la sesión con el id del usuario que ha iniciado |
|
| 122 | - * |
|
| 123 | - * @param array $user_data: Arreglo con información de la base de datos, del usuario |
|
| 124 | - * |
|
| 125 | - * @return void |
|
| 126 | - */ |
|
| 121 | + * Genera la sesión con el id del usuario que ha iniciado |
|
| 122 | + * |
|
| 123 | + * @param array $user_data: Arreglo con información de la base de datos, del usuario |
|
| 124 | + * |
|
| 125 | + * @return void |
|
| 126 | + */ |
|
| 127 | 127 | private function generateSession(array $user_data) { |
| 128 | 128 | global $session, $config; |
| 129 | 129 | |
@@ -132,14 +132,14 @@ discard block |
||
| 132 | 132 | } |
| 133 | 133 | |
| 134 | 134 | /** |
| 135 | - * Verifica en la base de datos, el email y contraseña ingresados por el usuario |
|
| 136 | - * |
|
| 137 | - * @param string $email: Email del usuario que intenta el login |
|
| 138 | - * @param string $pass: Contraseña sin encriptar del usuario que intenta el login |
|
| 139 | - * |
|
| 140 | - * @return bool true: Cuando el inicio de sesión es correcto |
|
| 141 | - * false: Cuando el inicio de sesión no es correcto |
|
| 142 | - */ |
|
| 135 | + * Verifica en la base de datos, el email y contraseña ingresados por el usuario |
|
| 136 | + * |
|
| 137 | + * @param string $email: Email del usuario que intenta el login |
|
| 138 | + * @param string $pass: Contraseña sin encriptar del usuario que intenta el login |
|
| 139 | + * |
|
| 140 | + * @return bool true: Cuando el inicio de sesión es correcto |
|
| 141 | + * false: Cuando el inicio de sesión no es correcto |
|
| 142 | + */ |
|
| 143 | 143 | private function authentication(string $email,string $pass) : bool { |
| 144 | 144 | $email = $this->db->scape($email); |
| 145 | 145 | $query = $this->db->select('id_user,pass','users',"email='$email'",'LIMIT 1'); |
@@ -159,10 +159,10 @@ discard block |
||
| 159 | 159 | } |
| 160 | 160 | |
| 161 | 161 | /** |
| 162 | - * Establece los intentos recientes desde la variable de sesión acumulativa |
|
| 163 | - * |
|
| 164 | - * @return void |
|
| 165 | - */ |
|
| 162 | + * Establece los intentos recientes desde la variable de sesión acumulativa |
|
| 163 | + * |
|
| 164 | + * @return void |
|
| 165 | + */ |
|
| 166 | 166 | private function setDefaultAttempts() { |
| 167 | 167 | global $session; |
| 168 | 168 | |
@@ -172,12 +172,12 @@ discard block |
||
| 172 | 172 | } |
| 173 | 173 | |
| 174 | 174 | /** |
| 175 | - * Establece el intento del usuario actual o incrementa su cantidad si ya existe |
|
| 176 | - * |
|
| 177 | - * @param string $email: Email del usuario |
|
| 178 | - * |
|
| 179 | - * @return void |
|
| 180 | - */ |
|
| 175 | + * Establece el intento del usuario actual o incrementa su cantidad si ya existe |
|
| 176 | + * |
|
| 177 | + * @param string $email: Email del usuario |
|
| 178 | + * |
|
| 179 | + * @return void |
|
| 180 | + */ |
|
| 181 | 181 | private function setNewAttempt(string $email) { |
| 182 | 182 | if(!array_key_exists($email,$this->recentAttempts)) { |
| 183 | 183 | $this->recentAttempts[$email] = array( |
@@ -191,14 +191,14 @@ discard block |
||
| 191 | 191 | } |
| 192 | 192 | |
| 193 | 193 | /** |
| 194 | - * Controla la cantidad de intentos permitidos máximos por usuario, si llega al límite, |
|
| 195 | - * el usuario podrá seguir intentando en self::MAX_ATTEMPTS_TIME segundos. |
|
| 196 | - * |
|
| 197 | - * @param string $email: Email del usuario |
|
| 198 | - * |
|
| 199 | - * @throws ModelsException cuando ya ha excedido self::MAX_ATTEMPTS |
|
| 200 | - * @return void |
|
| 201 | - */ |
|
| 194 | + * Controla la cantidad de intentos permitidos máximos por usuario, si llega al límite, |
|
| 195 | + * el usuario podrá seguir intentando en self::MAX_ATTEMPTS_TIME segundos. |
|
| 196 | + * |
|
| 197 | + * @param string $email: Email del usuario |
|
| 198 | + * |
|
| 199 | + * @throws ModelsException cuando ya ha excedido self::MAX_ATTEMPTS |
|
| 200 | + * @return void |
|
| 201 | + */ |
|
| 202 | 202 | private function maximumAttempts(string $email) { |
| 203 | 203 | if($this->recentAttempts[$email]['attempts'] >= self::MAX_ATTEMPTS) { |
| 204 | 204 | |
@@ -219,10 +219,10 @@ discard block |
||
| 219 | 219 | } |
| 220 | 220 | |
| 221 | 221 | /** |
| 222 | - * Realiza la acción de login dentro del sistema |
|
| 223 | - * |
|
| 224 | - * @return array : Con información de éxito/falla al inicio de sesión. |
|
| 225 | - */ |
|
| 222 | + * Realiza la acción de login dentro del sistema |
|
| 223 | + * |
|
| 224 | + * @return array : Con información de éxito/falla al inicio de sesión. |
|
| 225 | + */ |
|
| 226 | 226 | public function login() : array { |
| 227 | 227 | try { |
| 228 | 228 | global $http; |
@@ -258,10 +258,10 @@ discard block |
||
| 258 | 258 | } |
| 259 | 259 | |
| 260 | 260 | /** |
| 261 | - * Realiza la acción de registro dentro del sistema |
|
| 262 | - * |
|
| 263 | - * @return array : Con información de éxito/falla al registrar el usuario nuevo. |
|
| 264 | - */ |
|
| 261 | + * Realiza la acción de registro dentro del sistema |
|
| 262 | + * |
|
| 263 | + * @return array : Con información de éxito/falla al registrar el usuario nuevo. |
|
| 264 | + */ |
|
| 265 | 265 | public function register() : array { |
| 266 | 266 | try { |
| 267 | 267 | global $http; |
@@ -302,11 +302,11 @@ discard block |
||
| 302 | 302 | } |
| 303 | 303 | |
| 304 | 304 | /** |
| 305 | - * Envía un correo electrónico al usuario que quiere recuperar la contraseña, con un token y una nueva contraseña. |
|
| 306 | - * Si el usuario no visita el enlace, el sistema no cambiará la contraseña. |
|
| 307 | - * |
|
| 308 | - * @return array<string,integer|string> |
|
| 309 | - */ |
|
| 305 | + * Envía un correo electrónico al usuario que quiere recuperar la contraseña, con un token y una nueva contraseña. |
|
| 306 | + * Si el usuario no visita el enlace, el sistema no cambiará la contraseña. |
|
| 307 | + * |
|
| 308 | + * @return array<string,integer|string> |
|
| 309 | + */ |
|
| 310 | 310 | public function lostpass() { |
| 311 | 311 | try { |
| 312 | 312 | global $http, $config; |
@@ -342,8 +342,8 @@ discard block |
||
| 342 | 342 | |
| 343 | 343 | # Enviar el correo electrónico |
| 344 | 344 | $dest = array(); |
| 345 | - $dest[$email] = $user_data[0]['name']; |
|
| 346 | - $email = Emails::send_mail($dest,Emails::plantilla($HTML),'Recuperar contraseña perdida'); |
|
| 345 | + $dest[$email] = $user_data[0]['name']; |
|
| 346 | + $email = Emails::send_mail($dest,Emails::plantilla($HTML),'Recuperar contraseña perdida'); |
|
| 347 | 347 | |
| 348 | 348 | # Verificar si hubo algún problema con el envío del correo |
| 349 | 349 | if(false === $email) { |
@@ -364,13 +364,13 @@ discard block |
||
| 364 | 364 | } |
| 365 | 365 | |
| 366 | 366 | /** |
| 367 | - * Cambia la contraseña de un usuario en el sistema, luego de que éste haya solicitado cambiarla. |
|
| 368 | - * Luego retorna al sitio de inicio con la variable GET success=(bool) |
|
| 369 | - * |
|
| 370 | - * La URL debe tener la forma URL/lostpass/cambiar/&token=TOKEN&user=ID |
|
| 371 | - * |
|
| 372 | - * @return void |
|
| 373 | - */ |
|
| 367 | + * Cambia la contraseña de un usuario en el sistema, luego de que éste haya solicitado cambiarla. |
|
| 368 | + * Luego retorna al sitio de inicio con la variable GET success=(bool) |
|
| 369 | + * |
|
| 370 | + * La URL debe tener la forma URL/lostpass/cambiar/&token=TOKEN&user=ID |
|
| 371 | + * |
|
| 372 | + * @return void |
|
| 373 | + */ |
|
| 374 | 374 | public function changeTemporalPass() { |
| 375 | 375 | global $config, $http; |
| 376 | 376 | |
@@ -394,10 +394,10 @@ discard block |
||
| 394 | 394 | } |
| 395 | 395 | |
| 396 | 396 | /** |
| 397 | - * Desconecta a un usuario si éste está conectado, y lo devuelve al inicio |
|
| 398 | - * |
|
| 399 | - * @return void |
|
| 400 | - */ |
|
| 397 | + * Desconecta a un usuario si éste está conectado, y lo devuelve al inicio |
|
| 398 | + * |
|
| 399 | + * @return void |
|
| 400 | + */ |
|
| 401 | 401 | public function logout() { |
| 402 | 402 | global $session; |
| 403 | 403 | |
@@ -409,36 +409,36 @@ discard block |
||
| 409 | 409 | } |
| 410 | 410 | |
| 411 | 411 | /** |
| 412 | - * Obtiene datos de un usuario según su id en la base de datos |
|
| 413 | - * |
|
| 414 | - * @param int $id: Id del usuario a obtener |
|
| 415 | - * @param string $select : Por defecto es *, se usa para obtener sólo los parámetros necesarios |
|
| 416 | - * |
|
| 417 | - * @return false|array con información del usuario |
|
| 418 | - */ |
|
| 412 | + * Obtiene datos de un usuario según su id en la base de datos |
|
| 413 | + * |
|
| 414 | + * @param int $id: Id del usuario a obtener |
|
| 415 | + * @param string $select : Por defecto es *, se usa para obtener sólo los parámetros necesarios |
|
| 416 | + * |
|
| 417 | + * @return false|array con información del usuario |
|
| 418 | + */ |
|
| 419 | 419 | public function getUserById(int $id, string $select = '*') { |
| 420 | - return $this->db->select($select,'users',"id_user='$id'",'LIMIT 1'); |
|
| 420 | + return $this->db->select($select,'users',"id_user='$id'",'LIMIT 1'); |
|
| 421 | 421 | } |
| 422 | 422 | |
| 423 | 423 | /** |
| 424 | - * Obtiene a todos los usuarios |
|
| 425 | - * |
|
| 426 | - * @param string $select : Por defecto es *, se usa para obtener sólo los parámetros necesarios |
|
| 427 | - * |
|
| 428 | - * @return false|array con información de los usuarios |
|
| 429 | - */ |
|
| 424 | + * Obtiene a todos los usuarios |
|
| 425 | + * |
|
| 426 | + * @param string $select : Por defecto es *, se usa para obtener sólo los parámetros necesarios |
|
| 427 | + * |
|
| 428 | + * @return false|array con información de los usuarios |
|
| 429 | + */ |
|
| 430 | 430 | public function getUsers(string $select = '*') { |
| 431 | - return $this->db->select($select,'users'); |
|
| 431 | + return $this->db->select($select,'users'); |
|
| 432 | 432 | } |
| 433 | 433 | |
| 434 | 434 | /** |
| 435 | - * Obtiene datos del usuario conectado actualmente |
|
| 436 | - * |
|
| 437 | - * @param string $select : Por defecto es *, se usa para obtener sólo los parámetros necesarios |
|
| 438 | - * |
|
| 439 | - * @throws ModelsException si el usuario no está logeado |
|
| 440 | - * @return array con datos del usuario conectado |
|
| 441 | - */ |
|
| 435 | + * Obtiene datos del usuario conectado actualmente |
|
| 436 | + * |
|
| 437 | + * @param string $select : Por defecto es *, se usa para obtener sólo los parámetros necesarios |
|
| 438 | + * |
|
| 439 | + * @throws ModelsException si el usuario no está logeado |
|
| 440 | + * @return array con datos del usuario conectado |
|
| 441 | + */ |
|
| 442 | 442 | public function getOwnerUser(string $select = '*') : array { |
| 443 | 443 | if(null !== $this->id_user) { |
| 444 | 444 | |
@@ -456,10 +456,10 @@ discard block |
||
| 456 | 456 | } |
| 457 | 457 | |
| 458 | 458 | /** |
| 459 | - * Instala el módulo de usuarios en la base de datos para que pueda funcionar correctamete. |
|
| 460 | - * |
|
| 461 | - * @throws \RuntimeException si no se puede realizar la query |
|
| 462 | - */ |
|
| 459 | + * Instala el módulo de usuarios en la base de datos para que pueda funcionar correctamete. |
|
| 460 | + * |
|
| 461 | + * @throws \RuntimeException si no se puede realizar la query |
|
| 462 | + */ |
|
| 463 | 463 | public function install() { |
| 464 | 464 | if(!$this->db->query(" |
| 465 | 465 | CREATE TABLE IF NOT EXISTS `users` ( |
@@ -480,16 +480,16 @@ discard block |
||
| 480 | 480 | } |
| 481 | 481 | |
| 482 | 482 | /** |
| 483 | - * __construct() |
|
| 484 | - */ |
|
| 483 | + * __construct() |
|
| 484 | + */ |
|
| 485 | 485 | public function __construct(IRouter $router = null) { |
| 486 | 486 | parent::__construct($router); |
| 487 | 487 | $this->startDBConexion(); |
| 488 | 488 | } |
| 489 | 489 | |
| 490 | 490 | /** |
| 491 | - * __destruct() |
|
| 492 | - */ |
|
| 491 | + * __destruct() |
|
| 492 | + */ |
|
| 493 | 493 | public function __destruct() { |
| 494 | 494 | parent::__destruct(); |
| 495 | 495 | $this->endDBConexion(); |
@@ -73,7 +73,7 @@ discard block |
||
| 73 | 73 | * @throws ModelsException cuando las contraseñas no coinciden |
| 74 | 74 | */ |
| 75 | 75 | private function checkPassMatch(string $pass, string $pass_repeat) { |
| 76 | - if($pass != $pass_repeat) { |
|
| 76 | + if ($pass != $pass_repeat) { |
|
| 77 | 77 | throw new ModelsException('Las contraseñas no coinciden.'); |
| 78 | 78 | } |
| 79 | 79 | } |
@@ -87,13 +87,13 @@ discard block |
||
| 87 | 87 | */ |
| 88 | 88 | private function checkEmail(string $email) { |
| 89 | 89 | # Formato de email |
| 90 | - if(!Strings::is_email($email)) { |
|
| 90 | + if (!Strings::is_email($email)) { |
|
| 91 | 91 | throw new ModelsException('El email no tiene un formato válido.'); |
| 92 | 92 | } |
| 93 | 93 | # Existencia de email |
| 94 | 94 | $email = $this->db->scape($email); |
| 95 | - $query = $this->db->select('id_user','users',"email='$email'",'LIMIT 1'); |
|
| 96 | - if(false !== $query) { |
|
| 95 | + $query = $this->db->select('id_user', 'users', "email='$email'", 'LIMIT 1'); |
|
| 96 | + if (false !== $query) { |
|
| 97 | 97 | throw new ModelsException('El email introducido ya existe.'); |
| 98 | 98 | } |
| 99 | 99 | } |
@@ -107,7 +107,7 @@ discard block |
||
| 107 | 107 | * @return void |
| 108 | 108 | */ |
| 109 | 109 | private function restoreAttempts(string $email) { |
| 110 | - if(array_key_exists($email,$this->recentAttempts)) { |
|
| 110 | + if (array_key_exists($email, $this->recentAttempts)) { |
|
| 111 | 111 | $this->recentAttempts[$email]['attempts'] = 0; |
| 112 | 112 | $this->recentAttempts[$email]['time'] = null; |
| 113 | 113 | $this->updateSessionAttempts(); |
@@ -127,7 +127,7 @@ discard block |
||
| 127 | 127 | private function generateSession(array $user_data) { |
| 128 | 128 | global $session, $config; |
| 129 | 129 | |
| 130 | - $session->set('user_id',(int) $user_data['id_user']); |
|
| 130 | + $session->set('user_id', (int) $user_data['id_user']); |
|
| 131 | 131 | $session->set('unique_session', $config['sessions']['unique']); |
| 132 | 132 | } |
| 133 | 133 | |
@@ -140,12 +140,12 @@ discard block |
||
| 140 | 140 | * @return bool true: Cuando el inicio de sesión es correcto |
| 141 | 141 | * false: Cuando el inicio de sesión no es correcto |
| 142 | 142 | */ |
| 143 | - private function authentication(string $email,string $pass) : bool { |
|
| 143 | + private function authentication(string $email, string $pass) : bool { |
|
| 144 | 144 | $email = $this->db->scape($email); |
| 145 | - $query = $this->db->select('id_user,pass','users',"email='$email'",'LIMIT 1'); |
|
| 145 | + $query = $this->db->select('id_user,pass', 'users', "email='$email'", 'LIMIT 1'); |
|
| 146 | 146 | |
| 147 | 147 | # Incio de sesión con éxito |
| 148 | - if(false !== $query && Strings::chash($query[0]['pass'],$pass)) { |
|
| 148 | + if (false !== $query && Strings::chash($query[0]['pass'], $pass)) { |
|
| 149 | 149 | |
| 150 | 150 | # Restaurar intentos |
| 151 | 151 | $this->restoreAttempts($email); |
@@ -166,7 +166,7 @@ discard block |
||
| 166 | 166 | private function setDefaultAttempts() { |
| 167 | 167 | global $session; |
| 168 | 168 | |
| 169 | - if(null != $session->get('login_user_recentAttempts')) { |
|
| 169 | + if (null != $session->get('login_user_recentAttempts')) { |
|
| 170 | 170 | $this->recentAttempts = $session->get('login_user_recentAttempts'); |
| 171 | 171 | } |
| 172 | 172 | } |
@@ -179,7 +179,7 @@ discard block |
||
| 179 | 179 | * @return void |
| 180 | 180 | */ |
| 181 | 181 | private function setNewAttempt(string $email) { |
| 182 | - if(!array_key_exists($email,$this->recentAttempts)) { |
|
| 182 | + if (!array_key_exists($email, $this->recentAttempts)) { |
|
| 183 | 183 | $this->recentAttempts[$email] = array( |
| 184 | 184 | 'attempts' => 0, # Intentos |
| 185 | 185 | 'time' => null # Tiempo |
@@ -200,14 +200,14 @@ discard block |
||
| 200 | 200 | * @return void |
| 201 | 201 | */ |
| 202 | 202 | private function maximumAttempts(string $email) { |
| 203 | - if($this->recentAttempts[$email]['attempts'] >= self::MAX_ATTEMPTS) { |
|
| 203 | + if ($this->recentAttempts[$email]['attempts'] >= self::MAX_ATTEMPTS) { |
|
| 204 | 204 | |
| 205 | 205 | # Colocar timestamp para recuperar más adelante la posibilidad de acceso |
| 206 | - if(null == $this->recentAttempts[$email]['time']) { |
|
| 206 | + if (null == $this->recentAttempts[$email]['time']) { |
|
| 207 | 207 | $this->recentAttempts[$email]['time'] = time() + self::MAX_ATTEMPTS_TIME; |
| 208 | 208 | } |
| 209 | 209 | |
| 210 | - if(time() < $this->recentAttempts[$email]['time']) { |
|
| 210 | + if (time() < $this->recentAttempts[$email]['time']) { |
|
| 211 | 211 | # Setear sesión |
| 212 | 212 | $this->updateSessionAttempts(); |
| 213 | 213 | # Lanzar excepción |
@@ -235,7 +235,7 @@ discard block |
||
| 235 | 235 | $pass = $http->request->get('pass'); |
| 236 | 236 | |
| 237 | 237 | # Verificar que no están vacíos |
| 238 | - if($this->functions->e($email,$pass)) { |
|
| 238 | + if ($this->functions->e($email, $pass)) { |
|
| 239 | 239 | throw new ModelsException('Credenciales incompletas.'); |
| 240 | 240 | } |
| 241 | 241 | |
@@ -246,13 +246,13 @@ discard block |
||
| 246 | 246 | $this->maximumAttempts($email); |
| 247 | 247 | |
| 248 | 248 | # Autentificar |
| 249 | - if($this->authentication($email,$pass)) { |
|
| 249 | + if ($this->authentication($email, $pass)) { |
|
| 250 | 250 | return array('success' => 1, 'message' => 'Conectado con éxito.'); |
| 251 | 251 | } |
| 252 | 252 | |
| 253 | 253 | throw new ModelsException('Credenciales incorrectas.'); |
| 254 | 254 | |
| 255 | - } catch(ModelsException $e) { |
|
| 255 | + } catch (ModelsException $e) { |
|
| 256 | 256 | return array('success' => 0, 'message' => $e->getMessage()); |
| 257 | 257 | } |
| 258 | 258 | } |
@@ -273,7 +273,7 @@ discard block |
||
| 273 | 273 | $pass_repeat = $http->request->get('pass_repeat'); |
| 274 | 274 | |
| 275 | 275 | # Verificar que no están vacíos |
| 276 | - if($this->functions->e($name,$email,$pass,$pass_repeat)) { |
|
| 276 | + if ($this->functions->e($name, $email, $pass, $pass_repeat)) { |
|
| 277 | 277 | throw new ModelsException('Todos los datos son necesarios'); |
| 278 | 278 | } |
| 279 | 279 | |
@@ -281,10 +281,10 @@ discard block |
||
| 281 | 281 | $this->checkEmail($email); |
| 282 | 282 | |
| 283 | 283 | # Veriricar contraseñas |
| 284 | - $this->checkPassMatch($pass,$pass_repeat); |
|
| 284 | + $this->checkPassMatch($pass, $pass_repeat); |
|
| 285 | 285 | |
| 286 | 286 | # Registrar al usuario |
| 287 | - $this->db->insert('users',array( |
|
| 287 | + $this->db->insert('users', array( |
|
| 288 | 288 | 'name' => $name, |
| 289 | 289 | 'email' => $email, |
| 290 | 290 | 'pass' => Strings::hash($pass) |
@@ -296,7 +296,7 @@ discard block |
||
| 296 | 296 | )); |
| 297 | 297 | |
| 298 | 298 | return array('success' => 1, 'message' => 'Registrado con éxito.'); |
| 299 | - } catch(ModelsException $e) { |
|
| 299 | + } catch (ModelsException $e) { |
|
| 300 | 300 | return array('success' => 0, 'message' => $e->getMessage()); |
| 301 | 301 | } |
| 302 | 302 | } |
@@ -315,7 +315,7 @@ discard block |
||
| 315 | 315 | $email = $http->request->get('email'); |
| 316 | 316 | |
| 317 | 317 | # Campo lleno |
| 318 | - if($this->functions->emp($email)) { |
|
| 318 | + if ($this->functions->emp($email)) { |
|
| 319 | 319 | throw new ModelsException('El campo email debe estar lleno.'); |
| 320 | 320 | } |
| 321 | 321 | |
@@ -323,10 +323,10 @@ discard block |
||
| 323 | 323 | $email = $this->db->scape($email); |
| 324 | 324 | |
| 325 | 325 | # Obtener información del usuario |
| 326 | - $user_data = $this->db->select('id_user,name','users',"email='$email'",'LIMIT 1'); |
|
| 326 | + $user_data = $this->db->select('id_user,name', 'users', "email='$email'", 'LIMIT 1'); |
|
| 327 | 327 | |
| 328 | 328 | # Verificar correo en base de datos |
| 329 | - if(false === $user_data) { |
|
| 329 | + if (false === $user_data) { |
|
| 330 | 330 | throw new ModelsException('El email no está registrado en el sistema.'); |
| 331 | 331 | } |
| 332 | 332 | |
@@ -335,30 +335,30 @@ discard block |
||
| 335 | 335 | $pass = uniqid(); |
| 336 | 336 | |
| 337 | 337 | # Construir mensaje y enviar mensaje |
| 338 | - $HTML = 'Hola <b>'. $user_data[0]['name'] .'</b>, ha solicitado recuperar su contraseña perdida, si no ha realizado esta acción no necesita hacer nada. |
|
| 338 | + $HTML = 'Hola <b>' . $user_data[0]['name'] . '</b>, ha solicitado recuperar su contraseña perdida, si no ha realizado esta acción no necesita hacer nada. |
|
| 339 | 339 | <br /> |
| 340 | 340 | <br /> |
| 341 | - Para cambiar su contraseña por <b>'. $pass .'</b> haga <a href="'. $config['site']['url'] . 'lostpass/cambiar/&token='.$token.'&user='.$user_data[0]['id_user'].'" target="_blank">clic aquí</a>.'; |
|
| 341 | + Para cambiar su contraseña por <b>'. $pass . '</b> haga <a href="' . $config['site']['url'] . 'lostpass/cambiar/&token=' . $token . '&user=' . $user_data[0]['id_user'] . '" target="_blank">clic aquí</a>.'; |
|
| 342 | 342 | |
| 343 | 343 | # Enviar el correo electrónico |
| 344 | 344 | $dest = array(); |
| 345 | 345 | $dest[$email] = $user_data[0]['name']; |
| 346 | - $email = Emails::send_mail($dest,Emails::plantilla($HTML),'Recuperar contraseña perdida'); |
|
| 346 | + $email = Emails::send_mail($dest, Emails::plantilla($HTML), 'Recuperar contraseña perdida'); |
|
| 347 | 347 | |
| 348 | 348 | # Verificar si hubo algún problema con el envío del correo |
| 349 | - if(false === $email) { |
|
| 349 | + if (false === $email) { |
|
| 350 | 350 | throw new ModelsException('No se ha podido enviar el correo electrónico.'); |
| 351 | 351 | } |
| 352 | 352 | |
| 353 | 353 | # Actualizar datos |
| 354 | 354 | $id_user = $user_data[0]['id_user']; |
| 355 | - $this->db->update('users',array( |
|
| 355 | + $this->db->update('users', array( |
|
| 356 | 356 | 'tmp_pass' => Strings::hash($pass), |
| 357 | 357 | 'token' => $token |
| 358 | - ),"id_user='$id_user'",'LIMIT 1'); |
|
| 358 | + ), "id_user='$id_user'", 'LIMIT 1'); |
|
| 359 | 359 | |
| 360 | 360 | return array('success' => 1, 'message' => 'Se ha enviado un enlace a su correo electrónico.'); |
| 361 | - } catch(ModelsException $e) { |
|
| 361 | + } catch (ModelsException $e) { |
|
| 362 | 362 | return array('success' => 0, 'message' => $e->getMessage()); |
| 363 | 363 | } |
| 364 | 364 | } |
@@ -378,7 +378,7 @@ discard block |
||
| 378 | 378 | $id_user = $http->query->get('user'); |
| 379 | 379 | $token = $http->query->get('token'); |
| 380 | 380 | |
| 381 | - if(!$this->functions->emp($token) && is_numeric($id_user) && $id_user >= 1) { |
|
| 381 | + if (!$this->functions->emp($token) && is_numeric($id_user) && $id_user >= 1) { |
|
| 382 | 382 | # Filtros a los datos |
| 383 | 383 | $id_user = $this->db->scape($id_user); |
| 384 | 384 | $token = $this->db->scape($token); |
@@ -401,7 +401,7 @@ discard block |
||
| 401 | 401 | public function logout() { |
| 402 | 402 | global $session; |
| 403 | 403 | |
| 404 | - if(null != $session->get('user_id')) { |
|
| 404 | + if (null != $session->get('user_id')) { |
|
| 405 | 405 | $session->remove('user_id'); |
| 406 | 406 | } |
| 407 | 407 | |
@@ -417,7 +417,7 @@ discard block |
||
| 417 | 417 | * @return false|array con información del usuario |
| 418 | 418 | */ |
| 419 | 419 | public function getUserById(int $id, string $select = '*') { |
| 420 | - return $this->db->select($select,'users',"id_user='$id'",'LIMIT 1'); |
|
| 420 | + return $this->db->select($select, 'users', "id_user='$id'", 'LIMIT 1'); |
|
| 421 | 421 | } |
| 422 | 422 | |
| 423 | 423 | /** |
@@ -428,7 +428,7 @@ discard block |
||
| 428 | 428 | * @return false|array con información de los usuarios |
| 429 | 429 | */ |
| 430 | 430 | public function getUsers(string $select = '*') { |
| 431 | - return $this->db->select($select,'users'); |
|
| 431 | + return $this->db->select($select, 'users'); |
|
| 432 | 432 | } |
| 433 | 433 | |
| 434 | 434 | /** |
@@ -440,12 +440,12 @@ discard block |
||
| 440 | 440 | * @return array con datos del usuario conectado |
| 441 | 441 | */ |
| 442 | 442 | public function getOwnerUser(string $select = '*') : array { |
| 443 | - if(null !== $this->id_user) { |
|
| 443 | + if (null !== $this->id_user) { |
|
| 444 | 444 | |
| 445 | - $user = $this->db->select($select,'users',"id_user='$this->id_user'",'LIMIT 1'); |
|
| 445 | + $user = $this->db->select($select, 'users', "id_user='$this->id_user'", 'LIMIT 1'); |
|
| 446 | 446 | |
| 447 | 447 | # Si se borra al usuario desde la base de datos y sigue con la sesión activa |
| 448 | - if(false === $user) { |
|
| 448 | + if (false === $user) { |
|
| 449 | 449 | $this->logout(); |
| 450 | 450 | } |
| 451 | 451 | |
@@ -461,7 +461,7 @@ discard block |
||
| 461 | 461 | * @throws \RuntimeException si no se puede realizar la query |
| 462 | 462 | */ |
| 463 | 463 | public function install() { |
| 464 | - if(!$this->db->query(" |
|
| 464 | + if (!$this->db->query(" |
|
| 465 | 465 | CREATE TABLE IF NOT EXISTS `users` ( |
| 466 | 466 | `id_user` int(11) UNSIGNED NOT NULL AUTO_INCREMENT, |
| 467 | 467 | `name` varchar(100) NOT NULL, |
@@ -25,65 +25,65 @@ discard block |
||
| 25 | 25 | abstract class Controllers { |
| 26 | 26 | |
| 27 | 27 | /** |
| 28 | - * Obtiene el objeto del template |
|
| 29 | - * |
|
| 30 | - * @var \Twig_Environment |
|
| 31 | - */ |
|
| 28 | + * Obtiene el objeto del template |
|
| 29 | + * |
|
| 30 | + * @var \Twig_Environment |
|
| 31 | + */ |
|
| 32 | 32 | protected $template; |
| 33 | 33 | |
| 34 | 34 | /** |
| 35 | - * Verifica si está definida la ruta /id como un integer >= 1 |
|
| 36 | - * |
|
| 37 | - * @var bool |
|
| 38 | - */ |
|
| 35 | + * Verifica si está definida la ruta /id como un integer >= 1 |
|
| 36 | + * |
|
| 37 | + * @var bool |
|
| 38 | + */ |
|
| 39 | 39 | protected $isset_id = false; |
| 40 | 40 | |
| 41 | 41 | /** |
| 42 | - * Tiene el valor de la ruta /método |
|
| 43 | - * |
|
| 44 | - * @var string|null |
|
| 45 | - */ |
|
| 42 | + * Tiene el valor de la ruta /método |
|
| 43 | + * |
|
| 44 | + * @var string|null |
|
| 45 | + */ |
|
| 46 | 46 | protected $method; |
| 47 | 47 | |
| 48 | 48 | /** |
| 49 | - * Contiene una instancia del helper para funciones |
|
| 50 | - * |
|
| 51 | - * @var \Ocrend\Kernel\Helpers\Functions |
|
| 52 | - */ |
|
| 49 | + * Contiene una instancia del helper para funciones |
|
| 50 | + * |
|
| 51 | + * @var \Ocrend\Kernel\Helpers\Functions |
|
| 52 | + */ |
|
| 53 | 53 | protected $functions; |
| 54 | 54 | |
| 55 | 55 | /** |
| 56 | - * Arreglo con la información del usuario conectado actualmente. |
|
| 57 | - * |
|
| 58 | - * @var array |
|
| 59 | - */ |
|
| 56 | + * Arreglo con la información del usuario conectado actualmente. |
|
| 57 | + * |
|
| 58 | + * @var array |
|
| 59 | + */ |
|
| 60 | 60 | protected $user = array(); |
| 61 | 61 | |
| 62 | 62 | /** |
| 63 | - * Contiene información sobre el estado del usuario, si está o no conectado. |
|
| 64 | - * |
|
| 65 | - * @var bool |
|
| 66 | - */ |
|
| 63 | + * Contiene información sobre el estado del usuario, si está o no conectado. |
|
| 64 | + * |
|
| 65 | + * @var bool |
|
| 66 | + */ |
|
| 67 | 67 | private $is_logged = false; |
| 68 | 68 | |
| 69 | 69 | /** |
| 70 | - * Parámetros de configuración para el controlador con la forma: |
|
| 71 | - * 'parmáetro' => (bool) valor |
|
| 72 | - * |
|
| 73 | - * @var array |
|
| 74 | - */ |
|
| 70 | + * Parámetros de configuración para el controlador con la forma: |
|
| 71 | + * 'parmáetro' => (bool) valor |
|
| 72 | + * |
|
| 73 | + * @var array |
|
| 74 | + */ |
|
| 75 | 75 | private $controllerConfig; |
| 76 | 76 | |
| 77 | 77 | /** |
| 78 | - * Configuración inicial de cualquier controlador |
|
| 79 | - * |
|
| 80 | - * @param IRouter $router: Instancia de un Router |
|
| 81 | - * @param array|null $configController: Arreglo de configuración con la forma |
|
| 82 | - * 'twig_cache_reload' => bool, # Configura el autoreload del caché de twig |
|
| 83 | - * 'users_logged' => bool, # Configura el controlador para solo ser visto por usuarios logeados |
|
| 84 | - * 'users_not_logged' => bool, # Configura el controlador para solo ser visto por !(usuarios logeados) |
|
| 85 | - * |
|
| 86 | - */ |
|
| 78 | + * Configuración inicial de cualquier controlador |
|
| 79 | + * |
|
| 80 | + * @param IRouter $router: Instancia de un Router |
|
| 81 | + * @param array|null $configController: Arreglo de configuración con la forma |
|
| 82 | + * 'twig_cache_reload' => bool, # Configura el autoreload del caché de twig |
|
| 83 | + * 'users_logged' => bool, # Configura el controlador para solo ser visto por usuarios logeados |
|
| 84 | + * 'users_not_logged' => bool, # Configura el controlador para solo ser visto por !(usuarios logeados) |
|
| 85 | + * |
|
| 86 | + */ |
|
| 87 | 87 | protected function __construct(IRouter $router, $configController = null) { |
| 88 | 88 | global $config, $http, $session; |
| 89 | 89 | |
@@ -131,13 +131,13 @@ discard block |
||
| 131 | 131 | } |
| 132 | 132 | |
| 133 | 133 | /** |
| 134 | - * Establece los parámetros de configuración de un controlador |
|
| 135 | - * |
|
| 136 | - * @param IRouter $router: Instancia de un Router |
|
| 137 | - * @param array|null $config: Arreglo de configuración |
|
| 138 | - * |
|
| 139 | - * @return void |
|
| 140 | - */ |
|
| 134 | + * Establece los parámetros de configuración de un controlador |
|
| 135 | + * |
|
| 136 | + * @param IRouter $router: Instancia de un Router |
|
| 137 | + * @param array|null $config: Arreglo de configuración |
|
| 138 | + * |
|
| 139 | + * @return void |
|
| 140 | + */ |
|
| 141 | 141 | private function setControllerConfig($config) { |
| 142 | 142 | # Configuración por defecto |
| 143 | 143 | $this->controllerConfig['twig_cache_reload'] = true; |
@@ -162,10 +162,10 @@ discard block |
||
| 162 | 162 | } |
| 163 | 163 | |
| 164 | 164 | /** |
| 165 | - * Acción que regula quién entra o no al controlador según la configuración |
|
| 166 | - * |
|
| 167 | - * @return void |
|
| 168 | - */ |
|
| 165 | + * Acción que regula quién entra o no al controlador según la configuración |
|
| 166 | + * |
|
| 167 | + * @return void |
|
| 168 | + */ |
|
| 169 | 169 | private function knowVisitorPermissions() { |
| 170 | 170 | # Sólamente usuarios logeados |
| 171 | 171 | if($this->controllerConfig['users_logged'] && !$this->is_logged) { |
@@ -39,7 +39,7 @@ discard block |
||
| 39 | 39 | final public static function Start($name = null, $motor = null, bool $new_instance = false) : Database { |
| 40 | 40 | global $config; |
| 41 | 41 | |
| 42 | - if(!self::$inst instanceof self or $new_instance) { |
|
| 42 | + if (!self::$inst instanceof self or $new_instance) { |
|
| 43 | 43 | self::$inst = new self( |
| 44 | 44 | null === $name ? $config['database']['name'] : $name, |
| 45 | 45 | null === $motor ? $config['database']['motor'] : $motor |
@@ -72,63 +72,63 @@ discard block |
||
| 72 | 72 | try { |
| 73 | 73 | switch ($motor) { |
| 74 | 74 | case 'sqlite': |
| 75 | - parent::__construct('sqlite:'.$name); |
|
| 75 | + parent::__construct('sqlite:' . $name); |
|
| 76 | 76 | break; |
| 77 | 77 | case 'cubrid': |
| 78 | - parent::__construct('cubrid:host='.$config['database']['host'].';dbname='.$name.';port='.$config['database']['port'], |
|
| 78 | + parent::__construct('cubrid:host=' . $config['database']['host'] . ';dbname=' . $name . ';port=' . $config['database']['port'], |
|
| 79 | 79 | $config['database']['user'], |
| 80 | 80 | $config['database']['pass'], |
| 81 | 81 | $comun_config); |
| 82 | 82 | break; |
| 83 | 83 | case 'firebird': |
| 84 | - parent::__construct('firebird:dbname='.$config['database']['host'].':'.$name, |
|
| 84 | + parent::__construct('firebird:dbname=' . $config['database']['host'] . ':' . $name, |
|
| 85 | 85 | $config['database']['user'], |
| 86 | 86 | $config['database']['pass'], |
| 87 | 87 | $comun_config); |
| 88 | 88 | break; |
| 89 | 89 | case 'odbc'; |
| 90 | - parent::__construct('odbc:'.$name, |
|
| 90 | + parent::__construct('odbc:' . $name, |
|
| 91 | 91 | $config['database']['user'], |
| 92 | 92 | $config['database']['pass']); |
| 93 | 93 | break; |
| 94 | 94 | case 'oracle': |
| 95 | 95 | parent::__construct('oci:dbname=(DESCRIPTION = |
| 96 | 96 | (ADDRESS_LIST = |
| 97 | - (ADDRESS = (PROTOCOL = '.$config['database']['protocol'].')(HOST = '.$motor.')(PORT = '.$config['database']['port'].')) |
|
| 97 | + (ADDRESS = (PROTOCOL = '.$config['database']['protocol'] . ')(HOST = ' . $motor . ')(PORT = ' . $config['database']['port'] . ')) |
|
| 98 | 98 | ) |
| 99 | 99 | (CONNECT_DATA = |
| 100 | - (SERVICE_NAME = '.$name.') |
|
| 100 | + (SERVICE_NAME = '.$name . ') |
|
| 101 | 101 | ) |
| 102 | 102 | );charset=utf8', |
| 103 | 103 | $config['database']['user'], |
| 104 | 104 | $config['database']['pass'], |
| 105 | - array_merge(array(\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC),$comun_config)); |
|
| 105 | + array_merge(array(\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC), $comun_config)); |
|
| 106 | 106 | break; |
| 107 | 107 | case 'postgresql': |
| 108 | - parent::__construct('pgsql:host='.$config['database']['host'].';dbname='.$name.';charset=utf8', |
|
| 108 | + parent::__construct('pgsql:host=' . $config['database']['host'] . ';dbname=' . $name . ';charset=utf8', |
|
| 109 | 109 | $config['database']['user'], |
| 110 | 110 | $config['database']['pass'], |
| 111 | 111 | $comun_config); |
| 112 | 112 | break; |
| 113 | 113 | case 'mysql': |
| 114 | - parent::__construct('mysql:host='.$config['database']['host'].';dbname='.$name, |
|
| 114 | + parent::__construct('mysql:host=' . $config['database']['host'] . ';dbname=' . $name, |
|
| 115 | 115 | $config['database']['user'], |
| 116 | 116 | $config['database']['pass'], |
| 117 | - array_merge(array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'),$comun_config)); |
|
| 117 | + array_merge(array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'), $comun_config)); |
|
| 118 | 118 | break; |
| 119 | 119 | case 'mssql': |
| 120 | 120 | # Añadido por marc2684 |
| 121 | 121 | # DOC: https://github.com/prinick96/Ocrend-Framework/issues/7 |
| 122 | - parent::__construct('sqlsrv:Server='.$config['database']['host'].';Database='.$name.';ConnectionPooling=0', |
|
| 122 | + parent::__construct('sqlsrv:Server=' . $config['database']['host'] . ';Database=' . $name . ';ConnectionPooling=0', |
|
| 123 | 123 | $config['database']['user'], |
| 124 | 124 | $config['database']['pass'], |
| 125 | 125 | $comun_config); |
| 126 | 126 | break; |
| 127 | 127 | default: |
| 128 | - throw new \RuntimeException('Motor '. $motor .' de conexión no identificado.'); |
|
| 128 | + throw new \RuntimeException('Motor ' . $motor . ' de conexión no identificado.'); |
|
| 129 | 129 | break; |
| 130 | 130 | } |
| 131 | - } catch(\PDOException $e) { |
|
| 131 | + } catch (\PDOException $e) { |
|
| 132 | 132 | throw new \RuntimeException('Problema al conectar con la base de datos: ' . $e->getMessage()); |
| 133 | 133 | } |
| 134 | 134 | } |
@@ -163,18 +163,18 @@ discard block |
||
| 163 | 163 | * @return mixed elemento sano |
| 164 | 164 | */ |
| 165 | 165 | final public function scape($e) { |
| 166 | - if(null === $e) { |
|
| 166 | + if (null === $e) { |
|
| 167 | 167 | return ''; |
| 168 | 168 | } |
| 169 | 169 | |
| 170 | - if(is_numeric($e) and $e <= 2147483647) { |
|
| 171 | - if(explode('.',$e)[0] != $e) { |
|
| 170 | + if (is_numeric($e) and $e <= 2147483647) { |
|
| 171 | + if (explode('.', $e)[0] != $e) { |
|
| 172 | 172 | return (float) $e; |
| 173 | 173 | } |
| 174 | 174 | return (int) $e; |
| 175 | 175 | } |
| 176 | 176 | |
| 177 | - return (string) trim(str_replace(['\\',"\x00",'\n','\r',"'",'"',"\x1a"],['\\\\','\\0','\\n','\\r',"\'",'\"','\\Z'],$e)); |
|
| 177 | + return (string) trim(str_replace(['\\', "\x00", '\n', '\r', "'", '"', "\x1a"], ['\\\\', '\\0', '\\n', '\\r', "\'", '\"', '\\Z'], $e)); |
|
| 178 | 178 | } |
| 179 | 179 | |
| 180 | 180 | /** |
@@ -202,7 +202,7 @@ discard block |
||
| 202 | 202 | */ |
| 203 | 203 | final public function insert(string $table, array $e) : \PDOStatement { |
| 204 | 204 | if (sizeof($e) == 0) { |
| 205 | - throw new \RuntimeException('El arreglo pasado por $this->db->insert(\''.$table.'\',...) está vacío.'); |
|
| 205 | + throw new \RuntimeException('El arreglo pasado por $this->db->insert(\'' . $table . '\',...) está vacío.'); |
|
| 206 | 206 | } |
| 207 | 207 | |
| 208 | 208 | $query = "INSERT INTO $table ("; |
@@ -232,7 +232,7 @@ discard block |
||
| 232 | 232 | */ |
| 233 | 233 | final public function update(string $table, array $e, string $where, string $limit = '') : \PDOStatement { |
| 234 | 234 | if (sizeof($e) == 0) { |
| 235 | - throw new \RuntimeException('El arreglo pasado por $this->db->update(\''.$table.'\'...) está vacío.'); |
|
| 235 | + throw new \RuntimeException('El arreglo pasado por $this->db->update(\'' . $table . '\'...) está vacío.'); |
|
| 236 | 236 | } |
| 237 | 237 | |
| 238 | 238 | $query = "UPDATE $table SET "; |
@@ -269,7 +269,7 @@ discard block |
||
| 269 | 269 | $result = $sql->fetchAll(); |
| 270 | 270 | $sql->closeCursor(); |
| 271 | 271 | |
| 272 | - if(sizeof($result) > 0) { |
|
| 272 | + if (sizeof($result) > 0) { |
|
| 273 | 273 | return $result; |
| 274 | 274 | } |
| 275 | 275 | |
@@ -18,24 +18,24 @@ discard block |
||
| 18 | 18 | * @author Brayan Narváez <[email protected]> |
| 19 | 19 | */ |
| 20 | 20 | |
| 21 | - class Database extends \PDO { |
|
| 21 | + class Database extends \PDO { |
|
| 22 | 22 | |
| 23 | - /** |
|
| 23 | + /** |
|
| 24 | 24 | * Contiene la instancia de conexión a la base de datos |
| 25 | 25 | * |
| 26 | 26 | * @var Database |
| 27 | - */ |
|
| 28 | - private static $inst; |
|
| 27 | + */ |
|
| 28 | + private static $inst; |
|
| 29 | 29 | |
| 30 | 30 | /** |
| 31 | - * Inicia la instancia de conexión, si esta ya ha sido declarada antes, no la duplica y ahorra memoria. |
|
| 32 | - * |
|
| 33 | - * @param string|null $name : Nombre de la base de datos a conectar |
|
| 34 | - * @param string|null $motor: Motor de la base de datos a conectar |
|
| 35 | - * @param bool $new_instance: true para iniciar una nueva instancia (al querer conectar a una DB distinta) |
|
| 36 | - * |
|
| 37 | - * @return Database : Instancia de conexión |
|
| 38 | - */ |
|
| 31 | + * Inicia la instancia de conexión, si esta ya ha sido declarada antes, no la duplica y ahorra memoria. |
|
| 32 | + * |
|
| 33 | + * @param string|null $name : Nombre de la base de datos a conectar |
|
| 34 | + * @param string|null $motor: Motor de la base de datos a conectar |
|
| 35 | + * @param bool $new_instance: true para iniciar una nueva instancia (al querer conectar a una DB distinta) |
|
| 36 | + * |
|
| 37 | + * @return Database : Instancia de conexión |
|
| 38 | + */ |
|
| 39 | 39 | final public static function Start($name = null, $motor = null, bool $new_instance = false) : Database { |
| 40 | 40 | global $config; |
| 41 | 41 | |
@@ -50,16 +50,16 @@ discard block |
||
| 50 | 50 | } |
| 51 | 51 | |
| 52 | 52 | /** |
| 53 | - * Inicia la conexión con la base de datos seleccionada |
|
| 54 | - * |
|
| 55 | - * @param string|null $name : Nombre de la base de datos a conectar |
|
| 56 | - * @param string|null $motor: Motor de la base de datos a conectar |
|
| 57 | - * @param bool $new_instance: true para iniciar una nueva instancia (al querer conectar a una DB distinta) |
|
| 58 | - * |
|
| 59 | - * @throws \RuntimeException si el motor no existe |
|
| 60 | - * @throws \RuntimeException si existe algún problema de conexión con la base de datos |
|
| 61 | - * @return Database : Instancia de conexión |
|
| 62 | - */ |
|
| 53 | + * Inicia la conexión con la base de datos seleccionada |
|
| 54 | + * |
|
| 55 | + * @param string|null $name : Nombre de la base de datos a conectar |
|
| 56 | + * @param string|null $motor: Motor de la base de datos a conectar |
|
| 57 | + * @param bool $new_instance: true para iniciar una nueva instancia (al querer conectar a una DB distinta) |
|
| 58 | + * |
|
| 59 | + * @throws \RuntimeException si el motor no existe |
|
| 60 | + * @throws \RuntimeException si existe algún problema de conexión con la base de datos |
|
| 61 | + * @return Database : Instancia de conexión |
|
| 62 | + */ |
|
| 63 | 63 | final public function __construct(string $name, string $motor) { |
| 64 | 64 | global $config; |
| 65 | 65 | |
@@ -134,34 +134,34 @@ discard block |
||
| 134 | 134 | } |
| 135 | 135 | |
| 136 | 136 | /** |
| 137 | - * Convierte en arreglo asociativo de todos los resultados arrojados por una query |
|
| 138 | - * |
|
| 139 | - * @param object \PDOStatement $query, valor devuelto de la query |
|
| 140 | - * |
|
| 141 | - * @return array arreglo asociativo |
|
| 142 | - */ |
|
| 137 | + * Convierte en arreglo asociativo de todos los resultados arrojados por una query |
|
| 138 | + * |
|
| 139 | + * @param object \PDOStatement $query, valor devuelto de la query |
|
| 140 | + * |
|
| 141 | + * @return array arreglo asociativo |
|
| 142 | + */ |
|
| 143 | 143 | final public function fetch_array(\PDOStatement $query) : array { |
| 144 | 144 | return $query->fetchAll(\PDO::FETCH_ASSOC); |
| 145 | 145 | } |
| 146 | 146 | |
| 147 | - /** |
|
| 148 | - * Cantidad de filas encontradas después de un SELECT |
|
| 149 | - * |
|
| 150 | - * @param object \PDOStatement $query, valor devuelto de la query |
|
| 151 | - * |
|
| 152 | - * @return int numero de filas encontradas |
|
| 153 | - */ |
|
| 147 | + /** |
|
| 148 | + * Cantidad de filas encontradas después de un SELECT |
|
| 149 | + * |
|
| 150 | + * @param object \PDOStatement $query, valor devuelto de la query |
|
| 151 | + * |
|
| 152 | + * @return int numero de filas encontradas |
|
| 153 | + */ |
|
| 154 | 154 | final public function rows(\PDOStatement $query) : int { |
| 155 | 155 | return $query->rowCount(); |
| 156 | 156 | } |
| 157 | 157 | |
| 158 | 158 | /** |
| 159 | - * Sana un valor para posteriormente ser introducido en una query |
|
| 160 | - * |
|
| 161 | - * @param null/string/int/float a sanar |
|
| 162 | - * |
|
| 163 | - * @return mixed elemento sano |
|
| 164 | - */ |
|
| 159 | + * Sana un valor para posteriormente ser introducido en una query |
|
| 160 | + * |
|
| 161 | + * @param null/string/int/float a sanar |
|
| 162 | + * |
|
| 163 | + * @return mixed elemento sano |
|
| 164 | + */ |
|
| 165 | 165 | final public function scape($e) { |
| 166 | 166 | if(null === $e) { |
| 167 | 167 | return ''; |
@@ -178,28 +178,28 @@ discard block |
||
| 178 | 178 | } |
| 179 | 179 | |
| 180 | 180 | /** |
| 181 | - * Borra una serie de elementos de forma segura de una tabla en la base de datos |
|
| 182 | - * |
|
| 183 | - * @param string $table: Tabla a la cual se le quiere remover un elemento |
|
| 184 | - * @param string $where: Condición de borrado que define quien/quienes son dichos elementos |
|
| 185 | - * @param string $limit: Por defecto se limita a borrar un solo elemento que cumpla el $where |
|
| 186 | - * |
|
| 187 | - * @return \PDOStatement |
|
| 188 | - */ |
|
| 181 | + * Borra una serie de elementos de forma segura de una tabla en la base de datos |
|
| 182 | + * |
|
| 183 | + * @param string $table: Tabla a la cual se le quiere remover un elemento |
|
| 184 | + * @param string $where: Condición de borrado que define quien/quienes son dichos elementos |
|
| 185 | + * @param string $limit: Por defecto se limita a borrar un solo elemento que cumpla el $where |
|
| 186 | + * |
|
| 187 | + * @return \PDOStatement |
|
| 188 | + */ |
|
| 189 | 189 | final public function delete(string $table, string $where, string $limit = 'LIMIT 1') : \PDOStatement { |
| 190 | 190 | return $this->query("DELETE FROM $table WHERE $where $limit;"); |
| 191 | 191 | } |
| 192 | 192 | |
| 193 | 193 | /** |
| 194 | - * Inserta una serie de elementos a una tabla en la base de datos |
|
| 195 | - * |
|
| 196 | - * @param string $table: Tabla a la cual se le va a insertar elementos |
|
| 197 | - * @param array $e: Arreglo asociativo de elementos, con la estrctura 'campo_en_la_tabla' => 'valor_a_insertar_en_ese_campo', |
|
| 198 | - * todos los elementos del arreglo $e, serán sanados por el método sin necesidad de hacerlo manualmente al crear el arreglo |
|
| 199 | - * |
|
| 200 | - * @throws \RuntimeException si el arreglo está vacío |
|
| 201 | - * @return \PDOStatement |
|
| 202 | - */ |
|
| 194 | + * Inserta una serie de elementos a una tabla en la base de datos |
|
| 195 | + * |
|
| 196 | + * @param string $table: Tabla a la cual se le va a insertar elementos |
|
| 197 | + * @param array $e: Arreglo asociativo de elementos, con la estrctura 'campo_en_la_tabla' => 'valor_a_insertar_en_ese_campo', |
|
| 198 | + * todos los elementos del arreglo $e, serán sanados por el método sin necesidad de hacerlo manualmente al crear el arreglo |
|
| 199 | + * |
|
| 200 | + * @throws \RuntimeException si el arreglo está vacío |
|
| 201 | + * @return \PDOStatement |
|
| 202 | + */ |
|
| 203 | 203 | final public function insert(string $table, array $e) : \PDOStatement { |
| 204 | 204 | if (sizeof($e) == 0) { |
| 205 | 205 | throw new \RuntimeException('El arreglo pasado por $this->db->insert(\''.$table.'\',...) está vacío.'); |
@@ -219,17 +219,17 @@ discard block |
||
| 219 | 219 | } |
| 220 | 220 | |
| 221 | 221 | /** |
| 222 | - * Actualiza elementos de una tabla en la base de datos según una condición |
|
| 223 | - * |
|
| 224 | - * @param string $table: Tabla a actualizar |
|
| 225 | - * @param array $e: Arreglo asociativo de elementos, con la estrctura 'campo_en_la_tabla' => 'valor_a_insertar_en_ese_campo', |
|
| 226 | - * todos los elementos del arreglo $e, serán sanados por el método sin necesidad de hacerlo manualmente al crear el arreglo |
|
| 227 | - * @param string $where: Condición que indica quienes serán modificados |
|
| 228 | - * @param string $limite: Límite de elementos modificados, por defecto los modifica a todos |
|
| 229 | - * |
|
| 230 | - * @throws \RuntimeException si el arreglo está vacío |
|
| 231 | - * @return \PDOStatement |
|
| 232 | - */ |
|
| 222 | + * Actualiza elementos de una tabla en la base de datos según una condición |
|
| 223 | + * |
|
| 224 | + * @param string $table: Tabla a actualizar |
|
| 225 | + * @param array $e: Arreglo asociativo de elementos, con la estrctura 'campo_en_la_tabla' => 'valor_a_insertar_en_ese_campo', |
|
| 226 | + * todos los elementos del arreglo $e, serán sanados por el método sin necesidad de hacerlo manualmente al crear el arreglo |
|
| 227 | + * @param string $where: Condición que indica quienes serán modificados |
|
| 228 | + * @param string $limite: Límite de elementos modificados, por defecto los modifica a todos |
|
| 229 | + * |
|
| 230 | + * @throws \RuntimeException si el arreglo está vacío |
|
| 231 | + * @return \PDOStatement |
|
| 232 | + */ |
|
| 233 | 233 | final public function update(string $table, array $e, string $where, string $limit = '') : \PDOStatement { |
| 234 | 234 | if (sizeof($e) == 0) { |
| 235 | 235 | throw new \RuntimeException('El arreglo pasado por $this->db->update(\''.$table.'\'...) está vacío.'); |
@@ -246,24 +246,24 @@ discard block |
||
| 246 | 246 | } |
| 247 | 247 | |
| 248 | 248 | /** |
| 249 | - * Selecciona y lista en un arreglo asociativo/numérico los resultados de una búsqueda en la base de datos |
|
| 250 | - * |
|
| 251 | - * @param string $e: Elementos a seleccionar separados por coma |
|
| 252 | - * @param string $tbale: Tabla de la cual se quiere extraer los elementos $e |
|
| 253 | - * @param string $where: Condición que indica quienes son los que se extraen, si no se coloca extrae todos |
|
| 254 | - * @param string $limite: Límite de elemntos a traer, por defecto trae TODOS los que cumplan $where |
|
| 255 | - * |
|
| 256 | - * @return mixed false si no encuentra ningún resultado, array asociativo/numérico si consigue al menos uno |
|
| 257 | - */ |
|
| 249 | + * Selecciona y lista en un arreglo asociativo/numérico los resultados de una búsqueda en la base de datos |
|
| 250 | + * |
|
| 251 | + * @param string $e: Elementos a seleccionar separados por coma |
|
| 252 | + * @param string $tbale: Tabla de la cual se quiere extraer los elementos $e |
|
| 253 | + * @param string $where: Condición que indica quienes son los que se extraen, si no se coloca extrae todos |
|
| 254 | + * @param string $limite: Límite de elemntos a traer, por defecto trae TODOS los que cumplan $where |
|
| 255 | + * |
|
| 256 | + * @return mixed false si no encuentra ningún resultado, array asociativo/numérico si consigue al menos uno |
|
| 257 | + */ |
|
| 258 | 258 | final public function select(string $e, string $table, string $where = '1 = 1', string $limit = "") { |
| 259 | 259 | return $this->query_select("SELECT $e FROM $table WHERE $where $limit;"); |
| 260 | 260 | } |
| 261 | 261 | |
| 262 | - /** |
|
| 263 | - * Realiza una query, ideal para trabajar con SELECTS, JOINS, etc |
|
| 264 | - * |
|
| 265 | - * @return array|false si no encuentra ningún resultado, array asociativo/numérico si consigue al menos uno |
|
| 266 | - */ |
|
| 262 | + /** |
|
| 263 | + * Realiza una query, ideal para trabajar con SELECTS, JOINS, etc |
|
| 264 | + * |
|
| 265 | + * @return array|false si no encuentra ningún resultado, array asociativo/numérico si consigue al menos uno |
|
| 266 | + */ |
|
| 267 | 267 | final public function query_select(string $query) { |
| 268 | 268 | $sql = $this->query($query); |
| 269 | 269 | $result = $sql->fetchAll(); |
@@ -277,13 +277,13 @@ discard block |
||
| 277 | 277 | } |
| 278 | 278 | |
| 279 | 279 | /** |
| 280 | - * Alert para evitar clonaciones |
|
| 281 | - * |
|
| 282 | - * @throws \RuntimeException si se intenta clonar la conexión |
|
| 283 | - * @return void |
|
| 284 | - */ |
|
| 280 | + * Alert para evitar clonaciones |
|
| 281 | + * |
|
| 282 | + * @throws \RuntimeException si se intenta clonar la conexión |
|
| 283 | + * @return void |
|
| 284 | + */ |
|
| 285 | 285 | final public function __clone() { |
| 286 | 286 | throw new \RuntimeException('Estás intentando clonar la Conexión'); |
| 287 | 287 | } |
| 288 | 288 | |
| 289 | - } |
|
| 290 | 289 | \ No newline at end of file |
| 290 | + } |
|
| 291 | 291 | \ No newline at end of file |
@@ -20,14 +20,14 @@ discard block |
||
| 20 | 20 | final class Emails { |
| 21 | 21 | |
| 22 | 22 | /** |
| 23 | - * FUNCIÓN NO ACCESIBLE, USO ESTRICTO PARA UNA FUNCIÓN INTERNA DEL HELPER |
|
| 24 | - * Inicializa la clase PHPMailer y las configuraciones necesarias |
|
| 25 | - * Método privado utilizado en todo el Helper |
|
| 26 | - * |
|
| 27 | - * @param bool $is_smtp: Define si se hará la conexión a través de SMTP o no |
|
| 28 | - * |
|
| 29 | - * @return \PHPMailer un objeto de la clase PHPMailer |
|
| 30 | - */ |
|
| 23 | + * FUNCIÓN NO ACCESIBLE, USO ESTRICTO PARA UNA FUNCIÓN INTERNA DEL HELPER |
|
| 24 | + * Inicializa la clase PHPMailer y las configuraciones necesarias |
|
| 25 | + * Método privado utilizado en todo el Helper |
|
| 26 | + * |
|
| 27 | + * @param bool $is_smtp: Define si se hará la conexión a través de SMTP o no |
|
| 28 | + * |
|
| 29 | + * @return \PHPMailer un objeto de la clase PHPMailer |
|
| 30 | + */ |
|
| 31 | 31 | final private static function init(bool $is_smtp = true) : \PHPMailer { |
| 32 | 32 | global $config; |
| 33 | 33 | |
@@ -60,22 +60,22 @@ discard block |
||
| 60 | 60 | //------------------------------------------------ |
| 61 | 61 | |
| 62 | 62 | /** |
| 63 | - * Envía un correo electrónico utilizando PHPMailer |
|
| 64 | - * |
|
| 65 | - * @param array $dest: Arreglo con la forma array( |
|
| 66 | - * 'email destinatario 1' => 'nombre destinatario 1', |
|
| 67 | - * 'email destinatario 2' => 'nombre destinatario 2' |
|
| 68 | - * ) |
|
| 69 | - * @param string $HTML: Contenido en HTML del email |
|
| 70 | - * @param string $titulo: Asunto del email |
|
| 71 | - * @param bool $is_smtp: Define si se hará la conexión a través de SMTP o no |
|
| 72 | - * @param array $adj: Arreglo con direccion local de los adjuntos a enviar, con la forma array( |
|
| 73 | - * 'ruta archivo 1', |
|
| 74 | - * 'ruta archivo 2' |
|
| 75 | - * ) |
|
| 76 | - * |
|
| 77 | - * @return string|bool true si fue enviado correctamente, string con el Error descrito por PHPMailer |
|
| 78 | - */ |
|
| 63 | + * Envía un correo electrónico utilizando PHPMailer |
|
| 64 | + * |
|
| 65 | + * @param array $dest: Arreglo con la forma array( |
|
| 66 | + * 'email destinatario 1' => 'nombre destinatario 1', |
|
| 67 | + * 'email destinatario 2' => 'nombre destinatario 2' |
|
| 68 | + * ) |
|
| 69 | + * @param string $HTML: Contenido en HTML del email |
|
| 70 | + * @param string $titulo: Asunto del email |
|
| 71 | + * @param bool $is_smtp: Define si se hará la conexión a través de SMTP o no |
|
| 72 | + * @param array $adj: Arreglo con direccion local de los adjuntos a enviar, con la forma array( |
|
| 73 | + * 'ruta archivo 1', |
|
| 74 | + * 'ruta archivo 2' |
|
| 75 | + * ) |
|
| 76 | + * |
|
| 77 | + * @return string|bool true si fue enviado correctamente, string con el Error descrito por PHPMailer |
|
| 78 | + */ |
|
| 79 | 79 | final public static function send_mail(array $dest, string $HTML, string $titulo, bool $is_smtp = true, array $adj = []) { |
| 80 | 80 | global $config; |
| 81 | 81 | |
@@ -104,12 +104,12 @@ discard block |
||
| 104 | 104 | //------------------------------------------------ |
| 105 | 105 | |
| 106 | 106 | /** |
| 107 | - * Plantilla estándar que muestra de forma amigable el texto, utiliza bootstrap |
|
| 108 | - * |
|
| 109 | - * @param string $content: Cadena de texto en HTML, puede ser en bootstrap |
|
| 110 | - * |
|
| 111 | - * @return string con el HTML para enviar |
|
| 112 | - */ |
|
| 107 | + * Plantilla estándar que muestra de forma amigable el texto, utiliza bootstrap |
|
| 108 | + * |
|
| 109 | + * @param string $content: Cadena de texto en HTML, puede ser en bootstrap |
|
| 110 | + * |
|
| 111 | + * @return string con el HTML para enviar |
|
| 112 | + */ |
|
| 113 | 113 | final public static function plantilla(string $content) : string { |
| 114 | 114 | return ' |
| 115 | 115 | <html> |
@@ -19,28 +19,28 @@ discard block |
||
| 19 | 19 | |
| 20 | 20 | final class Arrays extends \Twig_Extension { |
| 21 | 21 | |
| 22 | - //------------------------------------------------ |
|
| 22 | + //------------------------------------------------ |
|
| 23 | 23 | |
| 24 | 24 | /** |
| 25 | - * Suma los contenidos del segundo arreglo en el primer arreglo, en las coincidencias de llaves. |
|
| 26 | - * |
|
| 27 | - * Si el primer arreglo está vacío, copiará todo el segundo arreglo en el primero. |
|
| 28 | - * |
|
| 29 | - * Si el segundo arreglo está vacío, copiará todo el primer arreglo en el segundo. |
|
| 30 | - * |
|
| 31 | - * Si el arreglo $a tiene una estructura distinta a $b, la estructura de $a queda intacta y sólamente, |
|
| 32 | - * se hará sumas en las posiciones donde haya coincidencias de llaves. |
|
| 33 | - * |
|
| 34 | - * El valor null será tomado como cero. |
|
| 35 | - * |
|
| 36 | - * @param array $a: Primer arreglo |
|
| 37 | - * @param array $b: Segundo arreglo |
|
| 38 | - * |
|
| 39 | - * @throws RuntimeException si los arreglos son de distinto nivel |
|
| 40 | - * @throws RuntimeException si en la posición de coincidencia no se puede realizar una operación de suma |
|
| 41 | - * |
|
| 42 | - * @return array fusión de los dos arreglos, dejando intactal estructura de $a |
|
| 43 | - */ |
|
| 25 | + * Suma los contenidos del segundo arreglo en el primer arreglo, en las coincidencias de llaves. |
|
| 26 | + * |
|
| 27 | + * Si el primer arreglo está vacío, copiará todo el segundo arreglo en el primero. |
|
| 28 | + * |
|
| 29 | + * Si el segundo arreglo está vacío, copiará todo el primer arreglo en el segundo. |
|
| 30 | + * |
|
| 31 | + * Si el arreglo $a tiene una estructura distinta a $b, la estructura de $a queda intacta y sólamente, |
|
| 32 | + * se hará sumas en las posiciones donde haya coincidencias de llaves. |
|
| 33 | + * |
|
| 34 | + * El valor null será tomado como cero. |
|
| 35 | + * |
|
| 36 | + * @param array $a: Primer arreglo |
|
| 37 | + * @param array $b: Segundo arreglo |
|
| 38 | + * |
|
| 39 | + * @throws RuntimeException si los arreglos son de distinto nivel |
|
| 40 | + * @throws RuntimeException si en la posición de coincidencia no se puede realizar una operación de suma |
|
| 41 | + * |
|
| 42 | + * @return array fusión de los dos arreglos, dejando intactal estructura de $a |
|
| 43 | + */ |
|
| 44 | 44 | final public static function arrays_sum(array $a, array $b) : array { |
| 45 | 45 | # Si alguno está vacío |
| 46 | 46 | if(sizeof($a) == 0) { |
@@ -84,13 +84,13 @@ discard block |
||
| 84 | 84 | //------------------------------------------------ |
| 85 | 85 | |
| 86 | 86 | /** |
| 87 | - * Dado un índice asociativo y un arreglo, devuelve el índice numérico correspondiente al asociativo |
|
| 88 | - * |
|
| 89 | - * @param string $index: Índice asociativo del arreglo |
|
| 90 | - * @param array $a: Arreglo a evaluar |
|
| 91 | - * |
|
| 92 | - * @return int el índice correspondiente, -1 si no existe el indice |
|
| 93 | - */ |
|
| 87 | + * Dado un índice asociativo y un arreglo, devuelve el índice numérico correspondiente al asociativo |
|
| 88 | + * |
|
| 89 | + * @param string $index: Índice asociativo del arreglo |
|
| 90 | + * @param array $a: Arreglo a evaluar |
|
| 91 | + * |
|
| 92 | + * @return int el índice correspondiente, -1 si no existe el indice |
|
| 93 | + */ |
|
| 94 | 94 | final public static function get_key_by_index(string $index, array $a) : int { |
| 95 | 95 | $i = 0; |
| 96 | 96 | foreach ($a as $key => $val) { |
@@ -105,14 +105,14 @@ discard block |
||
| 105 | 105 | //------------------------------------------------ |
| 106 | 106 | |
| 107 | 107 | /** |
| 108 | - * Elimina todos los elementos repetidos de un array |
|
| 109 | - * (string) '1' se considera igual a (int) 1 |
|
| 110 | - * |
|
| 111 | - * @param array $a: Arreglo a evaluar |
|
| 112 | - * |
|
| 113 | - * @return array devuelve un arreglo sin elementos repetidos |
|
| 114 | - * http://stackoverflow.com/questions/8321620/array-unique-vs-array-flip |
|
| 115 | - */ |
|
| 108 | + * Elimina todos los elementos repetidos de un array |
|
| 109 | + * (string) '1' se considera igual a (int) 1 |
|
| 110 | + * |
|
| 111 | + * @param array $a: Arreglo a evaluar |
|
| 112 | + * |
|
| 113 | + * @return array devuelve un arreglo sin elementos repetidos |
|
| 114 | + * http://stackoverflow.com/questions/8321620/array-unique-vs-array-flip |
|
| 115 | + */ |
|
| 116 | 116 | final public static function unique_array(array $a) : array { |
| 117 | 117 | return array_keys(array_flip($a)); |
| 118 | 118 | } |
@@ -120,12 +120,12 @@ discard block |
||
| 120 | 120 | //------------------------------------------------ |
| 121 | 121 | |
| 122 | 122 | /** |
| 123 | - * Evalúa si un arreglo es de tipo asociativo o no |
|
| 124 | - * |
|
| 125 | - * @param array $a: Arreglo a evaluar |
|
| 126 | - * |
|
| 127 | - * @return bool false si no lo es, true si lo es |
|
| 128 | - */ |
|
| 123 | + * Evalúa si un arreglo es de tipo asociativo o no |
|
| 124 | + * |
|
| 125 | + * @param array $a: Arreglo a evaluar |
|
| 126 | + * |
|
| 127 | + * @return bool false si no lo es, true si lo es |
|
| 128 | + */ |
|
| 129 | 129 | final public static function is_assoc(array $a) : bool { |
| 130 | 130 | if(sizeof($a) === 0) { |
| 131 | 131 | return false; |
@@ -137,12 +137,12 @@ discard block |
||
| 137 | 137 | //------------------------------------------------ |
| 138 | 138 | |
| 139 | 139 | /** |
| 140 | - * Evalúa si un arreglo es secuencial (de índices numéricos) |
|
| 141 | - * |
|
| 142 | - * @param array $a: Arreglo a evaluar |
|
| 143 | - * |
|
| 144 | - * @return bool false si no lo es, true si lo es |
|
| 145 | - */ |
|
| 140 | + * Evalúa si un arreglo es secuencial (de índices numéricos) |
|
| 141 | + * |
|
| 142 | + * @param array $a: Arreglo a evaluar |
|
| 143 | + * |
|
| 144 | + * @return bool false si no lo es, true si lo es |
|
| 145 | + */ |
|
| 146 | 146 | final public static function is_numeric_array(array $a) : bool { |
| 147 | 147 | return !self::is_assoc($a); |
| 148 | 148 | } |
@@ -150,12 +150,12 @@ discard block |
||
| 150 | 150 | //------------------------------------------------ |
| 151 | 151 | |
| 152 | 152 | /** |
| 153 | - * Obtiene de forma random un elemento de un arreglo |
|
| 154 | - * |
|
| 155 | - * @param array $a: Arreglo a evaluar |
|
| 156 | - * |
|
| 157 | - * @return mixed elemento random dentro del arreglo |
|
| 158 | - */ |
|
| 153 | + * Obtiene de forma random un elemento de un arreglo |
|
| 154 | + * |
|
| 155 | + * @param array $a: Arreglo a evaluar |
|
| 156 | + * |
|
| 157 | + * @return mixed elemento random dentro del arreglo |
|
| 158 | + */ |
|
| 159 | 159 | final public static function array_random_element(array $a) { |
| 160 | 160 | return $a[array_rand($a)]; |
| 161 | 161 | } |
@@ -163,10 +163,10 @@ discard block |
||
| 163 | 163 | //------------------------------------------------ |
| 164 | 164 | |
| 165 | 165 | /** |
| 166 | - * Se obtiene de Twig_Extension y sirve para que cada función esté disponible como etiqueta en twig |
|
| 167 | - * |
|
| 168 | - * @return array con todas las funciones con sus respectivos nombres de acceso en plantillas twig |
|
| 169 | - */ |
|
| 166 | + * Se obtiene de Twig_Extension y sirve para que cada función esté disponible como etiqueta en twig |
|
| 167 | + * |
|
| 168 | + * @return array con todas las funciones con sus respectivos nombres de acceso en plantillas twig |
|
| 169 | + */ |
|
| 170 | 170 | public function getFunctions() : array { |
| 171 | 171 | return array( |
| 172 | 172 | new \Twig_Function('get_key_by_index', array($this, 'get_key_by_index')), |
@@ -181,10 +181,10 @@ discard block |
||
| 181 | 181 | //------------------------------------------------ |
| 182 | 182 | |
| 183 | 183 | /** |
| 184 | - * Identificador único para la extensión de twig |
|
| 185 | - * |
|
| 186 | - * @return string con el nombre de la extensión |
|
| 187 | - */ |
|
| 184 | + * Identificador único para la extensión de twig |
|
| 185 | + * |
|
| 186 | + * @return string con el nombre de la extensión |
|
| 187 | + */ |
|
| 188 | 188 | public function getName() : string { |
| 189 | 189 | return 'ocrend_framework_helper_arrays'; |
| 190 | 190 | } |
@@ -43,32 +43,32 @@ discard block |
||
| 43 | 43 | */ |
| 44 | 44 | final public static function arrays_sum(array $a, array $b) : array { |
| 45 | 45 | # Si alguno está vacío |
| 46 | - if(sizeof($a) == 0) { |
|
| 46 | + if (sizeof($a) == 0) { |
|
| 47 | 47 | return $b; |
| 48 | - } else if(sizeof($b) == 0) { |
|
| 48 | + } else if (sizeof($b) == 0) { |
|
| 49 | 49 | return $a; |
| 50 | 50 | } |
| 51 | 51 | |
| 52 | 52 | # Recorrer el segundo arreglo |
| 53 | - foreach($b as $llave => $contenido) { |
|
| 53 | + foreach ($b as $llave => $contenido) { |
|
| 54 | 54 | |
| 55 | 55 | # Desnivel |
| 56 | - if(is_array($contenido)) { |
|
| 57 | - throw new \RuntimeException('El arreglo $b en la llave '.$llave.' es un arreglo y no puede operar.'); |
|
| 56 | + if (is_array($contenido)) { |
|
| 57 | + throw new \RuntimeException('El arreglo $b en la llave ' . $llave . ' es un arreglo y no puede operar.'); |
|
| 58 | 58 | break; |
| 59 | 59 | } |
| 60 | 60 | |
| 61 | 61 | # Existencia de la llave |
| 62 | - if(array_key_exists($llave,$a)) { |
|
| 62 | + if (array_key_exists($llave, $a)) { |
|
| 63 | 63 | # Excepciones de uso |
| 64 | - if(is_array($a[$llave])) { |
|
| 65 | - throw new \RuntimeException('El arreglo $a en la llave '.$llave.' es un arreglo y no puede operar.'); |
|
| 64 | + if (is_array($a[$llave])) { |
|
| 65 | + throw new \RuntimeException('El arreglo $a en la llave ' . $llave . ' es un arreglo y no puede operar.'); |
|
| 66 | 66 | break; |
| 67 | - } else if(!is_numeric($a[$llave]) && null !== $a[$llave]) { |
|
| 68 | - throw new \RuntimeException('El arreglo $a en la llave '.$llave.' no es un número y no puede operar.'); |
|
| 67 | + } else if (!is_numeric($a[$llave]) && null !== $a[$llave]) { |
|
| 68 | + throw new \RuntimeException('El arreglo $a en la llave ' . $llave . ' no es un número y no puede operar.'); |
|
| 69 | 69 | break; |
| 70 | - } else if(!is_numeric($b[$llave]) && null !== $b[$llave]) { |
|
| 71 | - throw new \RuntimeException('El arreglo $b en la llave '.$llave.' no es un número y no puede operar.'); |
|
| 70 | + } else if (!is_numeric($b[$llave]) && null !== $b[$llave]) { |
|
| 71 | + throw new \RuntimeException('El arreglo $b en la llave ' . $llave . ' no es un número y no puede operar.'); |
|
| 72 | 72 | break; |
| 73 | 73 | } |
| 74 | 74 | |
@@ -94,7 +94,7 @@ discard block |
||
| 94 | 94 | final public static function get_key_by_index(string $index, array $a) : int { |
| 95 | 95 | $i = 0; |
| 96 | 96 | foreach ($a as $key => $val) { |
| 97 | - if($key == $index) { |
|
| 97 | + if ($key == $index) { |
|
| 98 | 98 | return (int) $i; |
| 99 | 99 | } |
| 100 | 100 | $i++; |
@@ -127,7 +127,7 @@ discard block |
||
| 127 | 127 | * @return bool false si no lo es, true si lo es |
| 128 | 128 | */ |
| 129 | 129 | final public static function is_assoc(array $a) : bool { |
| 130 | - if(sizeof($a) === 0) { |
|
| 130 | + if (sizeof($a) === 0) { |
|
| 131 | 131 | return false; |
| 132 | 132 | } |
| 133 | 133 | |
@@ -91,7 +91,7 @@ discard block |
||
| 91 | 91 | */ |
| 92 | 92 | final private function setCollectionRule(string $index, string $rule) { |
| 93 | 93 | # Verificar si la regla existe |
| 94 | - if(!in_array($rule,self::RULES)) { |
|
| 94 | + if (!in_array($rule, self::RULES)) { |
|
| 95 | 95 | throw new \RuntimeException('La regla ' . $rule . ' no existe.'); |
| 96 | 96 | } |
| 97 | 97 | # Definir la regla para la ruta |
@@ -103,14 +103,14 @@ discard block |
||
| 103 | 103 | */ |
| 104 | 104 | final private function checkRequests() { |
| 105 | 105 | # Verificar si existe peticiones |
| 106 | - if(null !== $this->requestUri) { |
|
| 107 | - $this->real_request = explode('/',$this->requestUri); |
|
| 106 | + if (null !== $this->requestUri) { |
|
| 107 | + $this->real_request = explode('/', $this->requestUri); |
|
| 108 | 108 | $this->routerCollection['/controller'] = $this->real_request[0]; |
| 109 | 109 | } |
| 110 | 110 | |
| 111 | 111 | # Setear las siguientes rutas |
| 112 | - $this->routerCollection['/method'] = array_key_exists(1,$this->real_request) ? $this->real_request[1] : null; |
|
| 113 | - $this->routerCollection['/id'] = array_key_exists(2,$this->real_request) ? $this->real_request[2] : null; |
|
| 112 | + $this->routerCollection['/method'] = array_key_exists(1, $this->real_request) ? $this->real_request[1] : null; |
|
| 113 | + $this->routerCollection['/id'] = array_key_exists(2, $this->real_request) ? $this->real_request[2] : null; |
|
| 114 | 114 | } |
| 115 | 115 | |
| 116 | 116 | /** |
@@ -123,7 +123,7 @@ discard block |
||
| 123 | 123 | */ |
| 124 | 124 | final public function setRoute(string $index, string $rule = 'none') { |
| 125 | 125 | # Nombres de rutas no permitidos |
| 126 | - if(in_array($index,['/controller','/method','/id'])) { |
|
| 126 | + if (in_array($index, ['/controller', '/method', '/id'])) { |
|
| 127 | 127 | throw new \RuntimeException('No puede definirse ' . $index . ' como índice en la ruta.'); |
| 128 | 128 | } |
| 129 | 129 | |
@@ -135,8 +135,8 @@ discard block |
||
| 135 | 135 | |
| 136 | 136 | # Definir la ruta y regla |
| 137 | 137 | $lastRoute = sizeof($this->routerCollection); |
| 138 | - $this->routerCollection[$index] = array_key_exists($lastRoute,$this->real_request) ? $this->real_request[$lastRoute] : null; |
|
| 139 | - $this->setCollectionRule($index,$rule); |
|
| 138 | + $this->routerCollection[$index] = array_key_exists($lastRoute, $this->real_request) ? $this->real_request[$lastRoute] : null; |
|
| 139 | + $this->setCollectionRule($index, $rule); |
|
| 140 | 140 | } |
| 141 | 141 | |
| 142 | 142 | /** |
@@ -149,7 +149,7 @@ discard block |
||
| 149 | 149 | */ |
| 150 | 150 | final public function getRoute(string $index) { |
| 151 | 151 | # Verificar existencia de ruta |
| 152 | - if(!array_key_exists($index,$this->routerCollection)) { |
|
| 152 | + if (!array_key_exists($index, $this->routerCollection)) { |
|
| 153 | 153 | throw new \RuntimeException('La ruta ' . $index . ' no está definida en el controlador.'); |
| 154 | 154 | } |
| 155 | 155 | |
@@ -157,7 +157,7 @@ discard block |
||
| 157 | 157 | $ruta = $this->routerCollection[$index]; |
| 158 | 158 | |
| 159 | 159 | # Retornar ruta con la regla definida aplicada |
| 160 | - switch($this->routerCollectionRules[$index]) { |
|
| 160 | + switch ($this->routerCollectionRules[$index]) { |
|
| 161 | 161 | case 'none': |
| 162 | 162 | return $ruta; |
| 163 | 163 | case 'letters': |
@@ -211,7 +211,7 @@ discard block |
||
| 211 | 211 | */ |
| 212 | 212 | final public function getId(bool $with_rules = false) { |
| 213 | 213 | $id = $this->routerCollection['/id']; |
| 214 | - if($with_rules) { |
|
| 214 | + if ($with_rules) { |
|
| 215 | 215 | return (null !== $id && is_numeric($id) && $id > 0) ? (int) $id : null; |
| 216 | 216 | } |
| 217 | 217 | |
@@ -225,10 +225,10 @@ discard block |
||
| 225 | 225 | */ |
| 226 | 226 | final public function executeController() { |
| 227 | 227 | # Definir controlador |
| 228 | - if(null != ($controller = $this->getController())) { |
|
| 228 | + if (null != ($controller = $this->getController())) { |
|
| 229 | 229 | $controller = $controller . 'Controller'; |
| 230 | 230 | |
| 231 | - if(!is_readable('app/controllers/' . $controller . '.php')) { |
|
| 231 | + if (!is_readable('app/controllers/' . $controller . '.php')) { |
|
| 232 | 232 | $controller = 'errorController'; |
| 233 | 233 | } |
| 234 | 234 | |
@@ -23,32 +23,32 @@ discard block |
||
| 23 | 23 | abstract class Models { |
| 24 | 24 | |
| 25 | 25 | /** |
| 26 | - * Tiene siempre el id pasado por la ruta, en caso de no haber ninguno, será cero. |
|
| 27 | - * |
|
| 28 | - * @var int |
|
| 29 | - */ |
|
| 26 | + * Tiene siempre el id pasado por la ruta, en caso de no haber ninguno, será cero. |
|
| 27 | + * |
|
| 28 | + * @var int |
|
| 29 | + */ |
|
| 30 | 30 | protected $id = 0; |
| 31 | 31 | |
| 32 | 32 | /** |
| 33 | - * Contiene una instancia del helper para funciones |
|
| 34 | - * |
|
| 35 | - * @var \Ocrend\Kernel\Helpers\Functions |
|
| 36 | - */ |
|
| 33 | + * Contiene una instancia del helper para funciones |
|
| 34 | + * |
|
| 35 | + * @var \Ocrend\Kernel\Helpers\Functions |
|
| 36 | + */ |
|
| 37 | 37 | protected $functions; |
| 38 | 38 | |
| 39 | 39 | /** |
| 40 | - * Contiene el id del usuario que tiene su sesión iniciada. |
|
| 41 | - * |
|
| 42 | - * @var int|null con id del usuario |
|
| 43 | - */ |
|
| 40 | + * Contiene el id del usuario que tiene su sesión iniciada. |
|
| 41 | + * |
|
| 42 | + * @var int|null con id del usuario |
|
| 43 | + */ |
|
| 44 | 44 | protected $id_user = null; |
| 45 | 45 | |
| 46 | 46 | /** |
| 47 | - * Inicia la configuración inicial de cualquier modelo |
|
| 48 | - * |
|
| 49 | - * @param IRouter $router: Instancia de un Router |
|
| 50 | - * |
|
| 51 | - */ |
|
| 47 | + * Inicia la configuración inicial de cualquier modelo |
|
| 48 | + * |
|
| 49 | + * @param IRouter $router: Instancia de un Router |
|
| 50 | + * |
|
| 51 | + */ |
|
| 52 | 52 | protected function __construct(IRouter $router = null) { |
| 53 | 53 | global $session, $config; |
| 54 | 54 | |
@@ -63,19 +63,19 @@ discard block |
||
| 63 | 63 | |
| 64 | 64 | # Verificar sesión del usuario |
| 65 | 65 | if(null !== $session->get('user_id') && $session->get('unique_session') == $config['sessions']['unique']) { |
| 66 | - $this->id_user = $session->get('user_id'); |
|
| 66 | + $this->id_user = $session->get('user_id'); |
|
| 67 | 67 | } |
| 68 | 68 | } |
| 69 | 69 | |
| 70 | 70 | /** |
| 71 | - * Asigna el id desde un modelo, ideal para cuando queremos darle un valor numérico |
|
| 72 | - * que proviene de un formulario y puede ser inseguro. |
|
| 73 | - * |
|
| 74 | - * @param mixed $id : Id a asignar en $this->id |
|
| 75 | - * @param string $default_msg : Mensaje a mostrar en caso de que no se pueda asignar |
|
| 76 | - * |
|
| 77 | - * @throws ModelsException |
|
| 78 | - */ |
|
| 71 | + * Asigna el id desde un modelo, ideal para cuando queremos darle un valor numérico |
|
| 72 | + * que proviene de un formulario y puede ser inseguro. |
|
| 73 | + * |
|
| 74 | + * @param mixed $id : Id a asignar en $this->id |
|
| 75 | + * @param string $default_msg : Mensaje a mostrar en caso de que no se pueda asignar |
|
| 76 | + * |
|
| 77 | + * @throws ModelsException |
|
| 78 | + */ |
|
| 79 | 79 | protected function setId($id, string $default_msg = 'No puedede asignarse el id.') { |
| 80 | 80 | if(null == $id || !is_numeric($id) || $id <= 0) { |
| 81 | 81 | throw new ModelsException($default_msg); |
@@ -85,8 +85,8 @@ discard block |
||
| 85 | 85 | } |
| 86 | 86 | |
| 87 | 87 | /** |
| 88 | - * Cierra el modelo |
|
| 89 | - */ |
|
| 88 | + * Cierra el modelo |
|
| 89 | + */ |
|
| 90 | 90 | protected function __destruct() {} |
| 91 | 91 | |
| 92 | 92 | } |
| 93 | 93 | \ No newline at end of file |
@@ -20,7 +20,7 @@ discard block |
||
| 20 | 20 | * @author Brayan Narváez <[email protected]> |
| 21 | 21 | */ |
| 22 | 22 | |
| 23 | -abstract class Models { |
|
| 23 | +abstract class Models { |
|
| 24 | 24 | |
| 25 | 25 | /** |
| 26 | 26 | * Tiene siempre el id pasado por la ruta, en caso de no haber ninguno, será cero. |
@@ -53,7 +53,7 @@ discard block |
||
| 53 | 53 | global $session, $config; |
| 54 | 54 | |
| 55 | 55 | # Id captado por la ruta |
| 56 | - if(null != $router) { |
|
| 56 | + if (null != $router) { |
|
| 57 | 57 | $this->id = $router->getId(true); |
| 58 | 58 | $this->id = null == $this->id ? 0 : $this->id; |
| 59 | 59 | } |
@@ -62,7 +62,7 @@ discard block |
||
| 62 | 62 | $this->functions = new Functions(); |
| 63 | 63 | |
| 64 | 64 | # Verificar sesión del usuario |
| 65 | - if(null !== $session->get('user_id') && $session->get('unique_session') == $config['sessions']['unique']) { |
|
| 65 | + if (null !== $session->get('user_id') && $session->get('unique_session') == $config['sessions']['unique']) { |
|
| 66 | 66 | $this->id_user = $session->get('user_id'); |
| 67 | 67 | } |
| 68 | 68 | } |
@@ -77,7 +77,7 @@ discard block |
||
| 77 | 77 | * @throws ModelsException |
| 78 | 78 | */ |
| 79 | 79 | protected function setId($id, string $default_msg = 'No puedede asignarse el id.') { |
| 80 | - if(null == $id || !is_numeric($id) || $id <= 0) { |
|
| 80 | + if (null == $id || !is_numeric($id) || $id <= 0) { |
|
| 81 | 81 | throw new ModelsException($default_msg); |
| 82 | 82 | } |
| 83 | 83 | |
@@ -20,13 +20,13 @@ discard block |
||
| 20 | 20 | final class Strings extends \Twig_Extension { |
| 21 | 21 | //------------------------------------------------ |
| 22 | 22 | /** |
| 23 | - * Convierte un tiempo dado al formato hace 1 minuto, hace 2 horas, hace 1 año ... |
|
| 24 | - * |
|
| 25 | - * @param int $from: Tiempo en segundo desde donde se desea contar |
|
| 26 | - * @param int $to: Tiempo en segundo hasta donde se desea contar, si no se pasa por defecto es el tiempo actual |
|
| 27 | - * |
|
| 28 | - * @return string con la forma: hace 20 segundos, hace 1 minuto, hace 2 horas, hace 4 días, hace 1 semana, hace 3 meses, hace 1 año ... |
|
| 29 | - */ |
|
| 23 | + * Convierte un tiempo dado al formato hace 1 minuto, hace 2 horas, hace 1 año ... |
|
| 24 | + * |
|
| 25 | + * @param int $from: Tiempo en segundo desde donde se desea contar |
|
| 26 | + * @param int $to: Tiempo en segundo hasta donde se desea contar, si no se pasa por defecto es el tiempo actual |
|
| 27 | + * |
|
| 28 | + * @return string con la forma: hace 20 segundos, hace 1 minuto, hace 2 horas, hace 4 días, hace 1 semana, hace 3 meses, hace 1 año ... |
|
| 29 | + */ |
|
| 30 | 30 | final public static function amigable_time(int $from, int $to = 0) : string { |
| 31 | 31 | $to = $to == 0 ? time() : $to; |
| 32 | 32 | $form = new \DateTime(date('Y-m-d H:i:s', $from)); |
@@ -65,39 +65,39 @@ discard block |
||
| 65 | 65 | } |
| 66 | 66 | //------------------------------------------------ |
| 67 | 67 | /** |
| 68 | - * Compara un string hash con un string sin hash, si el string sin hash al encriptar posee la misma llave que hash, son iguales |
|
| 69 | - * |
|
| 70 | - * @param string $hash: Hash con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G |
|
| 71 | - * @param string $s2: Cadena de texto a comparar |
|
| 72 | - * |
|
| 73 | - * @example Strings::chash('$2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G','123456'); //return true |
|
| 74 | - * |
|
| 75 | - * @return bool true si $s2 contiene la misma llave que $hash, por tanto el contenido de $hash es $s2, de lo contrario false |
|
| 76 | - */ |
|
| 68 | + * Compara un string hash con un string sin hash, si el string sin hash al encriptar posee la misma llave que hash, son iguales |
|
| 69 | + * |
|
| 70 | + * @param string $hash: Hash con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G |
|
| 71 | + * @param string $s2: Cadena de texto a comparar |
|
| 72 | + * |
|
| 73 | + * @example Strings::chash('$2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G','123456'); //return true |
|
| 74 | + * |
|
| 75 | + * @return bool true si $s2 contiene la misma llave que $hash, por tanto el contenido de $hash es $s2, de lo contrario false |
|
| 76 | + */ |
|
| 77 | 77 | final public static function chash(string $hash, string $s2) : bool { |
| 78 | 78 | return $hash == crypt($s2, substr($hash, 0, 29)); |
| 79 | - } |
|
| 80 | - //------------------------------------------------ |
|
| 79 | + } |
|
| 80 | + //------------------------------------------------ |
|
| 81 | 81 | /** |
| 82 | - * Devuelve un hash DINÁMICO, para comparar un hash con un elemento se utiliza chash |
|
| 83 | - * |
|
| 84 | - * @param string $p: Cadena de texto a encriptar |
|
| 85 | - * |
|
| 86 | - * @return string Hash, con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G |
|
| 87 | - */ |
|
| 82 | + * Devuelve un hash DINÁMICO, para comparar un hash con un elemento se utiliza chash |
|
| 83 | + * |
|
| 84 | + * @param string $p: Cadena de texto a encriptar |
|
| 85 | + * |
|
| 86 | + * @return string Hash, con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G |
|
| 87 | + */ |
|
| 88 | 88 | final public static function hash(string $p) : string { |
| 89 | 89 | return crypt($p, '$2a$10$' . substr(sha1(mt_rand()),0,22)); |
| 90 | 90 | } |
| 91 | 91 | //------------------------------------------------ |
| 92 | 92 | /** |
| 93 | - * Calcula el tiempo de diferencia entre dos fechas |
|
| 94 | - * |
|
| 95 | - * @param string $ini: Fecha menor con el formato d-m-Y ó d/m/Y |
|
| 96 | - * @param string $fin: Fecha mayor con el formato d-m-Y ó d/m/Y |
|
| 97 | - * |
|
| 98 | - * @return int con la diferencia de tiempo en días |
|
| 99 | - * |
|
| 100 | - */ |
|
| 93 | + * Calcula el tiempo de diferencia entre dos fechas |
|
| 94 | + * |
|
| 95 | + * @param string $ini: Fecha menor con el formato d-m-Y ó d/m/Y |
|
| 96 | + * @param string $fin: Fecha mayor con el formato d-m-Y ó d/m/Y |
|
| 97 | + * |
|
| 98 | + * @return int con la diferencia de tiempo en días |
|
| 99 | + * |
|
| 100 | + */ |
|
| 101 | 101 | final public static function date_difference(string $ini, string $fin) : int { |
| 102 | 102 | $ini_i = explode('-',str_replace('/','-',$ini)); |
| 103 | 103 | $fin_i = explode('-',str_replace('/','-',$fin)); |
@@ -105,90 +105,90 @@ discard block |
||
| 105 | 105 | } |
| 106 | 106 | //------------------------------------------------ |
| 107 | 107 | /** |
| 108 | - * Calcula la edad de una persona segun la fecha de nacimiento |
|
| 109 | - * |
|
| 110 | - * @param string $cumple: Fecha de nacimiento con el formato d-m-Y ó d/m/Y |
|
| 111 | - * |
|
| 112 | - * @return int con la edad |
|
| 113 | - * |
|
| 114 | - */ |
|
| 108 | + * Calcula la edad de una persona segun la fecha de nacimiento |
|
| 109 | + * |
|
| 110 | + * @param string $cumple: Fecha de nacimiento con el formato d-m-Y ó d/m/Y |
|
| 111 | + * |
|
| 112 | + * @return int con la edad |
|
| 113 | + * |
|
| 114 | + */ |
|
| 115 | 115 | final public static function calculate_age(string $cumple) : int { |
| 116 | 116 | $age = explode('.', (string) (self::date_difference($cumple,date('d-m-Y',time())) / 365)); |
| 117 | 117 | return (int) $age[0]; |
| 118 | 118 | } |
| 119 | 119 | //------------------------------------------------ |
| 120 | 120 | /** |
| 121 | - * Calcula cuántos días tiene el mes actual |
|
| 122 | - * |
|
| 123 | - * @return integer con la cantidad de días del mes |
|
| 124 | - * |
|
| 125 | - */ |
|
| 121 | + * Calcula cuántos días tiene el mes actual |
|
| 122 | + * |
|
| 123 | + * @return integer con la cantidad de días del mes |
|
| 124 | + * |
|
| 125 | + */ |
|
| 126 | 126 | final public static function days_of_month() : int { |
| 127 | 127 | return cal_days_in_month(CAL_GREGORIAN, (int) date('m',time()), (int) date('Y',time())); |
| 128 | 128 | } |
| 129 | 129 | //------------------------------------------------ |
| 130 | 130 | /** |
| 131 | - * Verifica si una cadena de texto tiene forma de email |
|
| 132 | - * |
|
| 133 | - * @param string $address: Cadena de texto con el email |
|
| 134 | - * |
|
| 135 | - * @return mixed devuelve TRUE si es un email y FALSE si no lo es |
|
| 136 | - */ |
|
| 131 | + * Verifica si una cadena de texto tiene forma de email |
|
| 132 | + * |
|
| 133 | + * @param string $address: Cadena de texto con el email |
|
| 134 | + * |
|
| 135 | + * @return mixed devuelve TRUE si es un email y FALSE si no lo es |
|
| 136 | + */ |
|
| 137 | 137 | final public static function is_email(string $address) { |
| 138 | 138 | return filter_var($address, FILTER_VALIDATE_EMAIL); |
| 139 | 139 | } |
| 140 | 140 | //------------------------------------------------ |
| 141 | 141 | /** |
| 142 | - * Remueve todos los espacios en blanco de un string |
|
| 143 | - * |
|
| 144 | - * @param string $s: Cadena de texto a convertir |
|
| 145 | - * |
|
| 146 | - * @return string del texto sin espacios |
|
| 147 | - */ |
|
| 142 | + * Remueve todos los espacios en blanco de un string |
|
| 143 | + * |
|
| 144 | + * @param string $s: Cadena de texto a convertir |
|
| 145 | + * |
|
| 146 | + * @return string del texto sin espacios |
|
| 147 | + */ |
|
| 148 | 148 | final public static function remove_spaces(string $s) : string { |
| 149 | 149 | return trim(str_replace(' ','',$s)); |
| 150 | 150 | } |
| 151 | 151 | //------------------------------------------------ |
| 152 | 152 | /** |
| 153 | - * Analiza si una cadena de texto es alfanumérica |
|
| 154 | - * |
|
| 155 | - * @param string $s: Cadena de texto a verificar |
|
| 156 | - * |
|
| 157 | - * @return bool, verdadero si es alfanumerica, falso si no |
|
| 158 | - */ |
|
| 153 | + * Analiza si una cadena de texto es alfanumérica |
|
| 154 | + * |
|
| 155 | + * @param string $s: Cadena de texto a verificar |
|
| 156 | + * |
|
| 157 | + * @return bool, verdadero si es alfanumerica, falso si no |
|
| 158 | + */ |
|
| 159 | 159 | final public static function alphanumeric(string $s) : bool { |
| 160 | 160 | return ctype_alnum(self::remove_spaces($s)); |
| 161 | 161 | } |
| 162 | 162 | //------------------------------------------------ |
| 163 | 163 | /** |
| 164 | - * Analiza si una cadena de texto verificando si sólamente tiene letras |
|
| 165 | - * |
|
| 166 | - * @param string $s: Cadena de texto a verificar |
|
| 167 | - * |
|
| 168 | - * @return bool, verdadero si sólamente tiene letras, falso si no |
|
| 169 | - */ |
|
| 164 | + * Analiza si una cadena de texto verificando si sólamente tiene letras |
|
| 165 | + * |
|
| 166 | + * @param string $s: Cadena de texto a verificar |
|
| 167 | + * |
|
| 168 | + * @return bool, verdadero si sólamente tiene letras, falso si no |
|
| 169 | + */ |
|
| 170 | 170 | final public static function only_letters(string $s) : bool { |
| 171 | 171 | return ctype_alpha(self::remove_spaces($s)); |
| 172 | 172 | } |
| 173 | 173 | //------------------------------------------------ |
| 174 | 174 | /** |
| 175 | - * Analiza si una cadena de texto contiene sólamente letras y números |
|
| 176 | - * |
|
| 177 | - * @param string $s: Cadena de texto a verificar |
|
| 178 | - * |
|
| 179 | - * @return bool, verdadero si sólamente contiene letras y números, falso si no |
|
| 180 | - */ |
|
| 175 | + * Analiza si una cadena de texto contiene sólamente letras y números |
|
| 176 | + * |
|
| 177 | + * @param string $s: Cadena de texto a verificar |
|
| 178 | + * |
|
| 179 | + * @return bool, verdadero si sólamente contiene letras y números, falso si no |
|
| 180 | + */ |
|
| 181 | 181 | final public static function letters_and_numbers(string $s) : bool { |
| 182 | 182 | return (boolean) preg_match('/^[\w.]*$/', self::remove_spaces($s)); |
| 183 | 183 | } |
| 184 | 184 | //------------------------------------------------ |
| 185 | 185 | /** |
| 186 | - * Convierte una expresión de texto, a una compatible con url amigables |
|
| 187 | - * |
|
| 188 | - * @param string $url: Cadena de texto a convertir |
|
| 189 | - * |
|
| 190 | - * @return string Cadena de texto con formato de url amigable |
|
| 191 | - */ |
|
| 186 | + * Convierte una expresión de texto, a una compatible con url amigables |
|
| 187 | + * |
|
| 188 | + * @param string $url: Cadena de texto a convertir |
|
| 189 | + * |
|
| 190 | + * @return string Cadena de texto con formato de url amigable |
|
| 191 | + */ |
|
| 192 | 192 | final public static function url_amigable(string $url) : string { |
| 193 | 193 | $url = strtolower($url); |
| 194 | 194 | $url = str_replace (['á', 'é', 'í', 'ó', 'ú', 'ñ'],['a', 'e', 'i', 'o', 'u', 'n'], $url); |
@@ -197,12 +197,12 @@ discard block |
||
| 197 | 197 | } |
| 198 | 198 | //------------------------------------------------ |
| 199 | 199 | /** |
| 200 | - * Convierte código BBCode en su equivalente HTML |
|
| 201 | - * |
|
| 202 | - * @param string $string: Código con formato BBCode dentro |
|
| 203 | - * |
|
| 204 | - * @return string del código BBCode transformado en HTML |
|
| 205 | - */ |
|
| 200 | + * Convierte código BBCode en su equivalente HTML |
|
| 201 | + * |
|
| 202 | + * @param string $string: Código con formato BBCode dentro |
|
| 203 | + * |
|
| 204 | + * @return string del código BBCode transformado en HTML |
|
| 205 | + */ |
|
| 206 | 206 | final public static function bbcode(string $string) : string { |
| 207 | 207 | $BBcode = array( |
| 208 | 208 | '/\[i\](.*?)\[\/i\]/is', |
@@ -250,58 +250,58 @@ discard block |
||
| 250 | 250 | } |
| 251 | 251 | //------------------------------------------------ |
| 252 | 252 | /** |
| 253 | - * Dice si un string comienza con un caracter especificado |
|
| 254 | - * |
|
| 255 | - * @param string $sx: Caracter de inicio |
|
| 256 | - * @param string $str: String a evaluar |
|
| 257 | - * @param bool $case_sensitive: Boolean para definir si será seible a mayúsculas o no |
|
| 258 | - * |
|
| 259 | - * @return bool True si comienza con el caracter especificado, False si no |
|
| 260 | - */ |
|
| 253 | + * Dice si un string comienza con un caracter especificado |
|
| 254 | + * |
|
| 255 | + * @param string $sx: Caracter de inicio |
|
| 256 | + * @param string $str: String a evaluar |
|
| 257 | + * @param bool $case_sensitive: Boolean para definir si será seible a mayúsculas o no |
|
| 258 | + * |
|
| 259 | + * @return bool True si comienza con el caracter especificado, False si no |
|
| 260 | + */ |
|
| 261 | 261 | final public static function begin_with(string $sx, string $str) : bool { |
| 262 | 262 | return (bool) (strlen($str) > 0 and $str[0] == $sx); |
| 263 | 263 | } |
| 264 | 264 | //------------------------------------------------ |
| 265 | 265 | /** |
| 266 | - * Dice si un string termina con una caracter especificado |
|
| 267 | - * |
|
| 268 | - * @param string $sx: Caracter del final |
|
| 269 | - * @param string $str: String a evaluar |
|
| 270 | - * |
|
| 271 | - * @return bool True si termina con el caracter especificado, False si no |
|
| 272 | - */ |
|
| 266 | + * Dice si un string termina con una caracter especificado |
|
| 267 | + * |
|
| 268 | + * @param string $sx: Caracter del final |
|
| 269 | + * @param string $str: String a evaluar |
|
| 270 | + * |
|
| 271 | + * @return bool True si termina con el caracter especificado, False si no |
|
| 272 | + */ |
|
| 273 | 273 | final public static function end_with(string $sx, string $str) : bool { |
| 274 | 274 | return (bool) (strlen($str) > 0 and $str[strlen($str) - 1] == $sx); |
| 275 | 275 | } |
| 276 | 276 | //------------------------------------------------ |
| 277 | 277 | /** |
| 278 | - * Ver si un string está contenido en otro |
|
| 279 | - * |
|
| 280 | - * @param $s: String contenido en $str |
|
| 281 | - * @param $str: String a evaluar |
|
| 282 | - * |
|
| 283 | - * @return bool True si $s está dentro de $str, False si no |
|
| 284 | - */ |
|
| 278 | + * Ver si un string está contenido en otro |
|
| 279 | + * |
|
| 280 | + * @param $s: String contenido en $str |
|
| 281 | + * @param $str: String a evaluar |
|
| 282 | + * |
|
| 283 | + * @return bool True si $s está dentro de $str, False si no |
|
| 284 | + */ |
|
| 285 | 285 | final public static function contain(string $s, string $str) : bool { |
| 286 | 286 | return (bool) (strpos($str, $s) !== false); |
| 287 | 287 | } |
| 288 | 288 | //------------------------------------------------ |
| 289 | 289 | /** |
| 290 | - * Devuelve la cantidad de palabras en un string |
|
| 291 | - * |
|
| 292 | - * @param $str: String a evaluar |
|
| 293 | - * |
|
| 294 | - * @return int Cantidad de palabras |
|
| 295 | - */ |
|
| 290 | + * Devuelve la cantidad de palabras en un string |
|
| 291 | + * |
|
| 292 | + * @param $str: String a evaluar |
|
| 293 | + * |
|
| 294 | + * @return int Cantidad de palabras |
|
| 295 | + */ |
|
| 296 | 296 | final public static function count_words(string $s) : int { |
| 297 | 297 | return (int) str_word_count($s,0); |
| 298 | 298 | } |
| 299 | 299 | //------------------------------------------------ |
| 300 | 300 | /** |
| 301 | - * Se obtiene de Twig_Extension y sirve para que cada función esté disponible como etiqueta en twig |
|
| 302 | - * |
|
| 303 | - * @return array Todas las funciones con sus respectivos nombres de acceso en plantillas twig |
|
| 304 | - */ |
|
| 301 | + * Se obtiene de Twig_Extension y sirve para que cada función esté disponible como etiqueta en twig |
|
| 302 | + * |
|
| 303 | + * @return array Todas las funciones con sus respectivos nombres de acceso en plantillas twig |
|
| 304 | + */ |
|
| 305 | 305 | public function getFunctions() : array { |
| 306 | 306 | return array( |
| 307 | 307 | new \Twig_Function('amigable_time', array($this, 'amigable_time')), |
@@ -325,10 +325,10 @@ discard block |
||
| 325 | 325 | } |
| 326 | 326 | //------------------------------------------------ |
| 327 | 327 | /** |
| 328 | - * Identificador único para la extensión de twig |
|
| 329 | - * |
|
| 330 | - * @return string Nombre de la extensión |
|
| 331 | - */ |
|
| 328 | + * Identificador único para la extensión de twig |
|
| 329 | + * |
|
| 330 | + * @return string Nombre de la extensión |
|
| 331 | + */ |
|
| 332 | 332 | public function getName() : string { |
| 333 | 333 | return 'ocrend_framework_helper_strings'; |
| 334 | 334 | } |
@@ -41,7 +41,7 @@ discard block |
||
| 41 | 41 | } elseif ($diff->m == 1) { |
| 42 | 42 | $text = '1 mes'; |
| 43 | 43 | } elseif ($diff->d > 7) { |
| 44 | - $text = ceil($diff->d / 7) . ' semanas'; |
|
| 44 | + $text = ceil($diff->d/7) . ' semanas'; |
|
| 45 | 45 | } elseif ($diff->d == 7) { |
| 46 | 46 | $text = '1 semana'; |
| 47 | 47 | } elseif ($diff->d > 1) { |
@@ -86,7 +86,7 @@ discard block |
||
| 86 | 86 | * @return string Hash, con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G |
| 87 | 87 | */ |
| 88 | 88 | final public static function hash(string $p) : string { |
| 89 | - return crypt($p, '$2a$10$' . substr(sha1(mt_rand()),0,22)); |
|
| 89 | + return crypt($p, '$2a$10$' . substr(sha1(mt_rand()), 0, 22)); |
|
| 90 | 90 | } |
| 91 | 91 | //------------------------------------------------ |
| 92 | 92 | /** |
@@ -99,9 +99,9 @@ discard block |
||
| 99 | 99 | * |
| 100 | 100 | */ |
| 101 | 101 | final public static function date_difference(string $ini, string $fin) : int { |
| 102 | - $ini_i = explode('-',str_replace('/','-',$ini)); |
|
| 103 | - $fin_i = explode('-',str_replace('/','-',$fin)); |
|
| 104 | - return (int) floor((mktime(0, 0, 0, $fin_i[1], $fin_i[0], $fin_i[2]) - mktime(0, 0, 0, $ini_i[1], $ini_i[0], $ini_i[2])) / 86400); |
|
| 102 | + $ini_i = explode('-', str_replace('/', '-', $ini)); |
|
| 103 | + $fin_i = explode('-', str_replace('/', '-', $fin)); |
|
| 104 | + return (int) floor((mktime(0, 0, 0, $fin_i[1], $fin_i[0], $fin_i[2]) - mktime(0, 0, 0, $ini_i[1], $ini_i[0], $ini_i[2]))/86400); |
|
| 105 | 105 | } |
| 106 | 106 | //------------------------------------------------ |
| 107 | 107 | /** |
@@ -113,7 +113,7 @@ discard block |
||
| 113 | 113 | * |
| 114 | 114 | */ |
| 115 | 115 | final public static function calculate_age(string $cumple) : int { |
| 116 | - $age = explode('.', (string) (self::date_difference($cumple,date('d-m-Y',time())) / 365)); |
|
| 116 | + $age = explode('.', (string) (self::date_difference($cumple, date('d-m-Y', time()))/365)); |
|
| 117 | 117 | return (int) $age[0]; |
| 118 | 118 | } |
| 119 | 119 | //------------------------------------------------ |
@@ -124,7 +124,7 @@ discard block |
||
| 124 | 124 | * |
| 125 | 125 | */ |
| 126 | 126 | final public static function days_of_month() : int { |
| 127 | - return cal_days_in_month(CAL_GREGORIAN, (int) date('m',time()), (int) date('Y',time())); |
|
| 127 | + return cal_days_in_month(CAL_GREGORIAN, (int) date('m', time()), (int) date('Y', time())); |
|
| 128 | 128 | } |
| 129 | 129 | //------------------------------------------------ |
| 130 | 130 | /** |
@@ -146,7 +146,7 @@ discard block |
||
| 146 | 146 | * @return string del texto sin espacios |
| 147 | 147 | */ |
| 148 | 148 | final public static function remove_spaces(string $s) : string { |
| 149 | - return trim(str_replace(' ','',$s)); |
|
| 149 | + return trim(str_replace(' ', '', $s)); |
|
| 150 | 150 | } |
| 151 | 151 | //------------------------------------------------ |
| 152 | 152 | /** |
@@ -191,9 +191,9 @@ discard block |
||
| 191 | 191 | */ |
| 192 | 192 | final public static function url_amigable(string $url) : string { |
| 193 | 193 | $url = strtolower($url); |
| 194 | - $url = str_replace (['á', 'é', 'í', 'ó', 'ú', 'ñ'],['a', 'e', 'i', 'o', 'u', 'n'], $url); |
|
| 195 | - $url = str_replace([' ', '&', '\r\n', '\n', '+', '%'],'-',$url); |
|
| 196 | - return preg_replace (['/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/'],['', '-', ''], $url); |
|
| 194 | + $url = str_replace(['á', 'é', 'í', 'ó', 'ú', 'ñ'], ['a', 'e', 'i', 'o', 'u', 'n'], $url); |
|
| 195 | + $url = str_replace([' ', '&', '\r\n', '\n', '+', '%'], '-', $url); |
|
| 196 | + return preg_replace(['/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/'], ['', '-', ''], $url); |
|
| 197 | 197 | } |
| 198 | 198 | //------------------------------------------------ |
| 199 | 199 | /** |
@@ -246,7 +246,7 @@ discard block |
||
| 246 | 246 | '<span style="font-size: $1px">$2</span>', |
| 247 | 247 | '<span style="font-family: $1">$2</span>' |
| 248 | 248 | ); |
| 249 | - return nl2br(preg_replace($BBcode,$HTML,$string)); |
|
| 249 | + return nl2br(preg_replace($BBcode, $HTML, $string)); |
|
| 250 | 250 | } |
| 251 | 251 | //------------------------------------------------ |
| 252 | 252 | /** |
@@ -294,7 +294,7 @@ discard block |
||
| 294 | 294 | * @return int Cantidad de palabras |
| 295 | 295 | */ |
| 296 | 296 | final public static function count_words(string $s) : int { |
| 297 | - return (int) str_word_count($s,0); |
|
| 297 | + return (int) str_word_count($s, 0); |
|
| 298 | 298 | } |
| 299 | 299 | //------------------------------------------------ |
| 300 | 300 | /** |
@@ -19,29 +19,29 @@ discard block |
||
| 19 | 19 | |
| 20 | 20 | final class Functions extends \Twig_Extension { |
| 21 | 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 | - */ |
|
| 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 | 31 | final private function check_str_to_time(int $index, array $detail, int $max) : bool { |
| 32 | 32 | return !array_key_exists($index,$detail) || !is_numeric($detail[$index]) || intval($detail[$index]) < $max; |
| 33 | 33 | } |
| 34 | 34 | |
| 35 | - //------------------------------------------------ |
|
| 35 | + //------------------------------------------------ |
|
| 36 | 36 | |
| 37 | - /** |
|
| 38 | - * Redirecciona a una URL |
|
| 39 | - * |
|
| 40 | - * @param string $url: Sitio a donde redireccionará, si no se pasa, por defecto |
|
| 41 | - * se redirecciona a la URL principal del sitio |
|
| 42 | - * |
|
| 43 | - * @return void |
|
| 44 | - */ |
|
| 37 | + /** |
|
| 38 | + * Redirecciona a una URL |
|
| 39 | + * |
|
| 40 | + * @param string $url: Sitio a donde redireccionará, si no se pasa, por defecto |
|
| 41 | + * se redirecciona a la URL principal del sitio |
|
| 42 | + * |
|
| 43 | + * @return void |
|
| 44 | + */ |
|
| 45 | 45 | final public function redir($url = null) { |
| 46 | 46 | global $config; |
| 47 | 47 | |
@@ -56,13 +56,13 @@ discard block |
||
| 56 | 56 | //------------------------------------------------ |
| 57 | 57 | |
| 58 | 58 | /** |
| 59 | - * Calcula el porcentaje de una cantidad |
|
| 60 | - * |
|
| 61 | - * @param float $por: El porcentaje a evaluar, por ejemplo 1, 20, 30 % sin el "%", sólamente el número |
|
| 62 | - * @param float $n: El número al cual se le quiere sacar el porcentaje |
|
| 63 | - * |
|
| 64 | - * @return float con el porcentaje correspondiente |
|
| 65 | - */ |
|
| 59 | + * Calcula el porcentaje de una cantidad |
|
| 60 | + * |
|
| 61 | + * @param float $por: El porcentaje a evaluar, por ejemplo 1, 20, 30 % sin el "%", sólamente el número |
|
| 62 | + * @param float $n: El número al cual se le quiere sacar el porcentaje |
|
| 63 | + * |
|
| 64 | + * @return float con el porcentaje correspondiente |
|
| 65 | + */ |
|
| 66 | 66 | final public function percent(float $por, float $n) : float { |
| 67 | 67 | return $n * ($por / 100); |
| 68 | 68 | } |
@@ -70,12 +70,12 @@ discard block |
||
| 70 | 70 | //------------------------------------------------ |
| 71 | 71 | |
| 72 | 72 | /** |
| 73 | - * Da unidades de peso a un integer según sea su tamaño asumida en bytes |
|
| 74 | - * |
|
| 75 | - * @param int $size: Un entero que representa el tamaño a convertir |
|
| 76 | - * |
|
| 77 | - * @return string del tamaño $size convertido a la unidad más adecuada |
|
| 78 | - */ |
|
| 73 | + * Da unidades de peso a un integer según sea su tamaño asumida en bytes |
|
| 74 | + * |
|
| 75 | + * @param int $size: Un entero que representa el tamaño a convertir |
|
| 76 | + * |
|
| 77 | + * @return string del tamaño $size convertido a la unidad más adecuada |
|
| 78 | + */ |
|
| 79 | 79 | final public function convert(int $size) : string { |
| 80 | 80 | $unit = array('bytes','kb','mb','gb','tb','pb'); |
| 81 | 81 | return round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; |
@@ -84,55 +84,55 @@ discard block |
||
| 84 | 84 | //------------------------------------------------ |
| 85 | 85 | |
| 86 | 86 | /** |
| 87 | - * Retorna la URL de un gravatar, según el email |
|
| 88 | - * |
|
| 89 | - * @param string $email: El email del usuario a extraer el gravatar |
|
| 90 | - * @param int $size: El tamaño del gravatar |
|
| 91 | - * @return string con la URl |
|
| 92 | - */ |
|
| 93 | - final public function get_gravatar(string $email, int $size = 32) : string { |
|
| 94 | - return 'http://www.gravatar.com/avatar/' . md5($email) . '?s=' . (int) abs($size); |
|
| 95 | - } |
|
| 96 | - |
|
| 97 | - //------------------------------------------------ |
|
| 98 | - |
|
| 99 | - /** |
|
| 87 | + * Retorna la URL de un gravatar, según el email |
|
| 88 | + * |
|
| 89 | + * @param string $email: El email del usuario a extraer el gravatar |
|
| 90 | + * @param int $size: El tamaño del gravatar |
|
| 91 | + * @return string con la URl |
|
| 92 | + */ |
|
| 93 | + final public function get_gravatar(string $email, int $size = 32) : string { |
|
| 94 | + return 'http://www.gravatar.com/avatar/' . md5($email) . '?s=' . (int) abs($size); |
|
| 95 | + } |
|
| 96 | + |
|
| 97 | + //------------------------------------------------ |
|
| 98 | + |
|
| 99 | + /** |
|
| 100 | 100 | * Alias de Empty, más completo |
| 101 | 101 | * |
| 102 | 102 | * @param mixed $var: Variable a analizar |
| 103 | 103 | * |
| 104 | 104 | * @return bool con true si está vacío, false si no, un espacio en blanco cuenta como vacío |
| 105 | - */ |
|
| 106 | - final public function emp($var) : bool { |
|
| 107 | - return (isset($var) && empty(trim(str_replace(' ','',$var)))); |
|
| 108 | - } |
|
| 105 | + */ |
|
| 106 | + final public function emp($var) : bool { |
|
| 107 | + return (isset($var) && empty(trim(str_replace(' ','',$var)))); |
|
| 108 | + } |
|
| 109 | 109 | |
| 110 | - //------------------------------------------------ |
|
| 110 | + //------------------------------------------------ |
|
| 111 | 111 | |
| 112 | - /** |
|
| 112 | + /** |
|
| 113 | 113 | * 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 |
| 114 | 114 | * pasando como parámetro $_POST |
| 115 | 115 | * |
| 116 | 116 | * @param array $array, arreglo a analizar |
| 117 | 117 | * |
| 118 | 118 | * @return bool con true si están todos llenos, false si al menos uno está vacío |
| 119 | - */ |
|
| 120 | - final public function all_full(array $array) : bool { |
|
| 121 | - foreach($array as $e) { |
|
| 122 | - if($this->emp($e) and $e != '0') { |
|
| 123 | - return false; |
|
| 124 | - } |
|
| 125 | - } |
|
| 126 | - return true; |
|
| 127 | - } |
|
| 128 | - |
|
| 129 | - //------------------------------------------------ |
|
| 130 | - |
|
| 131 | - /** |
|
| 119 | + */ |
|
| 120 | + final public function all_full(array $array) : bool { |
|
| 121 | + foreach($array as $e) { |
|
| 122 | + if($this->emp($e) and $e != '0') { |
|
| 123 | + return false; |
|
| 124 | + } |
|
| 125 | + } |
|
| 126 | + return true; |
|
| 127 | + } |
|
| 128 | + |
|
| 129 | + //------------------------------------------------ |
|
| 130 | + |
|
| 131 | + /** |
|
| 132 | 132 | * Alias de Empty() pero soporta más de un parámetro (infinitos) |
| 133 | 133 | * |
| 134 | 134 | * @return bool con true si al menos uno está vacío, false si todos están llenos |
| 135 | - */ |
|
| 135 | + */ |
|
| 136 | 136 | final public function e() : bool { |
| 137 | 137 | for ($i = 0, $nargs = func_num_args(); $i < $nargs; $i++) { |
| 138 | 138 | if(null === func_get_arg($i) || ($this->emp(func_get_arg($i)) && func_get_arg($i) != '0')) { |
@@ -145,58 +145,58 @@ discard block |
||
| 145 | 145 | //------------------------------------------------ |
| 146 | 146 | |
| 147 | 147 | /** |
| 148 | - * Alias de date() pero devuele días y meses en español |
|
| 149 | - * |
|
| 150 | - * @param string $format: Formato de salida (igual que en date()) |
|
| 151 | - * @param int $time: Tiempo, por defecto es time() (igual que en date()) |
|
| 152 | - * |
|
| 153 | - * @return string con la fecha en formato humano (y en español) |
|
| 154 | - */ |
|
| 148 | + * Alias de date() pero devuele días y meses en español |
|
| 149 | + * |
|
| 150 | + * @param string $format: Formato de salida (igual que en date()) |
|
| 151 | + * @param int $time: Tiempo, por defecto es time() (igual que en date()) |
|
| 152 | + * |
|
| 153 | + * @return string con la fecha en formato humano (y en español) |
|
| 154 | + */ |
|
| 155 | 155 | final public function fecha(string $format, int $time = 0) : string { |
| 156 | - $date = date($format,$time == 0 ? time() : $time); |
|
| 157 | - $cambios = array( |
|
| 158 | - 'Monday'=> 'Lunes', |
|
| 159 | - 'Tuesday'=> 'Martes', |
|
| 160 | - 'Wednesday'=> 'Miércoles', |
|
| 161 | - 'Thursday'=> 'Jueves', |
|
| 162 | - 'Friday'=> 'Viernes', |
|
| 163 | - 'Saturday'=> 'Sábado', |
|
| 164 | - 'Sunday'=> 'Domingo', |
|
| 165 | - 'January'=> 'Enero', |
|
| 166 | - 'February'=> 'Febrero', |
|
| 167 | - 'March'=> 'Marzo', |
|
| 168 | - 'April'=> 'Abril', |
|
| 169 | - 'May'=> 'Mayo', |
|
| 170 | - 'June'=> 'Junio', |
|
| 171 | - 'July'=> 'Julio', |
|
| 172 | - 'August'=> 'Agosto', |
|
| 173 | - 'September'=> 'Septiembre', |
|
| 174 | - 'October'=> 'Octubre', |
|
| 175 | - 'November'=> 'Noviembre', |
|
| 176 | - 'December'=> 'Diciembre', |
|
| 177 | - 'Mon'=> 'Lun', |
|
| 178 | - 'Tue'=> 'Mar', |
|
| 179 | - 'Wed'=> 'Mie', |
|
| 180 | - 'Thu'=> 'Jue', |
|
| 181 | - 'Fri'=> 'Vie', |
|
| 182 | - 'Sat'=> 'Sab', |
|
| 183 | - 'Sun'=> 'Dom', |
|
| 184 | - 'Jan'=> 'Ene', |
|
| 185 | - 'Aug'=> 'Ago', |
|
| 186 | - 'Apr'=> 'Abr', |
|
| 187 | - 'Dec'=> 'Dic' |
|
| 188 | - ); |
|
| 189 | - return str_replace(array_keys($cambios),array_values($cambios),$date); |
|
| 190 | - } |
|
| 191 | - |
|
| 192 | - //------------------------------------------------ |
|
| 156 | + $date = date($format,$time == 0 ? time() : $time); |
|
| 157 | + $cambios = array( |
|
| 158 | + 'Monday'=> 'Lunes', |
|
| 159 | + 'Tuesday'=> 'Martes', |
|
| 160 | + 'Wednesday'=> 'Miércoles', |
|
| 161 | + 'Thursday'=> 'Jueves', |
|
| 162 | + 'Friday'=> 'Viernes', |
|
| 163 | + 'Saturday'=> 'Sábado', |
|
| 164 | + 'Sunday'=> 'Domingo', |
|
| 165 | + 'January'=> 'Enero', |
|
| 166 | + 'February'=> 'Febrero', |
|
| 167 | + 'March'=> 'Marzo', |
|
| 168 | + 'April'=> 'Abril', |
|
| 169 | + 'May'=> 'Mayo', |
|
| 170 | + 'June'=> 'Junio', |
|
| 171 | + 'July'=> 'Julio', |
|
| 172 | + 'August'=> 'Agosto', |
|
| 173 | + 'September'=> 'Septiembre', |
|
| 174 | + 'October'=> 'Octubre', |
|
| 175 | + 'November'=> 'Noviembre', |
|
| 176 | + 'December'=> 'Diciembre', |
|
| 177 | + 'Mon'=> 'Lun', |
|
| 178 | + 'Tue'=> 'Mar', |
|
| 179 | + 'Wed'=> 'Mie', |
|
| 180 | + 'Thu'=> 'Jue', |
|
| 181 | + 'Fri'=> 'Vie', |
|
| 182 | + 'Sat'=> 'Sab', |
|
| 183 | + 'Sun'=> 'Dom', |
|
| 184 | + 'Jan'=> 'Ene', |
|
| 185 | + 'Aug'=> 'Ago', |
|
| 186 | + 'Apr'=> 'Abr', |
|
| 187 | + 'Dec'=> 'Dic' |
|
| 188 | + ); |
|
| 189 | + return str_replace(array_keys($cambios),array_values($cambios),$date); |
|
| 190 | + } |
|
| 191 | + |
|
| 192 | + //------------------------------------------------ |
|
| 193 | 193 | |
| 194 | 194 | /** |
| 195 | - * Devuelve la etiqueta <base> html adecuada para que los assets carguen desde allí. |
|
| 196 | - * Se adapta a la configuración del dominio en general. |
|
| 197 | - * |
|
| 198 | - * @return string <base href="ruta" /> |
|
| 199 | - */ |
|
| 195 | + * Devuelve la etiqueta <base> html adecuada para que los assets carguen desde allí. |
|
| 196 | + * Se adapta a la configuración del dominio en general. |
|
| 197 | + * |
|
| 198 | + * @return string <base href="ruta" /> |
|
| 199 | + */ |
|
| 200 | 200 | final public function base_assets() : string { |
| 201 | 201 | global $config, $http; |
| 202 | 202 | |
@@ -224,7 +224,7 @@ discard block |
||
| 224 | 224 | * @param int $anio: Año (1975 a 2xxx) |
| 225 | 225 | * |
| 226 | 226 | * @return string con el número del día |
| 227 | - */ |
|
| 227 | + */ |
|
| 228 | 228 | final public function last_day_month(int $mes, int $anio) : string { |
| 229 | 229 | return date('d', (mktime(0,0,0,$mes + 1, 1, $anio) - 1)); |
| 230 | 230 | } |
@@ -237,7 +237,7 @@ discard block |
||
| 237 | 237 | * @param int $num: cifra |
| 238 | 238 | * |
| 239 | 239 | * @return string cifra con cero a la izquirda |
| 240 | - */ |
|
| 240 | + */ |
|
| 241 | 241 | final public function cero_izq(int $num) : string { |
| 242 | 242 | if($num < 10) { |
| 243 | 243 | return '0' . $num; |
@@ -248,14 +248,14 @@ discard block |
||
| 248 | 248 | |
| 249 | 249 | //------------------------------------------------ |
| 250 | 250 | |
| 251 | - /** |
|
| 252 | - * Devuelve el timestamp de una fecha, y null si su formato es incorrecto. |
|
| 253 | - * |
|
| 254 | - * @param string|null $fecha: Fecha con formato dd/mm/yy |
|
| 255 | - * @param string $hora: Hora de inicio de la $fecha |
|
| 256 | - * |
|
| 257 | - * @return int|null con el timestamp |
|
| 258 | - */ |
|
| 251 | + /** |
|
| 252 | + * Devuelve el timestamp de una fecha, y null si su formato es incorrecto. |
|
| 253 | + * |
|
| 254 | + * @param string|null $fecha: Fecha con formato dd/mm/yy |
|
| 255 | + * @param string $hora: Hora de inicio de la $fecha |
|
| 256 | + * |
|
| 257 | + * @return int|null con el timestamp |
|
| 258 | + */ |
|
| 259 | 259 | final public function str_to_time($fecha, string $hora = '00:00:00') { |
| 260 | 260 | if(null == $fecha) { |
| 261 | 261 | return null; |
@@ -299,11 +299,11 @@ discard block |
||
| 299 | 299 | * @param int $desde: Desde donde |
| 300 | 300 | * |
| 301 | 301 | * @return mixed |
| 302 | - */ |
|
| 302 | + */ |
|
| 303 | 303 | final public function desde_date(int $desde) { |
| 304 | - # Obtener esta fecha |
|
| 305 | - $hoy = date('d/m/Y/D',time()); |
|
| 306 | - $hoy = explode('/',$hoy); |
|
| 304 | + # Obtener esta fecha |
|
| 305 | + $hoy = date('d/m/Y/D',time()); |
|
| 306 | + $hoy = explode('/',$hoy); |
|
| 307 | 307 | |
| 308 | 308 | |
| 309 | 309 | switch($desde) { |
@@ -365,7 +365,7 @@ discard block |
||
| 365 | 365 | |
| 366 | 366 | default: |
| 367 | 367 | throw new \RuntimeException('Problema con el valor $desde en desde_date()'); |
| 368 | - break; |
|
| 368 | + break; |
|
| 369 | 369 | } |
| 370 | 370 | } |
| 371 | 371 | |
@@ -375,44 +375,44 @@ discard block |
||
| 375 | 375 | * Obtiene el tiempo actual |
| 376 | 376 | * |
| 377 | 377 | * @return int devuelve time() |
| 378 | - */ |
|
| 378 | + */ |
|
| 379 | 379 | final public function timestamp() : int { |
| 380 | - return time(); |
|
| 380 | + return time(); |
|
| 381 | 381 | } |
| 382 | 382 | |
| 383 | 383 | //------------------------------------------------ |
| 384 | 384 | |
| 385 | 385 | /** |
| 386 | 386 | * Se obtiene de Twig_Extension y sirve para que cada función esté disponible como etiqueta en twig |
| 387 | - * |
|
| 387 | + * |
|
| 388 | 388 | * @return array con todas las funciones con sus respectivos nombres de acceso en plantillas twig |
| 389 | - */ |
|
| 389 | + */ |
|
| 390 | 390 | public function getFunctions() : array { |
| 391 | 391 | return array( |
| 392 | - new \Twig_Function('percent', array($this, 'percent')), |
|
| 393 | - new \Twig_Function('convert', array($this, 'convert')), |
|
| 394 | - new \Twig_Function('get_gravatar', array($this, 'get_gravatar')), |
|
| 395 | - new \Twig_Function('emp', array($this, 'emp')), |
|
| 396 | - new \Twig_Function('e_dynamic', array($this, 'e')), |
|
| 397 | - new \Twig_Function('all_full', array($this, 'all_full')), |
|
| 398 | - new \Twig_Function('fecha', array($this, 'fecha')), |
|
| 399 | - new \Twig_Function('base_assets',array($this, 'base_assets')), |
|
| 400 | - new \Twig_Function('timestamp',array($this, 'timestamp')), |
|
| 401 | - new \Twig_Function('desde_date',array($this, 'desde_date')), |
|
| 402 | - new \Twig_Function('cero_izq',array($this, 'cero_izq')), |
|
| 403 | - new \Twig_Function('last_day_month',array($this, 'last_day_month')), |
|
| 404 | - new \Twig_Function('str_to_time',array($this, 'str_to_time')), |
|
| 405 | - new \Twig_Function('desde_date',array($this, 'desde_date')) |
|
| 406 | - ); |
|
| 407 | - } |
|
| 408 | - |
|
| 409 | - //------------------------------------------------ |
|
| 392 | + new \Twig_Function('percent', array($this, 'percent')), |
|
| 393 | + new \Twig_Function('convert', array($this, 'convert')), |
|
| 394 | + new \Twig_Function('get_gravatar', array($this, 'get_gravatar')), |
|
| 395 | + new \Twig_Function('emp', array($this, 'emp')), |
|
| 396 | + new \Twig_Function('e_dynamic', array($this, 'e')), |
|
| 397 | + new \Twig_Function('all_full', array($this, 'all_full')), |
|
| 398 | + new \Twig_Function('fecha', array($this, 'fecha')), |
|
| 399 | + new \Twig_Function('base_assets',array($this, 'base_assets')), |
|
| 400 | + new \Twig_Function('timestamp',array($this, 'timestamp')), |
|
| 401 | + new \Twig_Function('desde_date',array($this, 'desde_date')), |
|
| 402 | + new \Twig_Function('cero_izq',array($this, 'cero_izq')), |
|
| 403 | + new \Twig_Function('last_day_month',array($this, 'last_day_month')), |
|
| 404 | + new \Twig_Function('str_to_time',array($this, 'str_to_time')), |
|
| 405 | + new \Twig_Function('desde_date',array($this, 'desde_date')) |
|
| 406 | + ); |
|
| 407 | + } |
|
| 408 | + |
|
| 409 | + //------------------------------------------------ |
|
| 410 | 410 | |
| 411 | 411 | /** |
| 412 | - * Identificador único para la extensión de twig |
|
| 413 | - * |
|
| 414 | - * @return string con el nombre de la extensión |
|
| 415 | - */ |
|
| 412 | + * Identificador único para la extensión de twig |
|
| 413 | + * |
|
| 414 | + * @return string con el nombre de la extensión |
|
| 415 | + */ |
|
| 416 | 416 | public function getName() : string { |
| 417 | 417 | return 'ocrend_framework_func_class'; |
| 418 | 418 | } |
@@ -29,7 +29,7 @@ discard block |
||
| 29 | 29 | * @return bool con el resultado de la comparación |
| 30 | 30 | */ |
| 31 | 31 | final private 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; |
|
| 32 | + return !array_key_exists($index, $detail) || !is_numeric($detail[$index]) || intval($detail[$index]) < $max; |
|
| 33 | 33 | } |
| 34 | 34 | |
| 35 | 35 | //------------------------------------------------ |
@@ -45,7 +45,7 @@ discard block |
||
| 45 | 45 | final public function redir($url = null) { |
| 46 | 46 | global $config; |
| 47 | 47 | |
| 48 | - if(null == $url) { |
|
| 48 | + if (null == $url) { |
|
| 49 | 49 | $url = $config['site']['url']; |
| 50 | 50 | } |
| 51 | 51 | |
@@ -64,7 +64,7 @@ discard block |
||
| 64 | 64 | * @return float con el porcentaje correspondiente |
| 65 | 65 | */ |
| 66 | 66 | final public function percent(float $por, float $n) : float { |
| 67 | - return $n * ($por / 100); |
|
| 67 | + return $n*($por/100); |
|
| 68 | 68 | } |
| 69 | 69 | |
| 70 | 70 | //------------------------------------------------ |
@@ -77,8 +77,8 @@ discard block |
||
| 77 | 77 | * @return string del tamaño $size convertido a la unidad más adecuada |
| 78 | 78 | */ |
| 79 | 79 | final public function convert(int $size) : string { |
| 80 | - $unit = array('bytes','kb','mb','gb','tb','pb'); |
|
| 81 | - return round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i]; |
|
| 80 | + $unit = array('bytes', 'kb', 'mb', 'gb', 'tb', 'pb'); |
|
| 81 | + return round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i]; |
|
| 82 | 82 | } |
| 83 | 83 | |
| 84 | 84 | //------------------------------------------------ |
@@ -104,7 +104,7 @@ discard block |
||
| 104 | 104 | * @return bool con true si está vacío, false si no, un espacio en blanco cuenta como vacío |
| 105 | 105 | */ |
| 106 | 106 | final public function emp($var) : bool { |
| 107 | - return (isset($var) && empty(trim(str_replace(' ','',$var)))); |
|
| 107 | + return (isset($var) && empty(trim(str_replace(' ', '', $var)))); |
|
| 108 | 108 | } |
| 109 | 109 | |
| 110 | 110 | //------------------------------------------------ |
@@ -118,8 +118,8 @@ discard block |
||
| 118 | 118 | * @return bool con true si están todos llenos, false si al menos uno está vacío |
| 119 | 119 | */ |
| 120 | 120 | final public function all_full(array $array) : bool { |
| 121 | - foreach($array as $e) { |
|
| 122 | - if($this->emp($e) and $e != '0') { |
|
| 121 | + foreach ($array as $e) { |
|
| 122 | + if ($this->emp($e) and $e != '0') { |
|
| 123 | 123 | return false; |
| 124 | 124 | } |
| 125 | 125 | } |
@@ -135,7 +135,7 @@ discard block |
||
| 135 | 135 | */ |
| 136 | 136 | final public function e() : bool { |
| 137 | 137 | for ($i = 0, $nargs = func_num_args(); $i < $nargs; $i++) { |
| 138 | - if(null === func_get_arg($i) || ($this->emp(func_get_arg($i)) && func_get_arg($i) != '0')) { |
|
| 138 | + if (null === func_get_arg($i) || ($this->emp(func_get_arg($i)) && func_get_arg($i) != '0')) { |
|
| 139 | 139 | return true; |
| 140 | 140 | } |
| 141 | 141 | } |
@@ -153,7 +153,7 @@ discard block |
||
| 153 | 153 | * @return string con la fecha en formato humano (y en español) |
| 154 | 154 | */ |
| 155 | 155 | final public function fecha(string $format, int $time = 0) : string { |
| 156 | - $date = date($format,$time == 0 ? time() : $time); |
|
| 156 | + $date = date($format, $time == 0 ? time() : $time); |
|
| 157 | 157 | $cambios = array( |
| 158 | 158 | 'Monday'=> 'Lunes', |
| 159 | 159 | 'Tuesday'=> 'Martes', |
@@ -186,7 +186,7 @@ discard block |
||
| 186 | 186 | 'Apr'=> 'Abr', |
| 187 | 187 | 'Dec'=> 'Dic' |
| 188 | 188 | ); |
| 189 | - return str_replace(array_keys($cambios),array_values($cambios),$date); |
|
| 189 | + return str_replace(array_keys($cambios), array_values($cambios), $date); |
|
| 190 | 190 | } |
| 191 | 191 | |
| 192 | 192 | //------------------------------------------------ |
@@ -206,13 +206,13 @@ discard block |
||
| 206 | 206 | # Revisar protocolo |
| 207 | 207 | $base = $config['site']['router']['protocol'] . '://'; |
| 208 | 208 | |
| 209 | - if(strtolower($www) == 'www') { |
|
| 209 | + if (strtolower($www) == 'www') { |
|
| 210 | 210 | $base .= 'www.' . $config['site']['router']['path']; |
| 211 | 211 | } else { |
| 212 | 212 | $base .= $config['site']['router']['path']; |
| 213 | 213 | } |
| 214 | 214 | |
| 215 | - return '<base href="'.$base.'" />'; |
|
| 215 | + return '<base href="' . $base . '" />'; |
|
| 216 | 216 | } |
| 217 | 217 | |
| 218 | 218 | //------------------------------------------------ |
@@ -226,7 +226,7 @@ discard block |
||
| 226 | 226 | * @return string con el número del día |
| 227 | 227 | */ |
| 228 | 228 | final public function last_day_month(int $mes, int $anio) : string { |
| 229 | - return date('d', (mktime(0,0,0,$mes + 1, 1, $anio) - 1)); |
|
| 229 | + return date('d', (mktime(0, 0, 0, $mes + 1, 1, $anio) - 1)); |
|
| 230 | 230 | } |
| 231 | 231 | |
| 232 | 232 | //------------------------------------------------ |
@@ -239,7 +239,7 @@ discard block |
||
| 239 | 239 | * @return string cifra con cero a la izquirda |
| 240 | 240 | */ |
| 241 | 241 | final public function cero_izq(int $num) : string { |
| 242 | - if($num < 10) { |
|
| 242 | + if ($num < 10) { |
|
| 243 | 243 | return '0' . $num; |
| 244 | 244 | } |
| 245 | 245 | |
@@ -257,24 +257,24 @@ discard block |
||
| 257 | 257 | * @return int|null con el timestamp |
| 258 | 258 | */ |
| 259 | 259 | final public function str_to_time($fecha, string $hora = '00:00:00') { |
| 260 | - if(null == $fecha) { |
|
| 260 | + if (null == $fecha) { |
|
| 261 | 261 | return null; |
| 262 | 262 | } |
| 263 | 263 | |
| 264 | - $detail = explode('/',$fecha); |
|
| 264 | + $detail = explode('/', $fecha); |
|
| 265 | 265 | |
| 266 | 266 | // Formato de día incorrecto |
| 267 | - if($this->check_str_to_time(0,$detail,1)) { |
|
| 267 | + if ($this->check_str_to_time(0, $detail, 1)) { |
|
| 268 | 268 | return null; |
| 269 | 269 | } |
| 270 | 270 | |
| 271 | 271 | // Formato de mes incorrecto |
| 272 | - if($this->check_str_to_time(1,$detail,1) || intval($detail[1]) > 12) { |
|
| 272 | + if ($this->check_str_to_time(1, $detail, 1) || intval($detail[1]) > 12) { |
|
| 273 | 273 | return null; |
| 274 | 274 | } |
| 275 | 275 | |
| 276 | 276 | // Formato del año |
| 277 | - if($this->check_str_to_time(2,$detail,1970)) { |
|
| 277 | + if ($this->check_str_to_time(2, $detail, 1970)) { |
|
| 278 | 278 | return null; |
| 279 | 279 | } |
| 280 | 280 | |
@@ -284,7 +284,7 @@ discard block |
||
| 284 | 284 | $year = intval($detail[2]); |
| 285 | 285 | |
| 286 | 286 | // Veriricar dia según mes |
| 287 | - if($day > $this->last_day_month($month,$year)) { |
|
| 287 | + if ($day > $this->last_day_month($month, $year)) { |
|
| 288 | 288 | return null; |
| 289 | 289 | } |
| 290 | 290 | |
@@ -302,11 +302,11 @@ discard block |
||
| 302 | 302 | */ |
| 303 | 303 | final public function desde_date(int $desde) { |
| 304 | 304 | # Obtener esta fecha |
| 305 | - $hoy = date('d/m/Y/D',time()); |
|
| 306 | - $hoy = explode('/',$hoy); |
|
| 305 | + $hoy = date('d/m/Y/D', time()); |
|
| 306 | + $hoy = explode('/', $hoy); |
|
| 307 | 307 | |
| 308 | 308 | |
| 309 | - switch($desde) { |
|
| 309 | + switch ($desde) { |
|
| 310 | 310 | # Hoy |
| 311 | 311 | case 1: |
| 312 | 312 | return date('d/m/Y', time()); |
@@ -318,7 +318,7 @@ discard block |
||
| 318 | 318 | # Semana |
| 319 | 319 | case 3: |
| 320 | 320 | # Día de la semana actual |
| 321 | - switch($hoy[3]) { |
|
| 321 | + switch ($hoy[3]) { |
|
| 322 | 322 | case 'Mon': |
| 323 | 323 | $dia = $hoy[0]; |
| 324 | 324 | break; |
@@ -343,21 +343,21 @@ discard block |
||
| 343 | 343 | } |
| 344 | 344 | |
| 345 | 345 | # Mes anterior y posiblemente, año también. |
| 346 | - if($dia == 0) { |
|
| 346 | + if ($dia == 0) { |
|
| 347 | 347 | # Verificamos si estamos en enero |
| 348 | - if($hoy[1] == 1) { |
|
| 349 | - return $this->last_day_month($hoy[1],$hoy[2]) .'/'. $this->cero_izq($hoy[1] - 1) .'/' . ($hoy[2] - 1); |
|
| 348 | + if ($hoy[1] == 1) { |
|
| 349 | + return $this->last_day_month($hoy[1], $hoy[2]) . '/' . $this->cero_izq($hoy[1] - 1) . '/' . ($hoy[2] - 1); |
|
| 350 | 350 | } |
| 351 | 351 | |
| 352 | 352 | # Si no es enero, es el año actual |
| 353 | - return $this->last_day_month($hoy[1],$hoy[2]) .'/'. $this->cero_izq($hoy[1] - 1) .'/' . $hoy[2]; |
|
| 353 | + return $this->last_day_month($hoy[1], $hoy[2]) . '/' . $this->cero_izq($hoy[1] - 1) . '/' . $hoy[2]; |
|
| 354 | 354 | } |
| 355 | 355 | |
| 356 | - return $this->cero_izq($dia) .'/'. $this->cero_izq($hoy[1]) .'/' . $hoy[2]; |
|
| 356 | + return $this->cero_izq($dia) . '/' . $this->cero_izq($hoy[1]) . '/' . $hoy[2]; |
|
| 357 | 357 | |
| 358 | 358 | # Mes |
| 359 | 359 | case 4: |
| 360 | - return '01/'. $this->cero_izq($hoy[1]) .'/' . $hoy[2]; |
|
| 360 | + return '01/' . $this->cero_izq($hoy[1]) . '/' . $hoy[2]; |
|
| 361 | 361 | |
| 362 | 362 | # Año |
| 363 | 363 | case 5: |
@@ -396,13 +396,13 @@ discard block |
||
| 396 | 396 | new \Twig_Function('e_dynamic', array($this, 'e')), |
| 397 | 397 | new \Twig_Function('all_full', array($this, 'all_full')), |
| 398 | 398 | new \Twig_Function('fecha', array($this, 'fecha')), |
| 399 | - new \Twig_Function('base_assets',array($this, 'base_assets')), |
|
| 400 | - new \Twig_Function('timestamp',array($this, 'timestamp')), |
|
| 401 | - new \Twig_Function('desde_date',array($this, 'desde_date')), |
|
| 402 | - new \Twig_Function('cero_izq',array($this, 'cero_izq')), |
|
| 403 | - new \Twig_Function('last_day_month',array($this, 'last_day_month')), |
|
| 404 | - new \Twig_Function('str_to_time',array($this, 'str_to_time')), |
|
| 405 | - new \Twig_Function('desde_date',array($this, 'desde_date')) |
|
| 399 | + new \Twig_Function('base_assets', array($this, 'base_assets')), |
|
| 400 | + new \Twig_Function('timestamp', array($this, 'timestamp')), |
|
| 401 | + new \Twig_Function('desde_date', array($this, 'desde_date')), |
|
| 402 | + new \Twig_Function('cero_izq', array($this, 'cero_izq')), |
|
| 403 | + new \Twig_Function('last_day_month', array($this, 'last_day_month')), |
|
| 404 | + new \Twig_Function('str_to_time', array($this, 'str_to_time')), |
|
| 405 | + new \Twig_Function('desde_date', array($this, 'desde_date')) |
|
| 406 | 406 | ); |
| 407 | 407 | } |
| 408 | 408 | |