@@ -20,89 +20,89 @@ |
||
20 | 20 | final class Rules { |
21 | 21 | |
22 | 22 | /** |
23 | - * Sin ninguna regla |
|
24 | - * |
|
25 | - * @param mixed $ruta : Ruta a aplicar la regla |
|
26 | - * |
|
27 | - * @return mixed |
|
28 | - */ |
|
23 | + * Sin ninguna regla |
|
24 | + * |
|
25 | + * @param mixed $ruta : Ruta a aplicar la regla |
|
26 | + * |
|
27 | + * @return mixed |
|
28 | + */ |
|
29 | 29 | final public function none($ruta) { |
30 | 30 | return $ruta; |
31 | 31 | } |
32 | 32 | |
33 | 33 | /** |
34 | - * Sólamente letras |
|
35 | - * |
|
36 | - * @param mixed $ruta : Ruta a aplicar la regla |
|
37 | - * |
|
38 | - * @return mixed |
|
39 | - */ |
|
34 | + * Sólamente letras |
|
35 | + * |
|
36 | + * @param mixed $ruta : Ruta a aplicar la regla |
|
37 | + * |
|
38 | + * @return mixed |
|
39 | + */ |
|
40 | 40 | final public function letters($ruta) { |
41 | 41 | return preg_match("/^[a-zA-Z ]*$/", $ruta) ? $ruta : null; |
42 | 42 | } |
43 | 43 | |
44 | 44 | /** |
45 | - * Letras y números |
|
46 | - * |
|
47 | - * @param mixed $ruta : Ruta a aplicar la regla |
|
48 | - * |
|
49 | - * @return mixed |
|
50 | - */ |
|
45 | + * Letras y números |
|
46 | + * |
|
47 | + * @param mixed $ruta : Ruta a aplicar la regla |
|
48 | + * |
|
49 | + * @return mixed |
|
50 | + */ |
|
51 | 51 | final public function alphanumeric($ruta) { |
52 | 52 | return preg_match('/^[a-zA-Z0-9 ]*$/', $ruta) ? $ruta : null; |
53 | 53 | } |
54 | 54 | |
55 | 55 | /** |
56 | - * Con forma para URL (letras,números y el caracter -) |
|
57 | - * |
|
58 | - * @param mixed $ruta : Ruta a aplicar la regla |
|
59 | - * |
|
60 | - * @return mixed |
|
61 | - */ |
|
56 | + * Con forma para URL (letras,números y el caracter -) |
|
57 | + * |
|
58 | + * @param mixed $ruta : Ruta a aplicar la regla |
|
59 | + * |
|
60 | + * @return mixed |
|
61 | + */ |
|
62 | 62 | final public function url($ruta) { |
63 | 63 | return preg_match('/^[a-zA-Z0-9- ]*$/', $ruta) ? $ruta : null; |
64 | 64 | } |
65 | 65 | |
66 | 66 | /** |
67 | - * Sólamente números enteros |
|
68 | - * |
|
69 | - * @param mixed $ruta : Ruta a aplicar la regla |
|
70 | - * |
|
71 | - * @return int|null |
|
72 | - */ |
|
67 | + * Sólamente números enteros |
|
68 | + * |
|
69 | + * @param mixed $ruta : Ruta a aplicar la regla |
|
70 | + * |
|
71 | + * @return int|null |
|
72 | + */ |
|
73 | 73 | final public function integer($ruta) { |
74 | 74 | return is_numeric($ruta) ? (int) $ruta : null; |
75 | 75 | } |
76 | 76 | |
77 | 77 | /** |
78 | - * Solamente números enteros positivos |
|
79 | - * |
|
80 | - * @param mixed $ruta : Ruta a aplicar la regla |
|
81 | - * |
|
82 | - * @return int|null |
|
83 | - */ |
|
78 | + * Solamente números enteros positivos |
|
79 | + * |
|
80 | + * @param mixed $ruta : Ruta a aplicar la regla |
|
81 | + * |
|
82 | + * @return int|null |
|
83 | + */ |
|
84 | 84 | final public function integer_positive($ruta) { |
85 | 85 | return (is_numeric($ruta) && $ruta >= 0) ? (int) $ruta : null; |
86 | 86 | } |
87 | 87 | |
88 | 88 | /** |
89 | - * Solamente números con decimal |
|
90 | - * |
|
91 | - * @param mixed $ruta : Ruta a aplicar la regla |
|
92 | - * |
|
93 | - * @return float|null |
|
94 | - */ |
|
89 | + * Solamente números con decimal |
|
90 | + * |
|
91 | + * @param mixed $ruta : Ruta a aplicar la regla |
|
92 | + * |
|
93 | + * @return float|null |
|
94 | + */ |
|
95 | 95 | final public function float($ruta) { |
96 | 96 | return is_numeric($ruta) ? (float) $ruta : null; |
97 | 97 | } |
98 | 98 | |
99 | 99 | /** |
100 | - * Solamente números con decimal y positivos |
|
101 | - * |
|
102 | - * @param mixed $ruta : Ruta a aplicar la regla |
|
103 | - * |
|
104 | - * @return float|null |
|
105 | - */ |
|
100 | + * Solamente números con decimal y positivos |
|
101 | + * |
|
102 | + * @param mixed $ruta : Ruta a aplicar la regla |
|
103 | + * |
|
104 | + * @return float|null |
|
105 | + */ |
|
106 | 106 | final public function float_positive($ruta) { |
107 | 107 | return (is_numeric($ruta) && $ruta >= 0) ? (float) $ruta : null; |
108 | 108 | } |
@@ -24,8 +24,8 @@ discard block |
||
24 | 24 | final class Router implements IRouter { |
25 | 25 | |
26 | 26 | /** |
27 | - * @var array CONSTANTE con las reglas permitidas |
|
28 | - */ |
|
27 | + * @var array CONSTANTE con las reglas permitidas |
|
28 | + */ |
|
29 | 29 | const RULES = [ |
30 | 30 | 'none', # Sin ninguna regla |
31 | 31 | 'letters', # Sólamente letras |
@@ -38,10 +38,10 @@ discard block |
||
38 | 38 | ]; |
39 | 39 | |
40 | 40 | /** |
41 | - * Colección de rutas existentes |
|
42 | - * |
|
43 | - * @var array |
|
44 | - */ |
|
41 | + * Colección de rutas existentes |
|
42 | + * |
|
43 | + * @var array |
|
44 | + */ |
|
45 | 45 | private $routerCollection = array( |
46 | 46 | '/controller' => 'home', # controlador por defecto |
47 | 47 | '/method' => null, # método por defecto |
@@ -49,10 +49,10 @@ discard block |
||
49 | 49 | ); |
50 | 50 | |
51 | 51 | /** |
52 | - * Colección de reglas para cada ruta existente |
|
53 | - * |
|
54 | - * @var array |
|
55 | - */ |
|
52 | + * Colección de reglas para cada ruta existente |
|
53 | + * |
|
54 | + * @var array |
|
55 | + */ |
|
56 | 56 | private $routerCollectionRules = array( |
57 | 57 | '/controller' => 'letters', |
58 | 58 | '/method' => 'none', |
@@ -60,18 +60,18 @@ discard block |
||
60 | 60 | ); |
61 | 61 | |
62 | 62 | /** |
63 | - * @var array |
|
64 | - */ |
|
63 | + * @var array |
|
64 | + */ |
|
65 | 65 | private $real_request = array(); |
66 | 66 | |
67 | 67 | /** |
68 | - * @var string |
|
69 | - */ |
|
68 | + * @var string |
|
69 | + */ |
|
70 | 70 | private $requestUri; |
71 | 71 | |
72 | 72 | /** |
73 | - * __construct() |
|
74 | - */ |
|
73 | + * __construct() |
|
74 | + */ |
|
75 | 75 | public function __construct() { |
76 | 76 | global $http; |
77 | 77 | |
@@ -83,13 +83,13 @@ discard block |
||
83 | 83 | } |
84 | 84 | |
85 | 85 | /** |
86 | - * Coloca una regla destinada a una ruta, siempre y cuando esta regla exista. |
|
87 | - * |
|
88 | - * @param string $index : Índice de la ruta |
|
89 | - * @param string $rule : Nombre de la regla |
|
90 | - * |
|
91 | - * @throws \RuntimeException si la regla no existe |
|
92 | - */ |
|
86 | + * Coloca una regla destinada a una ruta, siempre y cuando esta regla exista. |
|
87 | + * |
|
88 | + * @param string $index : Índice de la ruta |
|
89 | + * @param string $rule : Nombre de la regla |
|
90 | + * |
|
91 | + * @throws \RuntimeException si la regla no existe |
|
92 | + */ |
|
93 | 93 | final private function setCollectionRule(string $index, string $rule) { |
94 | 94 | # Verificar si la regla existe |
95 | 95 | if(!in_array($rule,self::RULES)) { |
@@ -100,8 +100,8 @@ discard block |
||
100 | 100 | } |
101 | 101 | |
102 | 102 | /** |
103 | - * Verifica las peticiones por defecto |
|
104 | - */ |
|
103 | + * Verifica las peticiones por defecto |
|
104 | + */ |
|
105 | 105 | final private function checkRequests() { |
106 | 106 | # Verificar si existe peticiones |
107 | 107 | if(null !== $this->requestUri) { |
@@ -115,13 +115,13 @@ discard block |
||
115 | 115 | } |
116 | 116 | |
117 | 117 | /** |
118 | - * Crea una nueva ruta. |
|
119 | - * |
|
120 | - * @param string $index : Índice de la ruta |
|
121 | - * @param string $rule : Nombre de la regla, por defecto es ninguna "none" |
|
122 | - * |
|
123 | - * @throws \RuntimeException si no puede definirse la ruta |
|
124 | - */ |
|
118 | + * Crea una nueva ruta. |
|
119 | + * |
|
120 | + * @param string $index : Índice de la ruta |
|
121 | + * @param string $rule : Nombre de la regla, por defecto es ninguna "none" |
|
122 | + * |
|
123 | + * @throws \RuntimeException si no puede definirse la ruta |
|
124 | + */ |
|
125 | 125 | final public function setRoute(string $index, string $rule = 'none') { |
126 | 126 | # Nombres de rutas no permitidos |
127 | 127 | if(in_array($index,['/controller','/method','/id'])) { |
@@ -141,13 +141,13 @@ discard block |
||
141 | 141 | } |
142 | 142 | |
143 | 143 | /** |
144 | - * Obtiene el valor de una ruta según la regla que ha sido definida y si ésta existe. |
|
145 | - * |
|
146 | - * @param string $index : Índice de la ruta |
|
147 | - * |
|
148 | - * @throws \RuntimeException si la ruta no existe o si no está implementada la regla |
|
149 | - * @return mixed : Valor de la ruta solicitada |
|
150 | - */ |
|
144 | + * Obtiene el valor de una ruta según la regla que ha sido definida y si ésta existe. |
|
145 | + * |
|
146 | + * @param string $index : Índice de la ruta |
|
147 | + * |
|
148 | + * @throws \RuntimeException si la ruta no existe o si no está implementada la regla |
|
149 | + * @return mixed : Valor de la ruta solicitada |
|
150 | + */ |
|
151 | 151 | final public function getRoute(string $index) { |
152 | 152 | # Verificar existencia de ruta |
153 | 153 | if(!array_key_exists($index,$this->routerCollection)) { |
@@ -168,34 +168,34 @@ discard block |
||
168 | 168 | } |
169 | 169 | |
170 | 170 | /** |
171 | - * Obtiene el nombre del controlador. |
|
172 | - * |
|
173 | - * @return string controlador. |
|
174 | - */ |
|
171 | + * Obtiene el nombre del controlador. |
|
172 | + * |
|
173 | + * @return string controlador. |
|
174 | + */ |
|
175 | 175 | final public function getController() { |
176 | 176 | return $this->routerCollection['/controller']; |
177 | 177 | } |
178 | 178 | |
179 | 179 | /** |
180 | - * Obtiene el método |
|
181 | - * |
|
182 | - * @return string con el método. |
|
183 | - * null si no está definido. |
|
184 | - */ |
|
180 | + * Obtiene el método |
|
181 | + * |
|
182 | + * @return string con el método. |
|
183 | + * null si no está definido. |
|
184 | + */ |
|
185 | 185 | final public function getMethod() { |
186 | 186 | return $this->routerCollection['/method']; |
187 | 187 | } |
188 | 188 | |
189 | 189 | /** |
190 | - * Obtiene el id |
|
191 | - * |
|
192 | - * @param bool $with_rules : true para obtener el id con reglas definidas para números mayores a 0 |
|
193 | - * false para obtener el id sin reglas definidas |
|
194 | - * |
|
195 | - * @return int|null con el id |
|
196 | - * int con el id si usa reglas. |
|
197 | - * null si no está definido. |
|
198 | - */ |
|
190 | + * Obtiene el id |
|
191 | + * |
|
192 | + * @param bool $with_rules : true para obtener el id con reglas definidas para números mayores a 0 |
|
193 | + * false para obtener el id sin reglas definidas |
|
194 | + * |
|
195 | + * @return int|null con el id |
|
196 | + * int con el id si usa reglas. |
|
197 | + * null si no está definido. |
|
198 | + */ |
|
199 | 199 | final public function getId(bool $with_rules = false) { |
200 | 200 | $id = $this->routerCollection['/id']; |
201 | 201 | if($with_rules && (!is_numeric($id) || $id <= 0)) { |
@@ -205,11 +205,11 @@ discard block |
||
205 | 205 | return $id; |
206 | 206 | } |
207 | 207 | |
208 | - /** |
|
209 | - * Ejecuta el controlador solicitado por la URL. |
|
210 | - * Si este no existe, ejecutará errorController. |
|
211 | - * Si no se solicita ningún controlador, ejecutará homeController. |
|
212 | - */ |
|
208 | + /** |
|
209 | + * Ejecuta el controlador solicitado por la URL. |
|
210 | + * Si este no existe, ejecutará errorController. |
|
211 | + * Si no se solicita ningún controlador, ejecutará homeController. |
|
212 | + */ |
|
213 | 213 | final public function executeController() { |
214 | 214 | # Definir controlador |
215 | 215 | if(null != ($controller = $this->getController())) { |
@@ -92,7 +92,7 @@ discard block |
||
92 | 92 | */ |
93 | 93 | final private function setCollectionRule(string $index, string $rule) { |
94 | 94 | # Verificar si la regla existe |
95 | - if(!in_array($rule,self::RULES)) { |
|
95 | + if (!in_array($rule, self::RULES)) { |
|
96 | 96 | throw new \RuntimeException('La regla ' . $rule . ' no existe.'); |
97 | 97 | } |
98 | 98 | # Definir la regla para la ruta |
@@ -104,14 +104,14 @@ discard block |
||
104 | 104 | */ |
105 | 105 | final private function checkRequests() { |
106 | 106 | # Verificar si existe peticiones |
107 | - if(null !== $this->requestUri) { |
|
108 | - $this->real_request = explode('/',$this->requestUri); |
|
107 | + if (null !== $this->requestUri) { |
|
108 | + $this->real_request = explode('/', $this->requestUri); |
|
109 | 109 | $this->routerCollection['/controller'] = $this->real_request[0]; |
110 | 110 | } |
111 | 111 | |
112 | 112 | # Setear las siguientes rutas |
113 | - $this->routerCollection['/method'] = array_key_exists(1,$this->real_request) ? $this->real_request[1] : null; |
|
114 | - $this->routerCollection['/id'] = array_key_exists(2,$this->real_request) ? $this->real_request[2] : null; |
|
113 | + $this->routerCollection['/method'] = array_key_exists(1, $this->real_request) ? $this->real_request[1] : null; |
|
114 | + $this->routerCollection['/id'] = array_key_exists(2, $this->real_request) ? $this->real_request[2] : null; |
|
115 | 115 | } |
116 | 116 | |
117 | 117 | /** |
@@ -124,7 +124,7 @@ discard block |
||
124 | 124 | */ |
125 | 125 | final public function setRoute(string $index, string $rule = 'none') { |
126 | 126 | # Nombres de rutas no permitidos |
127 | - if(in_array($index,['/controller','/method','/id'])) { |
|
127 | + if (in_array($index, ['/controller', '/method', '/id'])) { |
|
128 | 128 | throw new \RuntimeException('No puede definirse ' . $index . ' como índice en la ruta.'); |
129 | 129 | } |
130 | 130 | |
@@ -136,8 +136,8 @@ discard block |
||
136 | 136 | |
137 | 137 | # Definir la ruta y regla |
138 | 138 | $lastRoute = sizeof($this->routerCollection); |
139 | - $this->routerCollection[$index] = array_key_exists($lastRoute,$this->real_request) ? $this->real_request[$lastRoute] : null; |
|
140 | - $this->setCollectionRule($index,$rule); |
|
139 | + $this->routerCollection[$index] = array_key_exists($lastRoute, $this->real_request) ? $this->real_request[$lastRoute] : null; |
|
140 | + $this->setCollectionRule($index, $rule); |
|
141 | 141 | } |
142 | 142 | |
143 | 143 | /** |
@@ -150,7 +150,7 @@ discard block |
||
150 | 150 | */ |
151 | 151 | final public function getRoute(string $index) { |
152 | 152 | # Verificar existencia de ruta |
153 | - if(!array_key_exists($index,$this->routerCollection)) { |
|
153 | + if (!array_key_exists($index, $this->routerCollection)) { |
|
154 | 154 | throw new \RuntimeException('La ruta ' . $index . ' no está definida en el controlador.'); |
155 | 155 | } |
156 | 156 | |
@@ -159,7 +159,7 @@ discard block |
||
159 | 159 | $rules = new Rules; |
160 | 160 | |
161 | 161 | # Retornar ruta con la regla definida aplicada |
162 | - if(method_exists($rules, $this->routerCollectionRules[$index])) { |
|
162 | + if (method_exists($rules, $this->routerCollectionRules[$index])) { |
|
163 | 163 | return $rules->{$this->routerCollectionRules[$index]}($ruta); |
164 | 164 | } |
165 | 165 | |
@@ -198,7 +198,7 @@ discard block |
||
198 | 198 | */ |
199 | 199 | final public function getId(bool $with_rules = false) { |
200 | 200 | $id = $this->routerCollection['/id']; |
201 | - if($with_rules && (!is_numeric($id) || $id <= 0)) { |
|
201 | + if ($with_rules && (!is_numeric($id) || $id <= 0)) { |
|
202 | 202 | return null; |
203 | 203 | } |
204 | 204 | |
@@ -212,10 +212,10 @@ discard block |
||
212 | 212 | */ |
213 | 213 | final public function executeController() { |
214 | 214 | # Definir controlador |
215 | - if(null != ($controller = $this->getController())) { |
|
215 | + if (null != ($controller = $this->getController())) { |
|
216 | 216 | $controller = $controller . 'Controller'; |
217 | 217 | |
218 | - if(!is_readable('app/controllers/' . $controller . '.php')) { |
|
218 | + if (!is_readable('app/controllers/' . $controller . '.php')) { |
|
219 | 219 | $controller = 'errorController'; |
220 | 220 | } |
221 | 221 |
@@ -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,10 +50,10 @@ discard block |
||
50 | 50 | } |
51 | 51 | |
52 | 52 | /** |
53 | - * Motor de base de datos MySQL |
|
54 | - * |
|
55 | - * @param array $params: Lista de parámetros de configuración |
|
56 | - */ |
|
53 | + * Motor de base de datos MySQL |
|
54 | + * |
|
55 | + * @param array $params: Lista de parámetros de configuración |
|
56 | + */ |
|
57 | 57 | final private function motor_mysql(array $params) { |
58 | 58 | parent::__construct('mysql:host='.$params['host'].';dbname='.$params['name'], |
59 | 59 | $params['user'], |
@@ -65,19 +65,19 @@ discard block |
||
65 | 65 | } |
66 | 66 | |
67 | 67 | /** |
68 | - * Motor de base de datos SQLite |
|
69 | - * |
|
70 | - * @param array $params: Lista de parámetros de configuración |
|
71 | - */ |
|
68 | + * Motor de base de datos SQLite |
|
69 | + * |
|
70 | + * @param array $params: Lista de parámetros de configuración |
|
71 | + */ |
|
72 | 72 | final private function motor_sqlite(array $params) { |
73 | 73 | parent::__construct('sqlite:'.$params['name']); |
74 | 74 | } |
75 | 75 | |
76 | 76 | /** |
77 | - * Motor de base de datos Cubrid |
|
78 | - * |
|
79 | - * @param array $params: Lista de parámetros de configuración |
|
80 | - */ |
|
77 | + * Motor de base de datos Cubrid |
|
78 | + * |
|
79 | + * @param array $params: Lista de parámetros de configuración |
|
80 | + */ |
|
81 | 81 | final private function motor_cubrid(array $params) { |
82 | 82 | parent::__construct('cubrid:host='.$params['host'].';dbname='.$params['name'].';port='.$params['port'], |
83 | 83 | $params['user'], |
@@ -88,10 +88,10 @@ discard block |
||
88 | 88 | } |
89 | 89 | |
90 | 90 | /** |
91 | - * Motor de base de datos Firebird |
|
92 | - * |
|
93 | - * @param array $params: Lista de parámetros de configuración |
|
94 | - */ |
|
91 | + * Motor de base de datos Firebird |
|
92 | + * |
|
93 | + * @param array $params: Lista de parámetros de configuración |
|
94 | + */ |
|
95 | 95 | final private function motor_firebird(array $params) { |
96 | 96 | parent::__construct('firebird:dbname='.$params['host'].':'.$params['name'], |
97 | 97 | $params['user'], |
@@ -102,10 +102,10 @@ discard block |
||
102 | 102 | } |
103 | 103 | |
104 | 104 | /** |
105 | - * Motor de base de datos ODBC |
|
106 | - * |
|
107 | - * @param array $params: Lista de parámetros de configuración |
|
108 | - */ |
|
105 | + * Motor de base de datos ODBC |
|
106 | + * |
|
107 | + * @param array $params: Lista de parámetros de configuración |
|
108 | + */ |
|
109 | 109 | final private function motor_odbc(array $params) { |
110 | 110 | parent::__construct('odbc:'.$params['name'], |
111 | 111 | $params['user'], |
@@ -114,10 +114,10 @@ discard block |
||
114 | 114 | } |
115 | 115 | |
116 | 116 | /** |
117 | - * Motor de base de datos Oracle |
|
118 | - * |
|
119 | - * @param array $params: Lista de parámetros de configuración |
|
120 | - */ |
|
117 | + * Motor de base de datos Oracle |
|
118 | + * |
|
119 | + * @param array $params: Lista de parámetros de configuración |
|
120 | + */ |
|
121 | 121 | final private function motor_oracle(array $params) { |
122 | 122 | parent::__construct('oci:dbname=(DESCRIPTION = |
123 | 123 | (ADDRESS_LIST = |
@@ -134,10 +134,10 @@ discard block |
||
134 | 134 | } |
135 | 135 | |
136 | 136 | /** |
137 | - * Motor de base de datos PostgreSQL |
|
138 | - * |
|
139 | - * @param array $params: Lista de parámetros de configuración |
|
140 | - */ |
|
137 | + * Motor de base de datos PostgreSQL |
|
138 | + * |
|
139 | + * @param array $params: Lista de parámetros de configuración |
|
140 | + */ |
|
141 | 141 | final private function motor_postgresql(array $params) { |
142 | 142 | parent::__construct('pgsql:host='.$params['host'].';dbname='.$params['name'].';charset=utf8', |
143 | 143 | $params['user'], |
@@ -148,11 +148,11 @@ discard block |
||
148 | 148 | } |
149 | 149 | |
150 | 150 | /** |
151 | - * Motor de base de datos MSSQL |
|
152 | - * Añadido por marc2684 https://github.com/prinick96/Ocrend-Framework/issues/7 |
|
153 | - * |
|
154 | - * @param array $params: Lista de parámetros de configuración |
|
155 | - */ |
|
151 | + * Motor de base de datos MSSQL |
|
152 | + * Añadido por marc2684 https://github.com/prinick96/Ocrend-Framework/issues/7 |
|
153 | + * |
|
154 | + * @param array $params: Lista de parámetros de configuración |
|
155 | + */ |
|
156 | 156 | final private function motor_mssql(array $params) { |
157 | 157 | parent::__construct('sqlsrv:Server='.$params['host'].';Database='.$params['name'].';ConnectionPooling=0', |
158 | 158 | $params['user'], |
@@ -164,16 +164,16 @@ discard block |
||
164 | 164 | } |
165 | 165 | |
166 | 166 | /** |
167 | - * Inicia la conexión con la base de datos seleccionada |
|
168 | - * |
|
169 | - * @param string|null $name : Nombre de la base de datos a conectar |
|
170 | - * @param string|null $motor: Motor de la base de datos a conectar |
|
171 | - * @param bool $new_instance: true para iniciar una nueva instancia (al querer conectar a una DB distinta) |
|
172 | - * |
|
173 | - * @throws \RuntimeException si el motor no existe |
|
174 | - * @throws \RuntimeException si existe algún problema de conexión con la base de datos |
|
175 | - * @return Database : Instancia de conexión |
|
176 | - */ |
|
167 | + * Inicia la conexión con la base de datos seleccionada |
|
168 | + * |
|
169 | + * @param string|null $name : Nombre de la base de datos a conectar |
|
170 | + * @param string|null $motor: Motor de la base de datos a conectar |
|
171 | + * @param bool $new_instance: true para iniciar una nueva instancia (al querer conectar a una DB distinta) |
|
172 | + * |
|
173 | + * @throws \RuntimeException si el motor no existe |
|
174 | + * @throws \RuntimeException si existe algún problema de conexión con la base de datos |
|
175 | + * @return Database : Instancia de conexión |
|
176 | + */ |
|
177 | 177 | final public function __construct(string $name, string $motor) { |
178 | 178 | global $config; |
179 | 179 | |
@@ -197,34 +197,34 @@ discard block |
||
197 | 197 | } |
198 | 198 | |
199 | 199 | /** |
200 | - * Convierte en arreglo asociativo de todos los resultados arrojados por una query |
|
201 | - * |
|
202 | - * @param object \PDOStatement $query, valor devuelto de la query |
|
203 | - * |
|
204 | - * @return array arreglo asociativo |
|
205 | - */ |
|
200 | + * Convierte en arreglo asociativo de todos los resultados arrojados por una query |
|
201 | + * |
|
202 | + * @param object \PDOStatement $query, valor devuelto de la query |
|
203 | + * |
|
204 | + * @return array arreglo asociativo |
|
205 | + */ |
|
206 | 206 | final public function fetch_array(\PDOStatement $query) : array { |
207 | 207 | return $query->fetchAll(\PDO::FETCH_ASSOC); |
208 | 208 | } |
209 | 209 | |
210 | - /** |
|
211 | - * Cantidad de filas encontradas después de un SELECT |
|
212 | - * |
|
213 | - * @param object \PDOStatement $query, valor devuelto de la query |
|
214 | - * |
|
215 | - * @return int numero de filas encontradas |
|
216 | - */ |
|
210 | + /** |
|
211 | + * Cantidad de filas encontradas después de un SELECT |
|
212 | + * |
|
213 | + * @param object \PDOStatement $query, valor devuelto de la query |
|
214 | + * |
|
215 | + * @return int numero de filas encontradas |
|
216 | + */ |
|
217 | 217 | final public function rows(\PDOStatement $query) : int { |
218 | 218 | return $query->rowCount(); |
219 | 219 | } |
220 | 220 | |
221 | 221 | /** |
222 | - * Sana un valor para posteriormente ser introducido en una query |
|
223 | - * |
|
224 | - * @param null/string/int/float a sanar |
|
225 | - * |
|
226 | - * @return mixed elemento sano |
|
227 | - */ |
|
222 | + * Sana un valor para posteriormente ser introducido en una query |
|
223 | + * |
|
224 | + * @param null/string/int/float a sanar |
|
225 | + * |
|
226 | + * @return mixed elemento sano |
|
227 | + */ |
|
228 | 228 | final public function scape($e) { |
229 | 229 | if(null === $e) { |
230 | 230 | return ''; |
@@ -241,28 +241,28 @@ discard block |
||
241 | 241 | } |
242 | 242 | |
243 | 243 | /** |
244 | - * Borra una serie de elementos de forma segura de una tabla en la base de datos |
|
245 | - * |
|
246 | - * @param string $table: Tabla a la cual se le quiere remover un elemento |
|
247 | - * @param string $where: Condición de borrado que define quien/quienes son dichos elementos |
|
248 | - * @param string $limit: Por defecto se limita a borrar un solo elemento que cumpla el $where |
|
249 | - * |
|
250 | - * @return \PDOStatement |
|
251 | - */ |
|
244 | + * Borra una serie de elementos de forma segura de una tabla en la base de datos |
|
245 | + * |
|
246 | + * @param string $table: Tabla a la cual se le quiere remover un elemento |
|
247 | + * @param string $where: Condición de borrado que define quien/quienes son dichos elementos |
|
248 | + * @param string $limit: Por defecto se limita a borrar un solo elemento que cumpla el $where |
|
249 | + * |
|
250 | + * @return \PDOStatement |
|
251 | + */ |
|
252 | 252 | final public function delete(string $table, string $where, string $limit = 'LIMIT 1') : \PDOStatement { |
253 | 253 | return $this->query("DELETE FROM $table WHERE $where $limit;"); |
254 | 254 | } |
255 | 255 | |
256 | 256 | /** |
257 | - * Inserta una serie de elementos a una tabla en la base de datos |
|
258 | - * |
|
259 | - * @param string $table: Tabla a la cual se le va a insertar elementos |
|
260 | - * @param array $e: Arreglo asociativo de elementos, con la estrctura 'campo_en_la_tabla' => 'valor_a_insertar_en_ese_campo', |
|
261 | - * todos los elementos del arreglo $e, serán sanados por el método sin necesidad de hacerlo manualmente al crear el arreglo |
|
262 | - * |
|
263 | - * @throws \RuntimeException si el arreglo está vacío |
|
264 | - * @return \PDOStatement |
|
265 | - */ |
|
257 | + * Inserta una serie de elementos a una tabla en la base de datos |
|
258 | + * |
|
259 | + * @param string $table: Tabla a la cual se le va a insertar elementos |
|
260 | + * @param array $e: Arreglo asociativo de elementos, con la estrctura 'campo_en_la_tabla' => 'valor_a_insertar_en_ese_campo', |
|
261 | + * todos los elementos del arreglo $e, serán sanados por el método sin necesidad de hacerlo manualmente al crear el arreglo |
|
262 | + * |
|
263 | + * @throws \RuntimeException si el arreglo está vacío |
|
264 | + * @return \PDOStatement |
|
265 | + */ |
|
266 | 266 | final public function insert(string $table, array $e) : \PDOStatement { |
267 | 267 | if (sizeof($e) == 0) { |
268 | 268 | throw new \RuntimeException('El arreglo pasado por $this->db->insert(\''.$table.'\',...) está vacío.'); |
@@ -282,17 +282,17 @@ discard block |
||
282 | 282 | } |
283 | 283 | |
284 | 284 | /** |
285 | - * Actualiza elementos de una tabla en la base de datos según una condición |
|
286 | - * |
|
287 | - * @param string $table: Tabla a actualizar |
|
288 | - * @param array $e: Arreglo asociativo de elementos, con la estrctura 'campo_en_la_tabla' => 'valor_a_insertar_en_ese_campo', |
|
289 | - * todos los elementos del arreglo $e, serán sanados por el método sin necesidad de hacerlo manualmente al crear el arreglo |
|
290 | - * @param string $where: Condición que indica quienes serán modificados |
|
291 | - * @param string $limite: Límite de elementos modificados, por defecto los modifica a todos |
|
292 | - * |
|
293 | - * @throws \RuntimeException si el arreglo está vacío |
|
294 | - * @return \PDOStatement |
|
295 | - */ |
|
285 | + * Actualiza elementos de una tabla en la base de datos según una condición |
|
286 | + * |
|
287 | + * @param string $table: Tabla a actualizar |
|
288 | + * @param array $e: Arreglo asociativo de elementos, con la estrctura 'campo_en_la_tabla' => 'valor_a_insertar_en_ese_campo', |
|
289 | + * todos los elementos del arreglo $e, serán sanados por el método sin necesidad de hacerlo manualmente al crear el arreglo |
|
290 | + * @param string $where: Condición que indica quienes serán modificados |
|
291 | + * @param string $limite: Límite de elementos modificados, por defecto los modifica a todos |
|
292 | + * |
|
293 | + * @throws \RuntimeException si el arreglo está vacío |
|
294 | + * @return \PDOStatement |
|
295 | + */ |
|
296 | 296 | final public function update(string $table, array $e, string $where, string $limit = '') : \PDOStatement { |
297 | 297 | if (sizeof($e) == 0) { |
298 | 298 | throw new \RuntimeException('El arreglo pasado por $this->db->update(\''.$table.'\'...) está vacío.'); |
@@ -309,24 +309,24 @@ discard block |
||
309 | 309 | } |
310 | 310 | |
311 | 311 | /** |
312 | - * Selecciona y lista en un arreglo asociativo/numérico los resultados de una búsqueda en la base de datos |
|
313 | - * |
|
314 | - * @param string $e: Elementos a seleccionar separados por coma |
|
315 | - * @param string $tbale: Tabla de la cual se quiere extraer los elementos $e |
|
316 | - * @param string $where: Condición que indica quienes son los que se extraen, si no se coloca extrae todos |
|
317 | - * @param string $limite: Límite de elemntos a traer, por defecto trae TODOS los que cumplan $where |
|
318 | - * |
|
319 | - * @return mixed false si no encuentra ningún resultado, array asociativo/numérico si consigue al menos uno |
|
320 | - */ |
|
312 | + * Selecciona y lista en un arreglo asociativo/numérico los resultados de una búsqueda en la base de datos |
|
313 | + * |
|
314 | + * @param string $e: Elementos a seleccionar separados por coma |
|
315 | + * @param string $tbale: Tabla de la cual se quiere extraer los elementos $e |
|
316 | + * @param string $where: Condición que indica quienes son los que se extraen, si no se coloca extrae todos |
|
317 | + * @param string $limite: Límite de elemntos a traer, por defecto trae TODOS los que cumplan $where |
|
318 | + * |
|
319 | + * @return mixed false si no encuentra ningún resultado, array asociativo/numérico si consigue al menos uno |
|
320 | + */ |
|
321 | 321 | final public function select(string $e, string $table, string $where = '1 = 1', string $limit = "") { |
322 | 322 | return $this->query_select("SELECT $e FROM $table WHERE $where $limit;"); |
323 | 323 | } |
324 | 324 | |
325 | - /** |
|
326 | - * Realiza una query, ideal para trabajar con SELECTS, JOINS, etc |
|
327 | - * |
|
328 | - * @return array|false si no encuentra ningún resultado, array asociativo/numérico si consigue al menos uno |
|
329 | - */ |
|
325 | + /** |
|
326 | + * Realiza una query, ideal para trabajar con SELECTS, JOINS, etc |
|
327 | + * |
|
328 | + * @return array|false si no encuentra ningún resultado, array asociativo/numérico si consigue al menos uno |
|
329 | + */ |
|
330 | 330 | final public function query_select(string $query) { |
331 | 331 | $sql = $this->query($query); |
332 | 332 | $result = $sql->fetchAll(); |
@@ -340,13 +340,13 @@ discard block |
||
340 | 340 | } |
341 | 341 | |
342 | 342 | /** |
343 | - * Alert para evitar clonaciones |
|
344 | - * |
|
345 | - * @throws \RuntimeException si se intenta clonar la conexión |
|
346 | - * @return void |
|
347 | - */ |
|
343 | + * Alert para evitar clonaciones |
|
344 | + * |
|
345 | + * @throws \RuntimeException si se intenta clonar la conexión |
|
346 | + * @return void |
|
347 | + */ |
|
348 | 348 | final public function __clone() { |
349 | 349 | throw new \RuntimeException('Estás intentando clonar la Conexión'); |
350 | 350 | } |
351 | 351 | |
352 | - } |
|
353 | 352 | \ No newline at end of file |
353 | + } |
|
354 | 354 | \ No newline at end of file |
@@ -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 |
@@ -55,7 +55,7 @@ discard block |
||
55 | 55 | * @param array $params: Lista de parámetros de configuración |
56 | 56 | */ |
57 | 57 | final private function motor_mysql(array $params) { |
58 | - parent::__construct('mysql:host='.$params['host'].';dbname='.$params['name'], |
|
58 | + parent::__construct('mysql:host=' . $params['host'] . ';dbname=' . $params['name'], |
|
59 | 59 | $params['user'], |
60 | 60 | $params['pass'], |
61 | 61 | array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', |
@@ -70,7 +70,7 @@ discard block |
||
70 | 70 | * @param array $params: Lista de parámetros de configuración |
71 | 71 | */ |
72 | 72 | final private function motor_sqlite(array $params) { |
73 | - parent::__construct('sqlite:'.$params['name']); |
|
73 | + parent::__construct('sqlite:' . $params['name']); |
|
74 | 74 | } |
75 | 75 | |
76 | 76 | /** |
@@ -79,9 +79,9 @@ discard block |
||
79 | 79 | * @param array $params: Lista de parámetros de configuración |
80 | 80 | */ |
81 | 81 | final private function motor_cubrid(array $params) { |
82 | - parent::__construct('cubrid:host='.$params['host'].';dbname='.$params['name'].';port='.$params['port'], |
|
82 | + parent::__construct('cubrid:host=' . $params['host'] . ';dbname=' . $params['name'] . ';port=' . $params['port'], |
|
83 | 83 | $params['user'], |
84 | - $params['pass'],array( |
|
84 | + $params['pass'], array( |
|
85 | 85 | \PDO::ATTR_EMULATE_PREPARES => false, |
86 | 86 | \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION |
87 | 87 | )); |
@@ -93,9 +93,9 @@ discard block |
||
93 | 93 | * @param array $params: Lista de parámetros de configuración |
94 | 94 | */ |
95 | 95 | final private function motor_firebird(array $params) { |
96 | - parent::__construct('firebird:dbname='.$params['host'].':'.$params['name'], |
|
96 | + parent::__construct('firebird:dbname=' . $params['host'] . ':' . $params['name'], |
|
97 | 97 | $params['user'], |
98 | - $params['pass'],array( |
|
98 | + $params['pass'], array( |
|
99 | 99 | \PDO::ATTR_EMULATE_PREPARES => false, |
100 | 100 | \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION |
101 | 101 | )); |
@@ -107,7 +107,7 @@ discard block |
||
107 | 107 | * @param array $params: Lista de parámetros de configuración |
108 | 108 | */ |
109 | 109 | final private function motor_odbc(array $params) { |
110 | - parent::__construct('odbc:'.$params['name'], |
|
110 | + parent::__construct('odbc:' . $params['name'], |
|
111 | 111 | $params['user'], |
112 | 112 | $params['pass'] |
113 | 113 | ); |
@@ -121,12 +121,12 @@ discard block |
||
121 | 121 | final private function motor_oracle(array $params) { |
122 | 122 | parent::__construct('oci:dbname=(DESCRIPTION = |
123 | 123 | (ADDRESS_LIST = |
124 | - (ADDRESS = (PROTOCOL = '.$params['protocol'].')(HOST = '.$params['host'].')(PORT = '.$params['port'].')) |
|
124 | + (ADDRESS = (PROTOCOL = '.$params['protocol'] . ')(HOST = ' . $params['host'] . ')(PORT = ' . $params['port'] . ')) |
|
125 | 125 | ) |
126 | 126 | (CONNECT_DATA = |
127 | - (SERVICE_NAME = '.$params['name'].') |
|
127 | + (SERVICE_NAME = '.$params['name'] . ') |
|
128 | 128 | ) |
129 | - );charset=utf8',$params['database']['user'],$params['database']['pass'], |
|
129 | + );charset=utf8',$params['database']['user'], $params['database']['pass'], |
|
130 | 130 | array(\PDO::ATTR_EMULATE_PREPARES => false, |
131 | 131 | \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION, |
132 | 132 | \PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC |
@@ -139,9 +139,9 @@ discard block |
||
139 | 139 | * @param array $params: Lista de parámetros de configuración |
140 | 140 | */ |
141 | 141 | final private function motor_postgresql(array $params) { |
142 | - parent::__construct('pgsql:host='.$params['host'].';dbname='.$params['name'].';charset=utf8', |
|
142 | + parent::__construct('pgsql:host=' . $params['host'] . ';dbname=' . $params['name'] . ';charset=utf8', |
|
143 | 143 | $params['user'], |
144 | - $params['pass'],array( |
|
144 | + $params['pass'], array( |
|
145 | 145 | \PDO::ATTR_EMULATE_PREPARES => false, |
146 | 146 | \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION |
147 | 147 | )); |
@@ -154,9 +154,9 @@ discard block |
||
154 | 154 | * @param array $params: Lista de parámetros de configuración |
155 | 155 | */ |
156 | 156 | final private function motor_mssql(array $params) { |
157 | - parent::__construct('sqlsrv:Server='.$params['host'].';Database='.$params['name'].';ConnectionPooling=0', |
|
157 | + parent::__construct('sqlsrv:Server=' . $params['host'] . ';Database=' . $params['name'] . ';ConnectionPooling=0', |
|
158 | 158 | $params['user'], |
159 | - $params['pass'],array(\PDO::ATTR_EMULATE_PREPARES => false, |
|
159 | + $params['pass'], array(\PDO::ATTR_EMULATE_PREPARES => false, |
|
160 | 160 | \PDO::SQLSRV_ENCODING_UTF8, |
161 | 161 | \PDO::ATTR_ERRMODE => |
162 | 162 | \PDO::ERRMODE_EXCEPTION |
@@ -179,7 +179,7 @@ discard block |
||
179 | 179 | |
180 | 180 | try { |
181 | 181 | # Verificar existencia del motor |
182 | - if(method_exists($this,'motor_' . $motor)) { |
|
182 | + if (method_exists($this, 'motor_' . $motor)) { |
|
183 | 183 | $this->{'motor_' . $motor}(array( |
184 | 184 | 'host' => $config['database']['host'], |
185 | 185 | 'name' => $name, |
@@ -189,9 +189,9 @@ discard block |
||
189 | 189 | 'protocol' => $config['database']['protocol'] |
190 | 190 | )); |
191 | 191 | } else { |
192 | - throw new \RuntimeException('Motor '. $motor .' de conexión no identificado.'); |
|
192 | + throw new \RuntimeException('Motor ' . $motor . ' de conexión no identificado.'); |
|
193 | 193 | } |
194 | - } catch(\PDOException $e) { |
|
194 | + } catch (\PDOException $e) { |
|
195 | 195 | throw new \RuntimeException('Problema al conectar con la base de datos: ' . $e->getMessage()); |
196 | 196 | } |
197 | 197 | } |
@@ -226,18 +226,18 @@ discard block |
||
226 | 226 | * @return mixed elemento sano |
227 | 227 | */ |
228 | 228 | final public function scape($e) { |
229 | - if(null === $e) { |
|
229 | + if (null === $e) { |
|
230 | 230 | return ''; |
231 | 231 | } |
232 | 232 | |
233 | - if(is_numeric($e) and $e <= 2147483647) { |
|
234 | - if(explode('.',$e)[0] != $e) { |
|
233 | + if (is_numeric($e) and $e <= 2147483647) { |
|
234 | + if (explode('.', $e)[0] != $e) { |
|
235 | 235 | return (float) $e; |
236 | 236 | } |
237 | 237 | return (int) $e; |
238 | 238 | } |
239 | 239 | |
240 | - return (string) trim(str_replace(['\\',"\x00",'\n','\r',"'",'"',"\x1a"],['\\\\','\\0','\\n','\\r',"\'",'\"','\\Z'],$e)); |
|
240 | + return (string) trim(str_replace(['\\', "\x00", '\n', '\r', "'", '"', "\x1a"], ['\\\\', '\\0', '\\n', '\\r', "\'", '\"', '\\Z'], $e)); |
|
241 | 241 | } |
242 | 242 | |
243 | 243 | /** |
@@ -265,7 +265,7 @@ discard block |
||
265 | 265 | */ |
266 | 266 | final public function insert(string $table, array $e) : \PDOStatement { |
267 | 267 | if (sizeof($e) == 0) { |
268 | - throw new \RuntimeException('El arreglo pasado por $this->db->insert(\''.$table.'\',...) está vacío.'); |
|
268 | + throw new \RuntimeException('El arreglo pasado por $this->db->insert(\'' . $table . '\',...) está vacío.'); |
|
269 | 269 | } |
270 | 270 | |
271 | 271 | $query = "INSERT INTO $table ("; |
@@ -295,7 +295,7 @@ discard block |
||
295 | 295 | */ |
296 | 296 | final public function update(string $table, array $e, string $where, string $limit = '') : \PDOStatement { |
297 | 297 | if (sizeof($e) == 0) { |
298 | - throw new \RuntimeException('El arreglo pasado por $this->db->update(\''.$table.'\'...) está vacío.'); |
|
298 | + throw new \RuntimeException('El arreglo pasado por $this->db->update(\'' . $table . '\'...) está vacío.'); |
|
299 | 299 | } |
300 | 300 | |
301 | 301 | $query = "UPDATE $table SET "; |
@@ -332,7 +332,7 @@ discard block |
||
332 | 332 | $result = $sql->fetchAll(); |
333 | 333 | $sql->closeCursor(); |
334 | 334 | |
335 | - if(sizeof($result) > 0) { |
|
335 | + if (sizeof($result) > 0) { |
|
336 | 336 | return $result; |
337 | 337 | } |
338 | 338 |
@@ -43,19 +43,19 @@ 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 | # Verificar que no hay desnivel |
55 | - if(!is_array($a[$llave]) && !is_array($b[$llave])) { |
|
55 | + if (!is_array($a[$llave]) && !is_array($b[$llave])) { |
|
56 | 56 | $a[$llave] += $b[$llave]; |
57 | 57 | } else { |
58 | - throw new \RuntimeException('Existe un problema para operar en la llave '.$llave.'.'); |
|
58 | + throw new \RuntimeException('Existe un problema para operar en la llave ' . $llave . '.'); |
|
59 | 59 | break; |
60 | 60 | } |
61 | 61 | } |
@@ -76,7 +76,7 @@ discard block |
||
76 | 76 | final public static function get_key_by_index(string $index, array $a) : int { |
77 | 77 | $i = 0; |
78 | 78 | foreach ($a as $key => $val) { |
79 | - if($key == $index) { |
|
79 | + if ($key == $index) { |
|
80 | 80 | return (int) $i; |
81 | 81 | } |
82 | 82 | $i++; |
@@ -109,7 +109,7 @@ discard block |
||
109 | 109 | * @return bool false si no lo es, true si lo es |
110 | 110 | */ |
111 | 111 | final public static function is_assoc(array $a) : bool { |
112 | - if(sizeof($a) === 0) { |
|
112 | + if (sizeof($a) === 0) { |
|
113 | 113 | return false; |
114 | 114 | } |
115 | 115 |
@@ -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 | $intervalos = array("segundo", "minuto", "hora", "día", "semana", "mes", "año"); |
32 | 32 | $duraciones = array("60","60","24","7","4.35","12"); |
@@ -59,39 +59,39 @@ discard block |
||
59 | 59 | } |
60 | 60 | //------------------------------------------------ |
61 | 61 | /** |
62 | - * Compara un string hash con un string sin hash, si el string sin hash al encriptar posee la misma llave que hash, son iguales |
|
63 | - * |
|
64 | - * @param string $hash: Hash con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G |
|
65 | - * @param string $s2: Cadena de texto a comparar |
|
66 | - * |
|
67 | - * @example Strings::chash('$2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G','123456'); //return true |
|
68 | - * |
|
69 | - * @return bool true si $s2 contiene la misma llave que $hash, por tanto el contenido de $hash es $s2, de lo contrario false |
|
70 | - */ |
|
62 | + * Compara un string hash con un string sin hash, si el string sin hash al encriptar posee la misma llave que hash, son iguales |
|
63 | + * |
|
64 | + * @param string $hash: Hash con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G |
|
65 | + * @param string $s2: Cadena de texto a comparar |
|
66 | + * |
|
67 | + * @example Strings::chash('$2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G','123456'); //return true |
|
68 | + * |
|
69 | + * @return bool true si $s2 contiene la misma llave que $hash, por tanto el contenido de $hash es $s2, de lo contrario false |
|
70 | + */ |
|
71 | 71 | final public static function chash(string $hash, string $s2) : bool { |
72 | 72 | return $hash == crypt($s2, substr($hash, 0, 29)); |
73 | - } |
|
74 | - //------------------------------------------------ |
|
73 | + } |
|
74 | + //------------------------------------------------ |
|
75 | 75 | /** |
76 | - * Devuelve un hash DINÁMICO, para comparar un hash con un elemento se utiliza chash |
|
77 | - * |
|
78 | - * @param string $p: Cadena de texto a encriptar |
|
79 | - * |
|
80 | - * @return string Hash, con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G |
|
81 | - */ |
|
76 | + * Devuelve un hash DINÁMICO, para comparar un hash con un elemento se utiliza chash |
|
77 | + * |
|
78 | + * @param string $p: Cadena de texto a encriptar |
|
79 | + * |
|
80 | + * @return string Hash, con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G |
|
81 | + */ |
|
82 | 82 | final public static function hash(string $p) : string { |
83 | 83 | return crypt($p, '$2a$10$' . substr(sha1(mt_rand()),0,22)); |
84 | 84 | } |
85 | 85 | //------------------------------------------------ |
86 | 86 | /** |
87 | - * Calcula el tiempo de diferencia entre dos fechas |
|
88 | - * |
|
89 | - * @param string $ini: Fecha menor con el formato d-m-Y ó d/m/Y |
|
90 | - * @param string $fin: Fecha mayor con el formato d-m-Y ó d/m/Y |
|
91 | - * |
|
92 | - * @return int con la diferencia de tiempo en días |
|
93 | - * |
|
94 | - */ |
|
87 | + * Calcula el tiempo de diferencia entre dos fechas |
|
88 | + * |
|
89 | + * @param string $ini: Fecha menor con el formato d-m-Y ó d/m/Y |
|
90 | + * @param string $fin: Fecha mayor con el formato d-m-Y ó d/m/Y |
|
91 | + * |
|
92 | + * @return int con la diferencia de tiempo en días |
|
93 | + * |
|
94 | + */ |
|
95 | 95 | final public static function date_difference(string $ini, string $fin) : int { |
96 | 96 | $ini_i = explode('-',str_replace('/','-',$ini)); |
97 | 97 | $fin_i = explode('-',str_replace('/','-',$fin)); |
@@ -99,90 +99,90 @@ discard block |
||
99 | 99 | } |
100 | 100 | //------------------------------------------------ |
101 | 101 | /** |
102 | - * Calcula la edad de una persona segun la fecha de nacimiento |
|
103 | - * |
|
104 | - * @param string $cumple: Fecha de nacimiento con el formato d-m-Y ó d/m/Y |
|
105 | - * |
|
106 | - * @return int con la edad |
|
107 | - * |
|
108 | - */ |
|
102 | + * Calcula la edad de una persona segun la fecha de nacimiento |
|
103 | + * |
|
104 | + * @param string $cumple: Fecha de nacimiento con el formato d-m-Y ó d/m/Y |
|
105 | + * |
|
106 | + * @return int con la edad |
|
107 | + * |
|
108 | + */ |
|
109 | 109 | final public static function calculate_age(string $cumple) : int { |
110 | 110 | $age = explode('.', (string) (self::date_difference($cumple,date('d-m-Y',time())) / 365)); |
111 | 111 | return (int) $age[0]; |
112 | 112 | } |
113 | 113 | //------------------------------------------------ |
114 | 114 | /** |
115 | - * Calcula cuántos días tiene el mes actual |
|
116 | - * |
|
117 | - * @return integer con la cantidad de días del mes |
|
118 | - * |
|
119 | - */ |
|
115 | + * Calcula cuántos días tiene el mes actual |
|
116 | + * |
|
117 | + * @return integer con la cantidad de días del mes |
|
118 | + * |
|
119 | + */ |
|
120 | 120 | final public static function days_of_month() : int { |
121 | 121 | return cal_days_in_month(CAL_GREGORIAN, (int) date('m',time()), (int) date('Y',time())); |
122 | 122 | } |
123 | 123 | //------------------------------------------------ |
124 | 124 | /** |
125 | - * Verifica si una cadena de texto tiene forma de email |
|
126 | - * |
|
127 | - * @param string $address: Cadena de texto con el email |
|
128 | - * |
|
129 | - * @return mixed devuelve TRUE si es un email y FALSE si no lo es |
|
130 | - */ |
|
125 | + * Verifica si una cadena de texto tiene forma de email |
|
126 | + * |
|
127 | + * @param string $address: Cadena de texto con el email |
|
128 | + * |
|
129 | + * @return mixed devuelve TRUE si es un email y FALSE si no lo es |
|
130 | + */ |
|
131 | 131 | final public static function is_email(string $address) { |
132 | 132 | return filter_var($address, FILTER_VALIDATE_EMAIL); |
133 | 133 | } |
134 | 134 | //------------------------------------------------ |
135 | 135 | /** |
136 | - * Remueve todos los espacios en blanco de un string |
|
137 | - * |
|
138 | - * @param string $s: Cadena de texto a convertir |
|
139 | - * |
|
140 | - * @return string del texto sin espacios |
|
141 | - */ |
|
136 | + * Remueve todos los espacios en blanco de un string |
|
137 | + * |
|
138 | + * @param string $s: Cadena de texto a convertir |
|
139 | + * |
|
140 | + * @return string del texto sin espacios |
|
141 | + */ |
|
142 | 142 | final public static function remove_spaces(string $s) : string { |
143 | 143 | return trim(str_replace(' ','',$s)); |
144 | 144 | } |
145 | 145 | //------------------------------------------------ |
146 | 146 | /** |
147 | - * Analiza si una cadena de texto es alfanumérica |
|
148 | - * |
|
149 | - * @param string $s: Cadena de texto a verificar |
|
150 | - * |
|
151 | - * @return bool, verdadero si es alfanumerica, falso si no |
|
152 | - */ |
|
147 | + * Analiza si una cadena de texto es alfanumérica |
|
148 | + * |
|
149 | + * @param string $s: Cadena de texto a verificar |
|
150 | + * |
|
151 | + * @return bool, verdadero si es alfanumerica, falso si no |
|
152 | + */ |
|
153 | 153 | final public static function alphanumeric(string $s) : bool { |
154 | 154 | return ctype_alnum(self::remove_spaces($s)); |
155 | 155 | } |
156 | 156 | //------------------------------------------------ |
157 | 157 | /** |
158 | - * Analiza si una cadena de texto verificando si sólamente tiene letras |
|
159 | - * |
|
160 | - * @param string $s: Cadena de texto a verificar |
|
161 | - * |
|
162 | - * @return bool, verdadero si sólamente tiene letras, falso si no |
|
163 | - */ |
|
158 | + * Analiza si una cadena de texto verificando si sólamente tiene letras |
|
159 | + * |
|
160 | + * @param string $s: Cadena de texto a verificar |
|
161 | + * |
|
162 | + * @return bool, verdadero si sólamente tiene letras, falso si no |
|
163 | + */ |
|
164 | 164 | final public static function only_letters(string $s) : bool { |
165 | 165 | return ctype_alpha(self::remove_spaces($s)); |
166 | 166 | } |
167 | 167 | //------------------------------------------------ |
168 | 168 | /** |
169 | - * Analiza si una cadena de texto contiene sólamente letras y números |
|
170 | - * |
|
171 | - * @param string $s: Cadena de texto a verificar |
|
172 | - * |
|
173 | - * @return bool, verdadero si sólamente contiene letras y números, falso si no |
|
174 | - */ |
|
169 | + * Analiza si una cadena de texto contiene sólamente letras y números |
|
170 | + * |
|
171 | + * @param string $s: Cadena de texto a verificar |
|
172 | + * |
|
173 | + * @return bool, verdadero si sólamente contiene letras y números, falso si no |
|
174 | + */ |
|
175 | 175 | final public static function letters_and_numbers(string $s) : bool { |
176 | 176 | return (boolean) preg_match('/^[\w.]*$/', self::remove_spaces($s)); |
177 | 177 | } |
178 | 178 | //------------------------------------------------ |
179 | 179 | /** |
180 | - * Convierte una expresión de texto, a una compatible con url amigables |
|
181 | - * |
|
182 | - * @param string $url: Cadena de texto a convertir |
|
183 | - * |
|
184 | - * @return string Cadena de texto con formato de url amigable |
|
185 | - */ |
|
180 | + * Convierte una expresión de texto, a una compatible con url amigables |
|
181 | + * |
|
182 | + * @param string $url: Cadena de texto a convertir |
|
183 | + * |
|
184 | + * @return string Cadena de texto con formato de url amigable |
|
185 | + */ |
|
186 | 186 | final public static function url_amigable(string $url) : string { |
187 | 187 | $url = strtolower($url); |
188 | 188 | $url = str_replace (['á', 'é', 'í', 'ó', 'ú', 'ñ'],['a', 'e', 'i', 'o', 'u', 'n'], $url); |
@@ -191,12 +191,12 @@ discard block |
||
191 | 191 | } |
192 | 192 | //------------------------------------------------ |
193 | 193 | /** |
194 | - * Convierte código BBCode en su equivalente HTML |
|
195 | - * |
|
196 | - * @param string $string: Código con formato BBCode dentro |
|
197 | - * |
|
198 | - * @return string del código BBCode transformado en HTML |
|
199 | - */ |
|
194 | + * Convierte código BBCode en su equivalente HTML |
|
195 | + * |
|
196 | + * @param string $string: Código con formato BBCode dentro |
|
197 | + * |
|
198 | + * @return string del código BBCode transformado en HTML |
|
199 | + */ |
|
200 | 200 | final public static function bbcode(string $string) : string { |
201 | 201 | $BBcode = array( |
202 | 202 | '/\[i\](.*?)\[\/i\]/is', |
@@ -244,58 +244,58 @@ discard block |
||
244 | 244 | } |
245 | 245 | //------------------------------------------------ |
246 | 246 | /** |
247 | - * Dice si un string comienza con un caracter especificado |
|
248 | - * |
|
249 | - * @param string $sx: Caracter de inicio |
|
250 | - * @param string $str: String a evaluar |
|
251 | - * @param bool $case_sensitive: Boolean para definir si será seible a mayúsculas o no |
|
252 | - * |
|
253 | - * @return bool True si comienza con el caracter especificado, False si no |
|
254 | - */ |
|
247 | + * Dice si un string comienza con un caracter especificado |
|
248 | + * |
|
249 | + * @param string $sx: Caracter de inicio |
|
250 | + * @param string $str: String a evaluar |
|
251 | + * @param bool $case_sensitive: Boolean para definir si será seible a mayúsculas o no |
|
252 | + * |
|
253 | + * @return bool True si comienza con el caracter especificado, False si no |
|
254 | + */ |
|
255 | 255 | final public static function begin_with(string $sx, string $str) : bool { |
256 | 256 | return (bool) (strlen($str) > 0 and $str[0] == $sx); |
257 | 257 | } |
258 | 258 | //------------------------------------------------ |
259 | 259 | /** |
260 | - * Dice si un string termina con una caracter especificado |
|
261 | - * |
|
262 | - * @param string $sx: Caracter del final |
|
263 | - * @param string $str: String a evaluar |
|
264 | - * |
|
265 | - * @return bool True si termina con el caracter especificado, False si no |
|
266 | - */ |
|
260 | + * Dice si un string termina con una caracter especificado |
|
261 | + * |
|
262 | + * @param string $sx: Caracter del final |
|
263 | + * @param string $str: String a evaluar |
|
264 | + * |
|
265 | + * @return bool True si termina con el caracter especificado, False si no |
|
266 | + */ |
|
267 | 267 | final public static function end_with(string $sx, string $str) : bool { |
268 | 268 | return (bool) (strlen($str) > 0 and $str[strlen($str) - 1] == $sx); |
269 | 269 | } |
270 | 270 | //------------------------------------------------ |
271 | 271 | /** |
272 | - * Ver si un string está contenido en otro |
|
273 | - * |
|
274 | - * @param $s: String contenido en $str |
|
275 | - * @param $str: String a evaluar |
|
276 | - * |
|
277 | - * @return bool True si $s está dentro de $str, False si no |
|
278 | - */ |
|
272 | + * Ver si un string está contenido en otro |
|
273 | + * |
|
274 | + * @param $s: String contenido en $str |
|
275 | + * @param $str: String a evaluar |
|
276 | + * |
|
277 | + * @return bool True si $s está dentro de $str, False si no |
|
278 | + */ |
|
279 | 279 | final public static function contain(string $s, string $str) : bool { |
280 | 280 | return (bool) (strpos($str, $s) !== false); |
281 | 281 | } |
282 | 282 | //------------------------------------------------ |
283 | 283 | /** |
284 | - * Devuelve la cantidad de palabras en un string |
|
285 | - * |
|
286 | - * @param $str: String a evaluar |
|
287 | - * |
|
288 | - * @return int Cantidad de palabras |
|
289 | - */ |
|
284 | + * Devuelve la cantidad de palabras en un string |
|
285 | + * |
|
286 | + * @param $str: String a evaluar |
|
287 | + * |
|
288 | + * @return int Cantidad de palabras |
|
289 | + */ |
|
290 | 290 | final public static function count_words(string $s) : int { |
291 | 291 | return (int) str_word_count($s,0); |
292 | 292 | } |
293 | 293 | //------------------------------------------------ |
294 | 294 | /** |
295 | - * Se obtiene de Twig_Extension y sirve para que cada función esté disponible como etiqueta en twig |
|
296 | - * |
|
297 | - * @return array Todas las funciones con sus respectivos nombres de acceso en plantillas twig |
|
298 | - */ |
|
295 | + * Se obtiene de Twig_Extension y sirve para que cada función esté disponible como etiqueta en twig |
|
296 | + * |
|
297 | + * @return array Todas las funciones con sus respectivos nombres de acceso en plantillas twig |
|
298 | + */ |
|
299 | 299 | public function getFunctions() : array { |
300 | 300 | return array( |
301 | 301 | new \Twig_Function('amigable_time', array($this, 'amigable_time')), |
@@ -319,10 +319,10 @@ discard block |
||
319 | 319 | } |
320 | 320 | //------------------------------------------------ |
321 | 321 | /** |
322 | - * Identificador único para la extensión de twig |
|
323 | - * |
|
324 | - * @return string Nombre de la extensión |
|
325 | - */ |
|
322 | + * Identificador único para la extensión de twig |
|
323 | + * |
|
324 | + * @return string Nombre de la extensión |
|
325 | + */ |
|
326 | 326 | public function getName() : string { |
327 | 327 | return 'ocrend_framework_helper_strings'; |
328 | 328 | } |
@@ -29,14 +29,14 @@ discard block |
||
29 | 29 | */ |
30 | 30 | final public static function amigable_time(int $from, int $to = 0) : string { |
31 | 31 | $intervalos = array("segundo", "minuto", "hora", "día", "semana", "mes", "año"); |
32 | - $duraciones = array("60","60","24","7","4.35","12"); |
|
32 | + $duraciones = array("60", "60", "24", "7", "4.35", "12"); |
|
33 | 33 | $to = $to === 0 ? time() : $to; |
34 | 34 | |
35 | - if(empty($from)) { |
|
35 | + if (empty($from)) { |
|
36 | 36 | return "Fecha incorracta"; |
37 | 37 | } |
38 | 38 | |
39 | - if($to > $from) { |
|
39 | + if ($to > $from) { |
|
40 | 40 | $diferencia = $to - $from; |
41 | 41 | $tiempo = "Hace"; |
42 | 42 | } else { |
@@ -44,15 +44,15 @@ discard block |
||
44 | 44 | $tiempo = "Dentro de"; |
45 | 45 | } |
46 | 46 | |
47 | - for($j = 0; $diferencia >= $duraciones[$j] && $j < count($duraciones)-1; $j++) { |
|
47 | + for ($j = 0; $diferencia >= $duraciones[$j] && $j < count($duraciones) - 1; $j++) { |
|
48 | 48 | $diferencia /= $duraciones[$j]; |
49 | 49 | } |
50 | 50 | |
51 | 51 | $diferencia = round($diferencia); |
52 | 52 | |
53 | - if($diferencia != 1) { |
|
54 | - $intervalos[5].="e"; //MESES |
|
55 | - $intervalos[$j].= "s"; |
|
53 | + if ($diferencia != 1) { |
|
54 | + $intervalos[5] .= "e"; //MESES |
|
55 | + $intervalos[$j] .= "s"; |
|
56 | 56 | } |
57 | 57 | |
58 | 58 | return "$tiempo $diferencia $intervalos[$j]"; |
@@ -80,7 +80,7 @@ discard block |
||
80 | 80 | * @return string Hash, con la forma $2a$10$87b2b603324793cc37f8dOPFTnHRY0lviq5filK5cN4aMCQDJcC9G |
81 | 81 | */ |
82 | 82 | final public static function hash(string $p) : string { |
83 | - return crypt($p, '$2a$10$' . substr(sha1(mt_rand()),0,22)); |
|
83 | + return crypt($p, '$2a$10$' . substr(sha1(mt_rand()), 0, 22)); |
|
84 | 84 | } |
85 | 85 | //------------------------------------------------ |
86 | 86 | /** |
@@ -93,9 +93,9 @@ discard block |
||
93 | 93 | * |
94 | 94 | */ |
95 | 95 | final public static function date_difference(string $ini, string $fin) : int { |
96 | - $ini_i = explode('-',str_replace('/','-',$ini)); |
|
97 | - $fin_i = explode('-',str_replace('/','-',$fin)); |
|
98 | - 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); |
|
96 | + $ini_i = explode('-', str_replace('/', '-', $ini)); |
|
97 | + $fin_i = explode('-', str_replace('/', '-', $fin)); |
|
98 | + 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); |
|
99 | 99 | } |
100 | 100 | //------------------------------------------------ |
101 | 101 | /** |
@@ -107,7 +107,7 @@ discard block |
||
107 | 107 | * |
108 | 108 | */ |
109 | 109 | final public static function calculate_age(string $cumple) : int { |
110 | - $age = explode('.', (string) (self::date_difference($cumple,date('d-m-Y',time())) / 365)); |
|
110 | + $age = explode('.', (string) (self::date_difference($cumple, date('d-m-Y', time()))/365)); |
|
111 | 111 | return (int) $age[0]; |
112 | 112 | } |
113 | 113 | //------------------------------------------------ |
@@ -118,7 +118,7 @@ discard block |
||
118 | 118 | * |
119 | 119 | */ |
120 | 120 | final public static function days_of_month() : int { |
121 | - return cal_days_in_month(CAL_GREGORIAN, (int) date('m',time()), (int) date('Y',time())); |
|
121 | + return cal_days_in_month(CAL_GREGORIAN, (int) date('m', time()), (int) date('Y', time())); |
|
122 | 122 | } |
123 | 123 | //------------------------------------------------ |
124 | 124 | /** |
@@ -140,7 +140,7 @@ discard block |
||
140 | 140 | * @return string del texto sin espacios |
141 | 141 | */ |
142 | 142 | final public static function remove_spaces(string $s) : string { |
143 | - return trim(str_replace(' ','',$s)); |
|
143 | + return trim(str_replace(' ', '', $s)); |
|
144 | 144 | } |
145 | 145 | //------------------------------------------------ |
146 | 146 | /** |
@@ -185,9 +185,9 @@ discard block |
||
185 | 185 | */ |
186 | 186 | final public static function url_amigable(string $url) : string { |
187 | 187 | $url = strtolower($url); |
188 | - $url = str_replace (['á', 'é', 'í', 'ó', 'ú', 'ñ'],['a', 'e', 'i', 'o', 'u', 'n'], $url); |
|
189 | - $url = str_replace([' ', '&', '\r\n', '\n', '+', '%'],'-',$url); |
|
190 | - return preg_replace (['/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/'],['', '-', ''], $url); |
|
188 | + $url = str_replace(['á', 'é', 'í', 'ó', 'ú', 'ñ'], ['a', 'e', 'i', 'o', 'u', 'n'], $url); |
|
189 | + $url = str_replace([' ', '&', '\r\n', '\n', '+', '%'], '-', $url); |
|
190 | + return preg_replace(['/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/'], ['', '-', ''], $url); |
|
191 | 191 | } |
192 | 192 | //------------------------------------------------ |
193 | 193 | /** |
@@ -240,7 +240,7 @@ discard block |
||
240 | 240 | '<span style="font-size: $1px">$2</span>', |
241 | 241 | '<span style="font-family: $1">$2</span>' |
242 | 242 | ); |
243 | - return nl2br(preg_replace($BBcode,$HTML,$string)); |
|
243 | + return nl2br(preg_replace($BBcode, $HTML, $string)); |
|
244 | 244 | } |
245 | 245 | //------------------------------------------------ |
246 | 246 | /** |
@@ -288,7 +288,7 @@ discard block |
||
288 | 288 | * @return int Cantidad de palabras |
289 | 289 | */ |
290 | 290 | final public static function count_words(string $s) : int { |
291 | - return (int) str_word_count($s,0); |
|
291 | + return (int) str_word_count($s, 0); |
|
292 | 292 | } |
293 | 293 | //------------------------------------------------ |
294 | 294 | /** |
@@ -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 (null === $var || empty(trim(str_replace(' ','',$var)))); |
|
108 | - } |
|
105 | + */ |
|
106 | + final public function emp($var) : bool { |
|
107 | + return (null === $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($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; |
@@ -292,7 +292,7 @@ discard block |
||
292 | 292 | * @param int $desde: Desde donde |
293 | 293 | * |
294 | 294 | * @return mixed |
295 | - */ |
|
295 | + */ |
|
296 | 296 | final public function desde_date(int $desde) { |
297 | 297 | # Obtener esta fecha |
298 | 298 | $hoy = date('d/m/Y/D',time()); |
@@ -300,19 +300,19 @@ discard block |
||
300 | 300 | |
301 | 301 | # Arreglo de condiciones y subcondiciones |
302 | 302 | $fecha = array( |
303 | - 1 => date('d/m/Y', time()), |
|
304 | - 2 => date('d/m/Y', time() - (60*60*24)), |
|
305 | - 3 => array( |
|
306 | - 'Mon' => $hoy[0], |
|
307 | - 'Tue' => intval($hoy[0]) - 1, |
|
308 | - 'Wed' => intval($hoy[0]) - 2, |
|
309 | - 'Thu' => intval($hoy[0]) - 3, |
|
310 | - 'Fri' => intval($hoy[0]) - 4, |
|
311 | - 'Sat' => intval($hoy[0]) - 5, |
|
312 | - 'Sun' => intval($hoy[0]) - 6 |
|
313 | - ), |
|
314 | - 4 => '01/'. $this->cero_izq($hoy[1]) .'/' . $hoy[2], |
|
315 | - 5 => '01/01/' . $hoy[2] |
|
303 | + 1 => date('d/m/Y', time()), |
|
304 | + 2 => date('d/m/Y', time() - (60*60*24)), |
|
305 | + 3 => array( |
|
306 | + 'Mon' => $hoy[0], |
|
307 | + 'Tue' => intval($hoy[0]) - 1, |
|
308 | + 'Wed' => intval($hoy[0]) - 2, |
|
309 | + 'Thu' => intval($hoy[0]) - 3, |
|
310 | + 'Fri' => intval($hoy[0]) - 4, |
|
311 | + 'Sat' => intval($hoy[0]) - 5, |
|
312 | + 'Sun' => intval($hoy[0]) - 6 |
|
313 | + ), |
|
314 | + 4 => '01/'. $this->cero_izq($hoy[1]) .'/' . $hoy[2], |
|
315 | + 5 => '01/01/' . $hoy[2] |
|
316 | 316 | ); |
317 | 317 | |
318 | 318 | if($desde == 3) { |
@@ -347,44 +347,44 @@ discard block |
||
347 | 347 | * Obtiene el tiempo actual |
348 | 348 | * |
349 | 349 | * @return int devuelve time() |
350 | - */ |
|
350 | + */ |
|
351 | 351 | final public function timestamp() : int { |
352 | - return time(); |
|
352 | + return time(); |
|
353 | 353 | } |
354 | 354 | |
355 | 355 | //------------------------------------------------ |
356 | 356 | |
357 | 357 | /** |
358 | 358 | * Se obtiene de Twig_Extension y sirve para que cada función esté disponible como etiqueta en twig |
359 | - * |
|
359 | + * |
|
360 | 360 | * @return array con todas las funciones con sus respectivos nombres de acceso en plantillas twig |
361 | - */ |
|
361 | + */ |
|
362 | 362 | public function getFunctions() : array { |
363 | 363 | return array( |
364 | - new \Twig_Function('percent', array($this, 'percent')), |
|
365 | - new \Twig_Function('convert', array($this, 'convert')), |
|
366 | - new \Twig_Function('get_gravatar', array($this, 'get_gravatar')), |
|
367 | - new \Twig_Function('emp', array($this, 'emp')), |
|
368 | - new \Twig_Function('e_dynamic', array($this, 'e')), |
|
369 | - new \Twig_Function('all_full', array($this, 'all_full')), |
|
370 | - new \Twig_Function('fecha', array($this, 'fecha')), |
|
371 | - new \Twig_Function('base_assets',array($this, 'base_assets')), |
|
372 | - new \Twig_Function('timestamp',array($this, 'timestamp')), |
|
373 | - new \Twig_Function('desde_date',array($this, 'desde_date')), |
|
374 | - new \Twig_Function('cero_izq',array($this, 'cero_izq')), |
|
375 | - new \Twig_Function('last_day_month',array($this, 'last_day_month')), |
|
376 | - new \Twig_Function('str_to_time',array($this, 'str_to_time')), |
|
377 | - new \Twig_Function('desde_date',array($this, 'desde_date')) |
|
378 | - ); |
|
379 | - } |
|
380 | - |
|
381 | - //------------------------------------------------ |
|
364 | + new \Twig_Function('percent', array($this, 'percent')), |
|
365 | + new \Twig_Function('convert', array($this, 'convert')), |
|
366 | + new \Twig_Function('get_gravatar', array($this, 'get_gravatar')), |
|
367 | + new \Twig_Function('emp', array($this, 'emp')), |
|
368 | + new \Twig_Function('e_dynamic', array($this, 'e')), |
|
369 | + new \Twig_Function('all_full', array($this, 'all_full')), |
|
370 | + new \Twig_Function('fecha', array($this, 'fecha')), |
|
371 | + new \Twig_Function('base_assets',array($this, 'base_assets')), |
|
372 | + new \Twig_Function('timestamp',array($this, 'timestamp')), |
|
373 | + new \Twig_Function('desde_date',array($this, 'desde_date')), |
|
374 | + new \Twig_Function('cero_izq',array($this, 'cero_izq')), |
|
375 | + new \Twig_Function('last_day_month',array($this, 'last_day_month')), |
|
376 | + new \Twig_Function('str_to_time',array($this, 'str_to_time')), |
|
377 | + new \Twig_Function('desde_date',array($this, 'desde_date')) |
|
378 | + ); |
|
379 | + } |
|
380 | + |
|
381 | + //------------------------------------------------ |
|
382 | 382 | |
383 | 383 | /** |
384 | - * Identificador único para la extensión de twig |
|
385 | - * |
|
386 | - * @return string con el nombre de la extensión |
|
387 | - */ |
|
384 | + * Identificador único para la extensión de twig |
|
385 | + * |
|
386 | + * @return string con el nombre de la extensión |
|
387 | + */ |
|
388 | 388 | public function getName() : string { |
389 | 389 | return 'ocrend_framework_func_class'; |
390 | 390 | } |
@@ -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 (null === $var || empty(trim(str_replace(' ','',$var)))); |
|
107 | + return (null === $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($this->emp(func_get_arg($i)) && func_get_arg($i) != '0') { |
|
138 | + if ($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,17 +257,17 @@ 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, mes y año incorrectos |
267 | - if ($this->check_str_to_time(0,$detail,1) |
|
268 | - || $this->check_str_to_time(1,$detail,1) |
|
267 | + if ($this->check_str_to_time(0, $detail, 1) |
|
268 | + || $this->check_str_to_time(1, $detail, 1) |
|
269 | 269 | || intval($detail[1]) > 12 |
270 | - || $this->check_str_to_time(2,$detail,1970)) { |
|
270 | + || $this->check_str_to_time(2, $detail, 1970)) { |
|
271 | 271 | return null; |
272 | 272 | } |
273 | 273 | |
@@ -277,7 +277,7 @@ discard block |
||
277 | 277 | $year = intval($detail[2]); |
278 | 278 | |
279 | 279 | // Veriricar dia según mes |
280 | - if($day > $this->last_day_month($month,$year)) { |
|
280 | + if ($day > $this->last_day_month($month, $year)) { |
|
281 | 281 | return null; |
282 | 282 | } |
283 | 283 | |
@@ -295,8 +295,8 @@ discard block |
||
295 | 295 | */ |
296 | 296 | final public function desde_date(int $desde) { |
297 | 297 | # Obtener esta fecha |
298 | - $hoy = date('d/m/Y/D',time()); |
|
299 | - $hoy = explode('/',$hoy); |
|
298 | + $hoy = date('d/m/Y/D', time()); |
|
299 | + $hoy = explode('/', $hoy); |
|
300 | 300 | |
301 | 301 | # Arreglo de condiciones y subcondiciones |
302 | 302 | $fecha = array( |
@@ -311,21 +311,21 @@ discard block |
||
311 | 311 | 'Sat' => intval($hoy[0]) - 5, |
312 | 312 | 'Sun' => intval($hoy[0]) - 6 |
313 | 313 | ), |
314 | - 4 => '01/'. $this->cero_izq($hoy[1]) .'/' . $hoy[2], |
|
314 | + 4 => '01/' . $this->cero_izq($hoy[1]) . '/' . $hoy[2], |
|
315 | 315 | 5 => '01/01/' . $hoy[2] |
316 | 316 | ); |
317 | 317 | |
318 | - if($desde == 3) { |
|
318 | + if ($desde == 3) { |
|
319 | 319 | # Dia actual |
320 | 320 | $dia = $fecha[3][$hoy[3]]; |
321 | 321 | |
322 | 322 | # Mes anterior y posiblemente, año también. |
323 | - if($dia == 0) { |
|
323 | + if ($dia == 0) { |
|
324 | 324 | # Restante de la fecha |
325 | - $real_fecha = $this->last_day_month($hoy[1],$hoy[2]) .'/'. $this->cero_izq($hoy[1] - 1) .'/'; |
|
325 | + $real_fecha = $this->last_day_month($hoy[1], $hoy[2]) . '/' . $this->cero_izq($hoy[1] - 1) . '/'; |
|
326 | 326 | |
327 | 327 | # Verificamos si estamos en enero |
328 | - if($hoy[1] == 1) { |
|
328 | + if ($hoy[1] == 1) { |
|
329 | 329 | return $real_fecha . ($hoy[2] - 1); |
330 | 330 | } |
331 | 331 | |
@@ -333,8 +333,8 @@ discard block |
||
333 | 333 | return $real_fecha . $hoy[2]; |
334 | 334 | } |
335 | 335 | |
336 | - return $this->cero_izq($dia) .'/'. $this->cero_izq($hoy[1]) .'/' . $hoy[2]; |
|
337 | - } else if(array_key_exists($desde,$fecha)) { |
|
336 | + return $this->cero_izq($dia) . '/' . $this->cero_izq($hoy[1]) . '/' . $hoy[2]; |
|
337 | + } else if (array_key_exists($desde, $fecha)) { |
|
338 | 338 | return $fecha[$desde]; |
339 | 339 | } |
340 | 340 | |
@@ -368,13 +368,13 @@ discard block |
||
368 | 368 | new \Twig_Function('e_dynamic', array($this, 'e')), |
369 | 369 | new \Twig_Function('all_full', array($this, 'all_full')), |
370 | 370 | new \Twig_Function('fecha', array($this, 'fecha')), |
371 | - new \Twig_Function('base_assets',array($this, 'base_assets')), |
|
372 | - new \Twig_Function('timestamp',array($this, 'timestamp')), |
|
373 | - new \Twig_Function('desde_date',array($this, 'desde_date')), |
|
374 | - new \Twig_Function('cero_izq',array($this, 'cero_izq')), |
|
375 | - new \Twig_Function('last_day_month',array($this, 'last_day_month')), |
|
376 | - new \Twig_Function('str_to_time',array($this, 'str_to_time')), |
|
377 | - new \Twig_Function('desde_date',array($this, 'desde_date')) |
|
371 | + new \Twig_Function('base_assets', array($this, 'base_assets')), |
|
372 | + new \Twig_Function('timestamp', array($this, 'timestamp')), |
|
373 | + new \Twig_Function('desde_date', array($this, 'desde_date')), |
|
374 | + new \Twig_Function('cero_izq', array($this, 'cero_izq')), |
|
375 | + new \Twig_Function('last_day_month', array($this, 'last_day_month')), |
|
376 | + new \Twig_Function('str_to_time', array($this, 'str_to_time')), |
|
377 | + new \Twig_Function('desde_date', array($this, 'desde_date')) |
|
378 | 378 | ); |
379 | 379 | } |
380 | 380 |