Completed
Push — develop ( 12d03f...349d60 )
by Florent
02:41
created

JWS::addSignatureFromLoadedData()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 7
rs 9.4285
cc 1
eloc 4
nc 1
nop 3
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\Object;
13
14
use Assert\Assertion;
15
use Base64Url\Base64Url;
16
17
/**
18
 * Class JWS.
19
 */
20
final class JWS implements JWSInterface
21
{
22
    use JWT;
23
24
    /**
25
     * @var \Jose\Object\SignatureInterface[]
26
     */
27
    private $signatures = [];
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function getEncodedPayload()
33
    {
34
        $payload = $this->getPayload();
35
        if (null === $payload) {
36
            return;
37
        } elseif (is_string($payload)) {
38
            return Base64Url::encode($payload);
39
        }
40
        $encoded = json_encode($payload);
41
        Assertion::notNull($encoded, 'Unsupported payload.');
42
43
        return Base64Url::encode($encoded);
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function getSignatures()
50
    {
51
        return $this->signatures;
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57
    public function &getSignature($id)
58
    {
59
        if (isset($this->signatures[$id])) {
60
            return $this->signatures[$id];
61
        }
62
        throw new \InvalidArgumentException('The signature does not exist.');
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function addSignature(JWKInterface $signature_key, array $protected_headers, array $headers = [])
69
    {
70
        $jws = clone $this;
71
        $jws->signatures[] = Signature::createSignature($signature_key, $protected_headers, $headers);
72
73
        return $jws;
74
    }
75
76
    /**
77
     * {@inheritdoc}
78
     */
79
    public function addSignatureFromLoadedData($signature, $encoded_protected_headers, array $headers)
80
    {
81
        $jws = clone $this;
82
        $jws->signatures[] = Signature::createSignatureFromLoadedData($signature, $encoded_protected_headers, $headers);
83
84
        return $jws;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $jws; (Jose\Object\JWS) is incompatible with the return type declared by the interface Jose\Object\JWSInterface...SignatureFromLoadedData of type Jose\Object\Signature.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
85
    }
86
87
    /**
88
     * {@inheritdoc}
89
     */
90
    public function countSignatures()
91
    {
92
        return count($this->signatures);
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public function toCompactJSON($id)
99
    {
100
        $signature = $this->getSignature($id);
101
102
        Assertion::true(
103
            empty($signature->getHeaders()),
104
            'The signature contains unprotected headers and cannot be converted into compact JSON'
105
        );
106
107
        return sprintf(
108
            '%s.%s.%s',
109
            $signature->getEncodedProtectedHeaders(),
110
            $this->getEncodedPayload(),
111
            Base64Url::encode($signature->getSignature())
112
        );
113
    }
114
115
    /**
116
     * {@inheritdoc}
117
     */
118
    public function toFlattenedJSON($id)
119
    {
120
        $signature = $this->getSignature($id);
121
122
        $data = [];
123
        $values = [
124
            'payload'   => $this->getEncodedPayload(),
125
            'protected' => $signature->getEncodedProtectedHeaders(),
126
            'header'    => $signature->getHeaders(),
127
        ];
128
129
        foreach ($values as $key => $value) {
130
            if (!empty($value)) {
131
                $data[$key] = $value;
132
            }
133
        }
134
        $data['signature'] = Base64Url::encode($signature->getSignature());
135
136
        return json_encode($data);
137
    }
138
139
    /**
140
     * {@inheritdoc}
141
     */
142
    public function toJSON()
143
    {
144
        Assertion::greaterThan($this->countSignatures(), 0, 'No signature.');
145
146
        $data = [];
147
        if (!empty($this->getEncodedPayload())) {
148
            $data['payload'] = $this->getEncodedPayload();
149
        }
150
151
        $data['signatures'] = [];
152
        foreach ($this->getSignatures() as $signature) {
153
            $tmp = ['signature' => Base64Url::encode($signature->getSignature())];
154
            $values = [
155
                'protected' => $signature->getEncodedProtectedHeaders(),
156
                'header'    => $signature->getHeaders(),
157
            ];
158
159
            foreach ($values as $key => $value) {
160
                if (!empty($value)) {
161
                    $tmp[$key] = $value;
162
                }
163
            }
164
            $data['signatures'][] = $tmp;
165
        }
166
167
        return json_encode($data);
168
    }
169
}
170