Failed Conditions
Push — v7 ( 3dace9...35cf1c )
by Florent
02:18
created

CompactSerializer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * The MIT License (MIT)
7
 *
8
 * Copyright (c) 2014-2017 Spomky-Labs
9
 *
10
 * This software may be modified and distributed under the terms
11
 * of the MIT license.  See the LICENSE file for details.
12
 */
13
14
namespace Jose\Component\Signature\Serializer;
15
16
use Base64Url\Base64Url;
17
use Jose\Component\Core\Converter\JsonConverterInterface;
18
use Jose\Component\Signature\JWS;
19
20
/**
21
 * Class CompactSerializer.
22
 */
23
final class CompactSerializer extends AbstractSerializer
24
{
25
    public const NAME = 'jws_compact';
26
27
    /**
28
     * @var JsonConverterInterface
29
     */
30
    private $jsonConverter;
31
32
    /**
33
     * JSONFlattenedSerializer constructor.
34
     *
35
     * @param JsonConverterInterface $jsonConverter
36
     */
37
    public function __construct(JsonConverterInterface $jsonConverter)
38
    {
39
        $this->jsonConverter = $jsonConverter;
40
    }
41
42
    /**
43
     * {@inheritdoc}
44
     */
45
    public function displayName(): string
46
    {
47
        return 'JWS Compact';
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public function name(): string
54
    {
55
        return self::NAME;
56
    }
57
58
    /**
59
     * {@inheritdoc}
60
     */
61
    public function serialize(JWS $jws, ?int $signatureIndex = null): string
62
    {
63
        if (null === $signatureIndex) {
64
            $signatureIndex = 0;
65
        }
66
        $signature = $jws->getSignature($signatureIndex);
67
        if (!empty($signature->getHeaders())) {
68
            throw new \LogicException('The signature contains unprotected headers and cannot be converted into compact JSON.');
69
        }
70
        if (!$this->isPayloadEncoded($signature->getProtectedHeaders()) && !empty($jws->getEncodedPayload())) {
71
            if (1 !== preg_match('/^[\x{20}-\x{2d}|\x{2f}-\x{7e}]*$/u', $jws->getPayload())) {
72
                throw new \LogicException('Unable to convert the JWS with non-encoded payload.');
73
            }
74
        }
75
76
        return sprintf(
77
            '%s.%s.%s',
78
            $signature->getEncodedProtectedHeaders(),
79
            $jws->getEncodedPayload(),
80
            Base64Url::encode($signature->getSignature())
81
        );
82
    }
83
84
    /**
85
     * {@inheritdoc}
86
     */
87
    public function unserialize(string $input): JWS
88
    {
89
        $parts = explode('.', $input);
90
        if (3 !== count($parts)) {
91
            throw new \InvalidArgumentException('Unsupported input');
92
        }
93
94
        try {
95
            $encodedProtectedHeaders = $parts[0];
96
            $protectedHeaders = $this->jsonConverter->decode(Base64Url::decode($parts[0]));
97
            if (empty($parts[1])) {
98
                $payload = null;
99
                $encodedPayload = null;
100
            } else {
101
                $encodedPayload = $parts[1];
102
                $payload = $this->isPayloadEncoded($protectedHeaders) ? Base64Url::decode($encodedPayload) : $encodedPayload;
103
            }
104
            $signature = Base64Url::decode($parts[2]);
105
106
            $jws = JWS::create($payload, $encodedPayload, empty($parts[1]));
107
            $jws = $jws->addSignature($signature, $protectedHeaders, $encodedProtectedHeaders);
108
109
            return $jws;
110
        } catch (\Exception $e) {
111
            throw new \InvalidArgumentException('Unsupported input');
112
        } catch (\Error $e) {
113
            throw new \InvalidArgumentException('Unsupported input');
114
        }
115
    }
116
}
117