Completed
Push — master ( ff92f6...3ef1d3 )
by John
09:08
created

Decoder::jsonDecode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 10
Ratio 100 %

Importance

Changes 0
Metric Value
dl 10
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php declare(strict_types = 1);
2
/*
3
 * This file is part of the KleijnWeb\JwtBundle package.
4
 *
5
 * For the full copyright and license information, please view the LICENSE
6
 * file that was distributed with this source code.
7
 */
8
namespace KleijnWeb\JwtBundle\Jwt;
9
10
/**
11
 * @author John Kleijn <[email protected]>
12
 */
13
class Decoder
14
{
15
    /**
16
     * @var array
17
     */
18
    private static $messages = [
19
        JSON_ERROR_NONE           => 'No error',
20
        JSON_ERROR_DEPTH          => 'Maximum stack depth exceeded',
21
        JSON_ERROR_STATE_MISMATCH => 'State mismatch (invalid or malformed JSON)',
22
        JSON_ERROR_CTRL_CHAR      => 'Control character error, possibly incorrectly encoded',
23
        JSON_ERROR_SYNTAX         => 'Syntax error',
24
        JSON_ERROR_UTF8           => 'Malformed UTF-8 characters, possibly incorrectly encoded'
25
    ];
26
27
    /**
28
     * @param string $base64Encoded
29
     *
30
     * @return array
31
     */
32
    public function decode(string $base64Encoded): array
33
    {
34
        return $this->jsonDecode($this->base64Decode($base64Encoded));
35
    }
36
37
    /**
38
     * @param string $plain
39
     *
40
     * @return array
41
     */
42 View Code Duplication
    public function jsonDecode(string $plain): array
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
43
    {
44
        $data = json_decode($plain, true);
45
46
        if (json_last_error() != JSON_ERROR_NONE) {
47
            throw new \RuntimeException(self::$messages[json_last_error()]);
48
        }
49
50
        return $data;
51
    }
52
53
    /**
54
     * @param string $base64Encoded
55
     *
56
     * @return string
57
     */
58
    public function base64Decode(string $base64Encoded): string
59
    {
60
        if ($remainder = strlen($base64Encoded) % 4) {
61
            $base64Encoded .= str_repeat('=', 4 - $remainder);
62
        }
63
64
        return base64_decode(strtr($base64Encoded, '-_', '+/'));
65
    }
66
}
67