Completed
Push — master ( e773ad...5a29ae )
by Colin
03:04
created

UrlEncoder::encode()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 8
cts 8
cp 1
rs 9.6
c 0
b 0
f 0
cc 3
nc 1
nop 1
crap 3
1
<?php
2
3
/*
4
 * This file is part of the league/commonmark package.
5
 *
6
 * (c) Colin O'Dell <[email protected]>
7
 *
8
 * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js)
9
 *  - (c) John MacFarlane
10
 *
11
 * For the full copyright and license information, please view the LICENSE
12
 * file that was distributed with this source code.
13
 */
14
15
namespace League\CommonMark\Util;
16
17
final class UrlEncoder
18
{
19
    private static $encodeCache = ["%00","%01","%02","%03","%04","%05","%06","%07","%08","%09","%0A","%0B","%0C","%0D","%0E","%0F","%10","%11","%12","%13","%14","%15","%16","%17","%18","%19","%1A","%1B","%1C","%1D","%1E","%1F","%20","!","%22","#","$","%25","&","'","(",")","*","+",",","-",".","/","0","1","2","3","4","5","6","7","8","9",":",";","%3C","=","%3E","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","%5B","%5C","%5D","%5E","_","%60","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","%7B","%7C","%7D","~","%7F"];
20
21
    /**
22
     * @param string $uri
23
     *
24
     * @return string
25
     */
26 651
    public static function unescapeAndEncode(string $uri): string
27
    {
28 651
        $result = '';
29
30
        /** @var string[] $chars */
31 651
        $chars = \preg_split('//u', $uri, -1, \PREG_SPLIT_NO_EMPTY);
32 651
        $l = \count($chars);
33 651
        for ($i = 0; $i < $l; $i++) {
34 642
            $code = $chars[$i];
35 642
            if ($code === '%' && $i + 2 < $l) {
36 96
                if (\preg_match('/^[0-9a-f]{2}$/i', $chars[$i+1] . $chars[$i+2]) === 1) {
37 96
                    $result .= '%' . $chars[$i+1] . $chars[$i+2];
38 96
                    $i += 2;
39 96
                    continue;
40
                }
41
            }
42
43 585
            if (\ord($code) < 128) {
44 585
                $result .= self::$encodeCache[\ord($code)];
45 585
                continue;
46
            }
47
48 18
            $result .= \rawurlencode($code);
49
        }
50
51 651
        return $result;
52
    }
53
}
54