blob: 65198bbb649f4dbdb2135332c49af727a66aa517 [file] [log] [blame]
Matthias Andreas Benkard12a57352021-12-28 18:02:04 +01001<?php
2
3/*
4 * This file is part of Twig.
5 *
6 * (c) Fabien Potencier
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Twig;
13
14/**
15 * Default autoescaping strategy based on file names.
16 *
17 * This strategy sets the HTML as the default autoescaping strategy,
18 * but changes it based on the template name.
19 *
20 * Note that there is no runtime performance impact as the
21 * default autoescaping strategy is set at compilation time.
22 *
23 * @author Fabien Potencier <fabien@symfony.com>
24 */
25class FileExtensionEscapingStrategy
26{
27 /**
28 * Guesses the best autoescaping strategy based on the file name.
29 *
30 * @param string $name The template name
31 *
32 * @return string|false The escaping strategy name to use or false to disable
33 */
34 public static function guess(string $name)
35 {
36 if (\in_array(substr($name, -1), ['/', '\\'])) {
37 return 'html'; // return html for directories
38 }
39
40 if ('.twig' === substr($name, -5)) {
41 $name = substr($name, 0, -5);
42 }
43
44 $extension = pathinfo($name, \PATHINFO_EXTENSION);
45
46 switch ($extension) {
47 case 'js':
48 return 'js';
49
50 case 'css':
51 return 'css';
52
53 case 'txt':
54 return false;
55
56 default:
57 return 'html';
58 }
59 }
60}