Completed
Push — v2.0.x ( 2b2b8e...21aa40 )
by Florent
03:32
created

JWSLoader::populatePayload()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
rs 9.2
cc 4
eloc 7
nc 3
nop 2
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
use Jose\Object\Signature;
18
use Jose\Object\SignatureInterface;
19
20
final class JWSLoader
21
{
22
    /**
23
     * @param array $data
24
     *
25
     * @return \Jose\Object\JWSInterface
26
     */
27
    public static function loadSerializedJsonJWS(array $data)
28
    {
29
        $jws = new JWS();
30
31
        self::populatePayload($jws, $data);
32
33
        foreach ($data['signatures'] as $signature) {
34
            $object = new Signature();
35
            $object = $object->withSignature(Base64Url::decode($signature['signature']));
36
37
            self::populateProtectedHeaders($object, $signature);
38
            self::populateHeaders($object, $signature);
39
40
            $jws = $jws->addSignature($object);
41
        }
42
43
        return $jws;
44
    }
45
46
    /**
47
     * @param \Jose\Object\SignatureInterface $signature
48
     * @param array                           $data
49
     */
50
    private static function populateProtectedHeaders(SignatureInterface &$signature, array $data)
51
    {
52
        if (array_key_exists('protected', $data)) {
53
            $signature = $signature->withEncodedProtectedHeaders($data['protected']);
54
        }
55
    }
56
57
    /**
58
     * @param \Jose\Object\SignatureInterface $signature
59
     * @param array                           $data
60
     */
61
    private static function populateHeaders(SignatureInterface &$signature, array $data)
62
    {
63
        if (array_key_exists('header', $data)) {
64
            $signature = $signature->withHeaders($data['header']);
65
        }
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