Passed
Push — master ( f2f9fb...1cd2da )
by Fran
02:56
created

TemplateFunctions::encrypt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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