Completed
Push — master ( 4036d4...da82e8 )
by Fran
03:44
created

TemplateFunctions::session()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
    namespace PSFS\base\extension;
3
4
    use PSFS\base\config\Config;
5
    use PSFS\base\exception\ConfigException;
6
    use PSFS\base\Request;
7
    use PSFS\base\Router;
8
    use PSFS\base\Security;
9
    use PSFS\base\Template;
10
    use PSFS\base\types\Form;
11
    use PSFS\Services\GeneratorService;
12
    use Symfony\Component\Translation\Tests\StringClass;
13
14
    class TemplateFunctions {
15
16
        const ASSETS_FUNCTION       = "\\PSFS\\base\\extension\\TemplateFunctions::asset";
17
        const ROUTE_FUNCTION        = "\\PSFS\\base\\extension\\TemplateFunctions::route";
18
        const CONFIG_FUNCTION       = "\\PSFS\\base\\extension\\TemplateFunctions::config";
19
        const BUTTON_FUNCTION       = "\\PSFS\\base\\extension\\TemplateFunctions::button";
20
        const WIDGET_FUNCTION       = "\\PSFS\\base\\extension\\TemplateFunctions::widget";
21
        const FORM_FUNCTION         = "\\PSFS\\base\\extension\\TemplateFunctions::form";
22
        const RESOURCE_FUNCTION     = "\\PSFS\\base\\extension\\TemplateFunctions::resource";
23
        const SESSION_FUNCTION      = "\\PSFS\\base\\extension\\TemplateFunctions::session";
24
        const EXISTS_FLASH_FUNCTION = "\\PSFS\\base\\extension\\TemplateFunctions::existsFlash";
25
        const GET_FLASH_FUNCTION    = "\\PSFS\\base\\extension\\TemplateFunctions::getFlash";
26
27
        /**
28
         * Función que copia los recursos de las carpetas Public al DocumentRoot
29
         * @param $string
30
         * @param null $name
31
         * @param bool|TRUE $return
32
         *
33
         * @return string
34
         */
35
        public static function asset($string, $name = null, $return = true) {
36
37
            $file_path = "";
38
            if (!file_exists($file_path)) {
39
                $file_path = BASE_DIR.$string;
40
            }
41
            $filename_path = AssetsParser::findDomainPath($string, $file_path);
42
43
            $file_path = self::processAsset($string, $name, $return, $filename_path);
44
            $return_path = (empty($name)) ? Request::getInstance()->getRootUrl().'/'.$file_path : $name;
45
            return ($return) ? $return_path : '';
46
        }
47
48
        /**
49
         * Función que devuelve una url correspondiente a una ruta
50
         * @param string $path
51
         * @param bool|FALSE $absolute
52
         * @param array $params
0 ignored issues
show
Documentation introduced by
Should the type for parameter $params not be null|array? Also, consider making the array more specific, something like array<String>, or String[].

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive. In addition it looks for parameters that have the generic type array and suggests a stricter type like array<String>.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
53
         *
54
         * @return string|null
55
         */
56
        public static function route($path = '', $absolute = false, array $params = null) {
57
            $router = Router::getInstance();
58
            try {
59
                return $router->getRoute($path, $absolute, $params);
60
            } catch (\Exception $e)
61
            {
62
                return $router->getRoute('', $absolute, $params);
63
            }
64
        }
65
66
        /**
67
         * Función que devuelve un parámetro de la configuración
68
         * @param $param
69
         * @param string $default
70
         *
71
         * @return string
72
         */
73
        public static function config($param, $default = '') {
74
            return Config::getInstance()->get($param) ?: $default;
75
        }
76
77
        /**
78
         * Método que devuelve un botón en html para la plantilla de formularios
79
         * @param array $button
80
         */
81
        public static function button(array $button) {
82
            Template::getInstance()->getTemplateEngine()->display('forms/button.html.twig', array(
83
                'button' => $button,
84
            ));
85
        }
86
87
        /**
88
         * Función que pinta parte de un formulario
89
         * @param array $field
90
         * @param StringClass $label
91
         */
92
        public static function widget(array $field, StringClass $label = null) {
93
            if (!empty($label)) {
94
                $field["label"] = $label;
95
            }
96
            //Limpiamos los campos obligatorios
97
            if (!isset($field["required"])) {
98
                $field["required"] = true;
99
            } elseif (isset($field["required"]) && (bool)$field["required"] === false) {
100
                unset($field["required"]);
101
            }
102
            Template::getInstance()->getTemplateEngine()->display('forms/field.html.twig', array(
103
                'field' => $field,
104
            ));
105
        }
106
107
        /**
108
         * Función que deveulve un formulario en html
109
         * @param Form $form
110
         */
111
        public static function form(Form $form) {
112
            Template::getInstance()->getTemplateEngine()->display('forms/base.html.twig', array(
113
                'form' => $form,
114
            ));
115
        }
116
117
        /**
118
         * Función que copia un recurso directamente en el DocumentRoot
119
         * @param string $path
120
         * @param string $dest
121
         * @param bool|FALSE $force
122
         *
123
         * @return string
124
         * @throws ConfigException
125
         */
126
        public static function resource($path, $dest, $force = false) {
127
            $debug = Config::getInstance()->getDebugMode();
128
            $domains = Template::getDomains(true);
129
            $filename_path = self::extractPathname($path, $domains);
130
            GeneratorService::copyResources($dest, $force, $filename_path, $debug);
131
            return '';
132
        }
133
134
        /**
135
         * Método que extrae el pathname para un dominio
136
         * @param string $path
137
         * @param $domains
138
         *
139
         * @return mixed
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use string.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
140
         */
141
        private static function extractPathname($path, $domains)
142
        {
143
            $filename_path = $path;
144 View Code Duplication
            if (!file_exists($path) && !empty($domains)) {
145
                foreach ($domains as $domain => $paths) {
146
                    $domain_filename = str_replace($domain, $paths["public"], $path);
147
                    if (file_exists($domain_filename)) {
148
                        $filename_path = $domain_filename;
149
                        continue;
150
                    }
151
                }
152
153
            }
154
155
            return $filename_path;
156
        }
157
158
        /**
159
         * @param string $filename_path
160
         */
161
        private static function processCssLines($filename_path)
162
        {
163
            $handle = @fopen($filename_path, 'r');
164
            if ($handle) {
165
                while (!feof($handle)) {
166
                    AssetsParser::extractCssLineResource($handle, $filename_path);
167
                }
168
                fclose($handle);
169
            }
170
        }
171
172
        /**
173
         * Método que copia el contenido de un recurso en su destino correspondiente
174
         * @param string $name
175
         * @param string $filename_path
176
         * @param string $base
177
         * @param string $file_path
178
         */
179
        private static function putResourceContent($name, $filename_path, $base, $file_path)
180
        {
181
            $data = file_get_contents($filename_path);
182
            if (!empty($name)) file_put_contents(WEB_DIR.DIRECTORY_SEPARATOR.$name, $data);
183
            else file_put_contents($base.$file_path, $data);
184
        }
185
186
        /**
187
         * Método que procesa un recurso para su copia en el DocumentRoot
188
         * @param string $string
189
         * @param string $name
190
         * @param boolean $return
191
         * @param string $filename_path
192
         *
193
         * @return string
194
         */
195
        private static function processAsset($string, $name, $return, $filename_path)
196
        {
197
            $file_path = $filename_path;
198
            if (file_exists($filename_path)) {
199
                list($base, $html_base, $file_path) = AssetsParser::calculateAssetPath($string, $name, $return, $filename_path);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 128 characters

Overly long lines are hard to read on any screen. Most code styles therefor impose a maximum limit on the number of characters in a line.

Loading history...
200
                //Creamos el directorio si no existe
201
                Config::createDir($base.$html_base);
202
                //Si se ha modificado
203
                if (!file_exists($base.$file_path) || filemtime($base.$file_path) < filemtime($filename_path)) {
204
                    if ($html_base == 'css') {
205
                        self::processCssLines($filename_path);
206
                    }
207
                    self::putResourceContent($name, $filename_path, $base, $file_path);
208
                }
209
            }
210
211
            return $file_path;
212
        }
213
214
        /**
215
         * Template function for get a session var
216
         * @param string $key
217
         * @return mixed
218
         */
219
        public static function session($key) {
220
            return Security::getInstance()->getSessionKey($key);
221
        }
222
223
        /**
224
         * Template function that check if exists any flash session var
225
         * @param string $key
226
         * @return bool
227
         */
228
        public static function existsFlash($key = '') {
229
            return null !== Security::getInstance()->getFlash($key);
230
        }
231
232
        /**
233
         * Template function that get a flash session var
234
         * @param string $key
235
         * @return mixed
236
         */
237
        public static function getFlash($key) {
238
            $var = Security::getInstance()->getFlash($key);
239
            Security::getInstance()->setFlash($key, null);
240
            return $var;
241
        }
242
    }