Completed
Push — master ( 1a59c2...c73113 )
by Florent
02:55
created

JWSLoader::loadSerializedJsonJWS()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 16
rs 9.4285
cc 2
eloc 9
nc 2
nop 1
1
<?php
2
3
/*
4
 * The MIT License (MIT)
5
 *
6
 * Copyright (c) 2014-2016 Spomky-Labs
7
 *
8
 * This software may be modified and distributed under the terms
9
 * of the MIT license.  See the LICENSE file for details.
10
 */
11
12
namespace Jose\Util;
13
14
use Base64Url\Base64Url;
15
use Jose\Object\JWS;
16
use Jose\Object\JWSInterface;
17
18
final class JWSLoader
19
{
20
    /**
21
     * @param array $data
22
     *
23
     * @return \Jose\Object\JWSInterface
24
     */
25
    public static function loadSerializedJsonJWS(array $data)
26
    {
27
        $jws = new JWS();
28
29
        self::populatePayload($jws, $data);
30
31
        foreach ($data['signatures'] as $signature) {
32
            $bin_signature = Base64Url::decode($signature['signature']);
33
            $protected_headers = self::getProtectedHeaders($signature);
34
            $headers = self::getHeaders($signature);
35
36
            $jws = $jws->addSignatureFromLoadedData($bin_signature, $protected_headers, $headers);
37
        }
38
39
        return $jws;
40
    }
41
42
    /**
43
     * @param array $data
44
     *
45
     * @return string|null
46
     */
47
    private static function getProtectedHeaders(array $data)
48
    {
49
        if (array_key_exists('protected', $data)) {
50
            return $data['protected'];
51
        }
52
    }
53
54
    /**
55
     * @param array $data
56
     *
57
     * @return array
58
     */
59
    private static function getHeaders(array $data)
60
    {
61
        if (array_key_exists('header', $data)) {
62
            return $data['header'];
63
        }
64
65
        return [];
66
    }
67
68
    /**
69
     * @param \Jose\Object\JWSInterface $jws
70
     * @param array                     $data
71
     */
72
    private static function populatePayload(JWSInterface &$jws, array $data)
73
    {
74
        if (array_key_exists('payload', $data)) {
75
            $payload = Base64Url::decode($data['payload']);
76
            $json = json_decode($payload, true);
77
            if (null !== $json && !empty($payload)) {
78
                $payload = $json;
79
            }
80
            $jws = $jws->withPayload($payload);
81
        }
82
    }
83
}
84