Passed
Push — master ( e02aff...283335 )
by Fran
09:22
created

TemplateFunctions::existsFlash()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace PSFS\base\extension;
4
5
use Firebase\JWT\JWT;
6
use PSFS\base\Cache;
7
use PSFS\base\config\Config;
8
use PSFS\base\exception\GeneratorException;
9
use PSFS\base\Logger;
10
use PSFS\base\Request;
11
use PSFS\base\Router;
12
use PSFS\base\Security;
13
use PSFS\base\Template;
14
use PSFS\base\types\Form;
15
use PSFS\base\types\helpers\AssetsHelper;
16
use PSFS\base\types\helpers\AuthHelper;
17
use PSFS\base\types\helpers\GeneratorHelper;
18
19
/**
20
 * Class TemplateFunctions
21
 * @package PSFS\base\extension
22
 */
23
class TemplateFunctions
24
{
25
26
    const ASSETS_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::asset';
27
    const ROUTE_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::route';
28
    const CONFIG_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::config';
29
    const BUTTON_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::button';
30
    const WIDGET_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::widget';
31
    const FORM_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::form';
32
    const RESOURCE_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::resource';
33
    const SESSION_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::session';
34
    const EXISTS_FLASH_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::existsFlash';
35
    const GET_FLASH_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::getFlash';
36
    const GET_QUERY_FUNCTION = '\\PSFS\\base\\extension\\TemplateFunctions::query';
37
    const ENCRYPT_FUNCTION = '\PSFS\base\extension\TemplateFunctions::encrypt';
38
    const AUTH_TOKEN_FUNCTION = '\PSFS\base\extension\TemplateFunctions::generateAuthToken';
39
    const JWT_TOKEN_FUNCTION = '\PSFS\base\extension\TemplateFunctions::generateJWTToken';
40
41
    /**
42
     * Función que copia los recursos de las carpetas Public al DocumentRoot
43
     * @param string $string
44
     * @param string|null $name
45
     * @param bool $return
46
     * @return string|null
47
     * @throws \PSFS\base\exception\GeneratorException
48
     */
49 2
    public static function asset(string $string, string $name = null, bool $return = true): ?string
50
    {
51
52 2
        $filePath = $returnPath = '';
53 2
        if (!file_exists($filePath)) {
54 2
            $filePath = BASE_DIR . $string;
55
        }
56 2
        $filenamePath = AssetsHelper::findDomainPath($string, $filePath);
57 2
        if(!empty($filenamePath)){
58 2
            $filePath = self::processAsset($string, $name, $return, $filenamePath);
59 2
            $basePath = Config::getParam('resources.cdn.url', Request::getInstance()->getRootUrl(false));
60 2
            $returnPath = empty($name) ? $basePath . '/' . $filePath : $name;
61
        }
62 2
        return $return ? $returnPath : '';
63
    }
64
65
    /**
66
     * Función que devuelve una url correspondiente a una ruta
67
     * @param string $path
68
     * @param bool $absolute
69
     * @param array $params
70
     *
71
     * @return string|null
72
     */
73 2
    public static function route(string $path = '', bool $absolute = false, array $params = []): ?string
74
    {
75 2
        $router = Router::getInstance();
76
        try {
77 2
            return $router->getRoute($path, $absolute, $params);
78
        } catch (\Exception $e) {
79
            Logger::log($e->getMessage());
80
            return $router->getRoute('', $absolute, $params);
81
        }
82
    }
83
84
    /**
85
     * Función que devuelve un parámetro de la configuración
86
     * @param string $param
87
     * @param string $default
88
     *
89
     * @return mixed|null
90
     */
91 4
    public static function config(string $param, string $default = ''): mixed
92
    {
93 4
        return Config::getInstance()->get($param) ?: $default;
94
    }
95
96
    /**
97
     * Función que devuelve un query string
98
     * @param string $query
99
     *
100
     * @return string
101
     */
102
    public static function query(string $query): string
103
    {
104
        return Request::getInstance()->getQuery($query);
105
    }
106
107
    /**
108
     * @param array $button
109
     * @throws \Twig\Error\LoaderError
110
     * @throws \Twig\Error\RuntimeError
111
     * @throws \Twig\Error\SyntaxError
112
     */
113
    public static function button(array $button): void
114
    {
115
        Template::getInstance()->getTemplateEngine()->display('forms/button.html.twig', array(
116
            'button' => $button,
117
        ));
118
    }
119
120
    /**
121
     * @param array $field
122
     * @param string|null $label
123
     * @throws \Twig\Error\LoaderError
124
     * @throws \Twig\Error\RuntimeError
125
     * @throws \Twig\Error\SyntaxError
126
     */
127
    public static function widget(array $field, string $label = null): void
128
    {
129
        if (null !== $label) {
130
            $field['label'] = $label;
131
        }
132
        //Limpiamos los campos obligatorios
133
        if (!isset($field['required'])) {
134
            $field['required'] = true;
135
        }
136
        if (isset($field['required']) && (bool)$field['required'] === false) {
137
            unset($field['required']);
138
        }
139
        Template::getInstance()->getTemplateEngine()->display('forms/field.html.twig', array(
140
            'field' => $field,
141
        ));
142
    }
143
144
    /**
145
     * Función que deveulve un formulario en html
146
     * @param Form $form
147
     * @throws \Twig\Error\LoaderError
148
     * @throws \Twig\Error\RuntimeError
149
     * @throws \Twig\Error\SyntaxError
150
     */
151
    public static function form(Form $form): void
152
    {
153
        Template::getInstance()->getTemplateEngine()->display('forms/base.html.twig', array(
154
            'form' => $form,
155
        ));
156
    }
157
158
    /**
159
     * Función que copia un recurso directamente en el DocumentRoot
160
     * @param string $path
161
     * @param string $dest
162
     * @param bool|bool $force
163
     *
164
     * @return string
165
     * @throws \PSFS\base\exception\GeneratorException
166
     */
167 2
    public static function resource(string $path, string $dest, bool $force = false): string
168
    {
169 2
        $debug = Config::getParam('debug');
170 2
        $domains = Template::getDomains(true);
171 2
        $filenamePath = self::extractPathname($path, $domains);
172
        // Check if resources has been copied to public folders
173 2
        if (!$debug) {
174 1
            $cacheFilename = Config::getParam('cache.var', '__initial__') . '.file.cache';
175 1
            $cachedFiles = Cache::getInstance()->readFromCache($cacheFilename,
176 1
                1, fn() => [], Cache::JSON, true) ?: [];
177
            // Force the resource copy
178 1
            if (!in_array($filenamePath, $cachedFiles) || $force) {
179 1
                $force = true;
180 1
                $cachedFiles[] = $filenamePath;
181 1
                Cache::getInstance()->storeData($cacheFilename, $cachedFiles, Cache::JSON);
182
            }
183
        }
184 2
        GeneratorHelper::copyResources($dest, $force, $filenamePath, $debug);
185 2
        return '';
186
    }
187
188
    /**
189
     * Método que extrae el pathname para un dominio
190
     * @param string $path
191
     * @param $domains
192
     *
193
     * @return string|array
194
     */
195 2
    private static function extractPathname(string $path, $domains): string|array
196
    {
197 2
        $filenamePath = $path;
198 2
        if (!empty($domains) && !file_exists($path)) {
199 2
            foreach ($domains as $domain => $paths) {
200 2
                $domainFilename = str_replace($domain, $paths['public'], $path);
201 2
                if (file_exists($domainFilename)) {
202 2
                    $filenamePath = $domainFilename;
203 2
                    break;
204
                }
205
            }
206
207
        }
208
209 2
        return $filenamePath;
210
    }
211
212
    /**
213
     * @param $filenamePath
214
     * @throws \PSFS\base\exception\GeneratorException
215
     */
216
    private static function processCssLines($filenamePath): void
217
    {
218
        $handle = @fopen($filenamePath, 'r');
219
        if ($handle) {
0 ignored issues
show
introduced by
$handle is of type false|resource, thus it always evaluated to false.
Loading history...
220
            while (!feof($handle)) {
221
                AssetsParser::extractCssLineResource($handle, $filenamePath);
222
            }
223
            fclose($handle);
224
        }
225
    }
226
227
    /**
228
     * Método que copia el contenido de un recurso en su destino correspondiente
229
     * @param string|null $name
230
     * @param string $filenamePath
231
     * @param string $base
232
     * @param string $filePath
233
     */
234 2
    private static function putResourceContent(string|null $name, string $filenamePath, string $base, string $filePath): void
235
    {
236 2
        $data = file_get_contents($filenamePath);
237 2
        if (!empty($name)) {
238
            file_put_contents(WEB_DIR . DIRECTORY_SEPARATOR . $name, $data);
239
        } else {
240 2
            file_put_contents($base . $filePath, $data);
241
        }
242
    }
243
244
    /**
245
     * Método que procesa un recurso para su copia en el DocumentRoot
246
     * @param string $string
247
     * @param string|null $name
248
     * @param boolean $return
249
     * @param string $filenamePath
250
     * @return string
251
     * @throws GeneratorException
252
     */
253 2
    private static function processAsset(string $string, string|null $name = null, bool $return = true, string $filenamePath = ''): string
254
    {
255 2
        $filePath = $filenamePath;
256 2
        if (file_exists($filenamePath)) {
257 2
            list($base, $htmlBase, $filePath) = AssetsHelper::calculateAssetPath($string, $name, $return, $filenamePath);
258
            //Creamos el directorio si no existe
259 2
            GeneratorHelper::createDir($base . $htmlBase);
260
            //Si se ha modificado
261 2
            if (!file_exists($base . $filePath) || filemtime($base . $filePath) < filemtime($filenamePath)) {
262 2
                if ($htmlBase === 'css') {
263
                    self::processCssLines($filenamePath);
264
                }
265 2
                self::putResourceContent($name, $filenamePath, $base, $filePath);
266
            }
267
        }
268
269 2
        return $filePath;
270
    }
271
272
    /**
273
     * Template function for get a session var
274
     * @param string $key
275
     * @return mixed
276
     */
277 2
    public static function session(string $key): mixed
278
    {
279 2
        return Security::getInstance()->getSessionKey($key);
280
    }
281
282
    /**
283
     * Template function that check if exists any flash session var
284
     * @param string $key
285
     * @return bool
286
     */
287 2
    public static function existsFlash(string $key = ''): bool
288
    {
289 2
        return null !== Security::getInstance()->getFlash($key);
290
    }
291
292
    /**
293
     * Template function that get a flash session var
294
     * @param string $key
295
     * @return mixed
296
     */
297
    public static function getFlash(string $key): mixed
298
    {
299
        $var = Security::getInstance()->getFlash($key);
300
        Security::getInstance()->setFlash($key, null);
301
        return $var;
302
    }
303
304
    public static function encrypt(string $string, string $key): string {
305
        return AuthHelper::encrypt($string, $key);
306
    }
307
308 2
    public static function generateAuthToken(string $user, string $password, $userAgent = null) {
309 2
        return AuthHelper::generateToken($user, $password, $userAgent);
310
    }
311
312
    public static function generateJWTToken(string $user, string $module, string $password) {
313
        return JWT::encode([
314
            'iss' => Config::getParam('platform.name', 'PSFS'),
315
            'sub' => $user,
316
            'aud' => $module,
317
            'iat' => time(),
318
            'exp' => time() + 3600,
319
        ], $password, Config::getParam('jwt.alg', 'HS256'));
0 ignored issues
show
Bug introduced by
It seems like PSFS\base\config\Config:...ram('jwt.alg', 'HS256') can also be of type null; however, parameter $alg of Firebase\JWT\JWT::encode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

319
        ], $password, /** @scrutinizer ignore-type */ Config::getParam('jwt.alg', 'HS256'));
Loading history...
320
    }
321
322
}
323