TYPO3 CMS  TYPO3_8-7
JavaScriptEncoder.php
Go to the documentation of this file.
1 <?php
3 
4 /*
5  * This file is part of the TYPO3 CMS project.
6  *
7  * It is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU General Public License, either version 2
9  * of the License, or any later version.
10  *
11  * For the full copyright and license information, please read the
12  * LICENSE.txt file that was distributed with this source code.
13  *
14  * The TYPO3 project - inspiring people to share!
15  */
16 
27 {
34  protected $hexMatrix = [];
35 
41  protected $immuneCharacters = [',', '.', '_'];
42 
48  protected $charsetConversion = null;
49 
55  public function __construct()
56  {
57  $this->charsetConversion = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Charset\CharsetConverter::class);
58  for ($i = 0; $i < 256; $i++) {
59  if ($i >= ord('0') && $i <= ord('9') || $i >= ord('A') && $i <= ord('Z') || $i >= ord('a') && $i <= ord('z')) {
60  $this->hexMatrix[$i] = null;
61  } else {
62  $this->hexMatrix[$i] = dechex($i);
63  }
64  }
65  }
66 
73  public function encode($input)
74  {
75  $stringLength = mb_strlen($input, 'utf-8');
76  $encodedString = '';
77  for ($i = 0; $i < $stringLength; $i++) {
78  $c = mb_substr($input, $i, 1, 'utf-8');
79  $encodedString .= $this->encodeCharacter($c);
80  }
81  return $encodedString;
82  }
83 
94  protected function encodeCharacter($character)
95  {
96  if ($this->isImmuneCharacter($character)) {
97  return $character;
98  }
99  $ordinalValue = $this->charsetConversion->utf8CharToUnumber($character);
100  // Check for alphanumeric characters
101  $hex = $this->getHexForNonAlphanumeric($ordinalValue);
102  if ($hex === null) {
103  return $character;
104  }
105  // Encode up to 256 with \\xHH
106  if ($ordinalValue < 256) {
107  $pad = substr('00', strlen($hex));
108  return '\\x' . $pad . strtoupper($hex);
109  }
110  // Otherwise encode with \\uHHHH
111  $pad = substr('0000', strlen($hex));
112  return '\\u' . $pad . strtoupper($hex);
113  }
114 
121  protected function isImmuneCharacter($character)
122  {
123  return in_array($character, $this->immuneCharacters, true);
124  }
125 
136  protected function getHexForNonAlphanumeric($ordinalValue)
137  {
138  if ($ordinalValue <= 255) {
139  return $this->hexMatrix[$ordinalValue];
140  }
141  return dechex($ordinalValue);
142  }
143 }
static makeInstance($className,... $constructorArguments)