Completed
Push — v2.0.x ( 24925e...149802 )
by Florent
02:52
created

JWSLoader::loadSerializedJsonJWS()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
rs 9.4285
cc 2
eloc 10
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
use Jose\Object\Signature;
18
use Jose\Object\SignatureInterface;
19
20
final class JWSLoader
21
{
22
    /**
23
     * Loader constructor.
24
     */
25
    private function __construct()
26
    {
27
    }
28
29
    /**
30
     * @param array $data
31
     *
32
     * @return \Jose\Object\JWSInterface
33
     */
34
    public static function loadSerializedJsonJWS(array $data)
35
    {
36
        $jws = new JWS();
37
38
        self::populatePayload($jws, $data);
39
40
        foreach ($data['signatures'] as $signature) {
41
            $object = new Signature();
42
            $object = $object->withSignature(Base64Url::decode($signature['signature']));
43
44
            self::populateProtectedHeaders($object, $signature);
45
            self::populateHeaders($object, $signature);
46
47
            $jws = $jws->addSignature($object);
48
        }
49
50
        return $jws;
51
    }
52
53
    /**
54
     * @param \Jose\Object\SignatureInterface $signature
55
     * @param array                           $data
56
     */
57
    private static function populateProtectedHeaders(SignatureInterface &$signature, array $data)
58
    {
59
        if (array_key_exists('protected', $data)) {
60
            $signature = $signature->withEncodedProtectedHeaders($data['protected']);
61
        }
62
    }
63
64
    /**
65
     * @param \Jose\Object\SignatureInterface $signature
66
     * @param array                           $data
67
     */
68
    private static function populateHeaders(SignatureInterface &$signature, array $data)
69
    {
70
        if (array_key_exists('header', $data)) {
71
            $signature = $signature->withHeaders($data['header']);
72
        }
73
    }
74
75
    /**
76
     * @param \Jose\Object\JWSInterface $jws
77
     * @param array                     $data
78
     */
79
    private static function populatePayload(JWSInterface &$jws, array $data)
80
    {
81
        if (array_key_exists('payload', $data)) {
82
            $payload = Base64Url::decode($data['payload']);
83
            $json = json_decode($payload, true);
84
            if (null !== $json && !empty($payload)) {
85
                $payload = $json;
86
            }
87
            $jws = $jws->withPayload($payload);
88
        }
89
    }
90
}
91