Passed
Push — master ( d9c7de...c204f0 )
by Fran
04:05
created

Template::extractPath()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 9
ccs 7
cts 7
cp 1
crap 2
rs 9.6666
c 0
b 0
f 0
1
<?php
2
namespace PSFS\base;
3
4
use PSFS\base\config\Config;
5
use PSFS\base\extension\AssetsTokenParser;
6
use PSFS\base\extension\TemplateFunctions;
7
use PSFS\base\types\helpers\GeneratorHelper;
8
use PSFS\base\types\helpers\ResponseHelper;
9
use PSFS\base\types\traits\OutputTrait;
10
use PSFS\base\types\traits\RouteTrait;
11
use PSFS\base\types\traits\SingletonTrait;
12
13
/**
14
 * Class Template
15
 * @package PSFS\base
16
 */
17
class Template
18
{
19
    use SingletonTrait;
20
    use OutputTrait;
21
    use RouteTrait;
22
    const STATUS_OK = 'HTTP/1.0 200 OK';
23
    /**
24
     * @var \Twig_Environment tpl
25
     */
26
    protected $tpl;
27
    protected $filters = array();
28
29
    /**
30
     * Constructor por defecto
31
     */
32 1
    public function __construct()
33
    {
34 1
        $this->setup();
35 1
        $this->addTemplateFunctions();
36 1
        $this->addTemplateTokens();
37 1
        $this->optimizeTemplates();
38 1
    }
39
40
    /**
41
     * Método que devuelve el loader del Template
42
     * @return \Twig_LoaderInterface
43
     */
44 1
    public function getLoader()
45
    {
46 1
        return $this->tpl->getLoader();
47
    }
48
49
    /**
50
     * Método que activa la zona pública
51
     * @param bool $public
52
     *
53
     * @return Template
54
     */
55 1
    public function setPublicZone($public = true)
56
    {
57 1
        $this->public_zone = $public;
58 1
        return $this;
59
    }
60
61
    /**
62
     * @return bool
63
     */
64 1
    public function isPublicZone() {
65 1
        return $this->public_zone;
66
    }
67
68
    /**
69
     * Método que procesa la plantilla
70
     *
71
     * @param string $tpl
72
     * @param array $vars
73
     * @param array $cookies
74
     *
75
     * @return string HTML
0 ignored issues
show
Documentation introduced by
Should the return type not be string|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
76
     */
77 1
    public function render($tpl, array $vars = array(), array $cookies = array())
78
    {
79 1
        Logger::log('Start render response');
80 1
        $vars = ResponseHelper::setDebugHeaders($vars);
81
        $output = $this->dump($tpl, $vars);
82
83
        return $this->output($output, 'text/html', $cookies);
84
    }
85
86
    /**
87
     * Método que añade una nueva ruta al path de Twig
88
     * @param $path
89
     * @param $domain
90
     *
91
     * @return Template
92
     */
93 2
    public function addPath($path, $domain = '')
94
    {
95 2
        $this->tpl->getLoader()->addPath($path, $domain);
96 2
        return $this;
97
    }
98
99
    /**
100
     * Método que devuelve el contenido de una plantilla
101
     * @param string $tpl
102
     * @param array $vars
103
     * @return string
104
     */
105 1
    public function dump($tpl, array $vars = array())
106
    {
107 1
        $vars["__user__"] = Security::getInstance()->getUser();
108 1
        $vars["__admin__"] = Security::getInstance()->getAdmin();
109 1
        $vars["__profiles__"] = Security::getCleanProfiles();
110 1
        $vars["__flash__"] = Security::getInstance()->getFlashes();
111 1
        $dump = '';
112
        try {
113 1
            $dump = $this->tpl->render($tpl, $vars);
114 1
        } catch (\Exception $e) {
115
            Logger::log($e->getMessage(), LOG_ERR);
116
        }
117 1
        return $dump;
118
    }
119
120
    /**
121
     * Método que añade una función al motor de plantillas
122
     * @param string $templateFunction
123
     * @param $functionName
124
     *
125
     * @return Template
126
     */
127 1
    protected function addTemplateFunction($templateFunction, $functionName)
128 1
    {
129 1
        $function = new \Twig_SimpleFunction($templateFunction, $functionName);
130 1
        $this->tpl->addFunction($function);
131 1
        return $this;
132
    }
133
134
    /**
135
     * Servicio que regenera todas las plantillas
136
     * @return array
137
     */
138 1
    public function regenerateTemplates()
139
    {
140 1
        $this->generateTemplatesCache();
141 1
        $domains = Cache::getInstance()->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . "domains.json", Cache::JSON, true);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 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...
142 1
        $translations = [];
143 1
        if (is_array($domains)) {
144 1
            $translations = $this->parsePathTranslations($domains);
145 1
        }
146 1
        $translations[] = _("Plantillas regeneradas correctamente");
147 1
        return $translations;
148
    }
149
150
    /**
151
     * @param $tplDir
152
     * @param string $domain
153
     *
154
     * @return mixed
155
     */
156 1
    protected function generateTemplate($tplDir, $domain = '')
157
    {
158 1
        $templatesDir = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($tplDir), \RecursiveIteratorIterator::LEAVES_ONLY);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 138 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...
159 1
        foreach ($templatesDir as $file) {
160
            // force compilation
161 1
            if ($file->isFile()) {
162
                try {
163 1
                    $this->tpl->load(str_replace($tplDir . '/', '', $file));
164 1
                } catch (\Exception $e) {
165 1
                    Logger::log($e->getMessage(), LOG_ERR, ['file' => $e->getFile(), 'line' => $e->getLine()]);
166
                }
167 1
            }
168 1
        }
169 1
        return str_replace("%d", $domain, str_replace("%s", $tplDir, _("Generando plantillas en path '%s' para el dominio '%d'")));
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 131 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...
170
    }
171
172
    /**
173
     * Método que extrae el path de un string
174
     * @param $path
175
     *
176
     * @return string
177
     */
178 1
    public static function extractPath($path)
179
    {
180 1
        $explodePath = explode(DIRECTORY_SEPARATOR, $path);
181 1
        $realPath = array();
182 1
        for ($i = 0, $parts = count($explodePath) - 1; $i < $parts; $i++) {
183 1
            $realPath[] = $explodePath[$i];
184 1
        }
185 1
        return implode(DIRECTORY_SEPARATOR, $realPath);
186
    }
187
188
    /**
189
     * Método que devuelve los dominios de una plataforma
190
     * @param bool $append
191
     * @return array
192
     */
193 1
    static public function getDomains($append = false)
194
    {
195 1
        $domains = Router::getInstance()->getDomains();
196 1
        if ($append) {
197 1
            foreach ($domains as &$domain) {
198 1
                foreach ($domain as &$path) {
199 1
                    $path .= DIRECTORY_SEPARATOR;
200 1
                }
201 1
            }
202 1
        }
203 1
        return $domains;
204
    }
205
206
    /**
207
     * Método que añade todas las funciones de las plantillas
208
     */
209 1
    private function addTemplateFunctions()
210
    {
211
        //Asignamos las funciones especiales
212
        $functions = [
213 1
            'asset' => TemplateFunctions::ASSETS_FUNCTION,
214 1
            'form' => TemplateFunctions::FORM_FUNCTION,
215 1
            'form_widget' => TemplateFunctions::WIDGET_FUNCTION,
216 1
            'form_button' => TemplateFunctions::BUTTON_FUNCTION,
217 1
            'get_config' => TemplateFunctions::CONFIG_FUNCTION,
218 1
            'path' => TemplateFunctions::ROUTE_FUNCTION,
219 1
            'resource' => TemplateFunctions::RESOURCE_FUNCTION,
220 1
            'session' => TemplateFunctions::SESSION_FUNCTION,
221 1
            'existsFlash' => TemplateFunctions::EXISTS_FLASH_FUNCTION,
222 1
            'getFlash' => TemplateFunctions::GET_FLASH_FUNCTION,
223 1
        ];
224 1
        foreach($functions as $name => $function) {
225 1
            $this->addTemplateFunction($name, $function);
226 1
        }
227 1
    }
228
229
    /**
230
     * Método que devuelve el motod de plantillas
231
     * @return \Twig_Environment
232
     */
233 1
    public function getTemplateEngine()
234
    {
235 1
        return $this->tpl;
236
    }
237
238
    /**
239
     * Method that extract all domains for using them with the templates
240
     */
241 1
    private function loadDomains()
242
    {
243 1
        $domains = Cache::getInstance()->getDataFromFile(CONFIG_DIR . DIRECTORY_SEPARATOR . 'domains.json', Cache::JSON, true);
0 ignored issues
show
Coding Style introduced by
This line exceeds maximum limit of 120 characters; contains 127 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...
244 1
        if (null !== $domains) {
245 1
            foreach ($domains as $domain => $paths) {
246 1
                $this->addPath($paths['template'], preg_replace('/(@|\/)/', '', $domain));
247 1
            }
248 1
        }
249 1
    }
250
251
    /**
252
     * Método que inicializa el motor de plantillas
253
     */
254 1
    private function setup()
255
    {
256 1
        $loader = new \Twig_Loader_Filesystem(GeneratorHelper::getTemplatePath());
257 1
        $this->tpl = new \Twig_Environment($loader, array(
258 1
            'cache' => CACHE_DIR . DIRECTORY_SEPARATOR . 'twig',
259 1
            'debug' => (bool)$this->debug,
260 1
            'auto_reload' => Config::getParam('twig.auto_reload', TRUE),
261 1
        ));
262 1
        $this->loadDomains();
263 1
    }
264
265
    /**
266
     * Método que inyecta los parseadores
267
     */
268 1
    private function addTemplateTokens()
269
    {
270
        //Añadimos las extensiones de los tags
271 1
        $this->tpl->addTokenParser(new AssetsTokenParser("css"));
272 1
        $this->tpl->addTokenParser(new AssetsTokenParser("js"));
273 1
    }
274
275
    /**
276
     * Método que inyecta las optimizaciones al motor de la plantilla
277
     */
278 1
    private function optimizeTemplates()
279
    {
280
        //Optimizamos
281 1
        $this->tpl->addExtension(new \Twig_Extensions_Extension_I18n());
282 1
    }
283
284
    /**
285
     * Method that extract all path tag for extracting translations
286
     * @param array $domains
287
     *
288
     * @return array
289
     */
290 1
    private function parsePathTranslations($domains)
291
    {
292 1
        $translations = array();
293 1
        if (!empty($domains)) {
294 1
            foreach ($domains as $domain => $paths) {
295 1
                if (strlen($domain) && array_key_exists("template", $paths)) {
296 1
                    $this->addPath($paths["template"], $domain);
297 1
                    $translations[] = $this->generateTemplate($paths["template"], $domain);
298 1
                }
299 1
            }
300 1
        }
301
302 1
        return $translations;
303
    }
304
305
    /**
306
     * Method that generate all template caches
307
     */
308 1
    private function generateTemplatesCache()
309
    {
310
        /** @var \Twig_Loader_Filesystem $loader */
311 1
        $loader = $this->tpl->getLoader();
312 1
        $availablePaths = $loader->getPaths();
313 1
        if (!empty($availablePaths)) {
314 1
            foreach ($availablePaths as $path) {
315 1
                $this->generateTemplate($path);
316 1
            }
317 1
        }
318 1
    }
319
}
320