Failed Conditions
Pull Request — master (#138)
by Florent
16:23 queued 13:38
created

JWKSetPEM::getPEM()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.4285
c 0
b 0
f 0
nc 3
cc 3
eloc 8
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\Object;
13
14
use Jose\KeyConverter\ECKey;
15
use Jose\KeyConverter\RSAKey;
16
17
/**
18
 * Class JWKSetPEM.
19
 */
20
trait JWKSetPEM
21
{
22
    /**
23
     * @return \Jose\Object\JWKInterface[]
24
     */
25
    abstract public function getKeys();
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function toPEM()
31
    {
32
        $keys = $this->getKeys();
33
        $result = [];
34
35
        foreach ($keys as $key) {
36
            if (!in_array($key->get('kty'), ['RSA', 'EC'])) {
37
                continue;
38
            }
39
40
            $pem = $this->getPEM($key);
41
            if ($key->has('kid')) {
42
                $result[$key->get('kid')] = $pem;
43
            } else {
44
                $result[] = $pem;
45
            }
46
        }
47
48
        return $result;
49
    }
50
51
    /**
52
     * @param \Jose\Object\JWKInterface $key
53
     *
54
     * @return string
55
     */
56
    private function getPEM(JWKInterface $key)
57
    {
58
        switch ($key->get('kty')) {
59
            case 'RSA':
60
                return (new RSAKey($key))->toPEM();
61
            case 'EC':
62
                return (new ECKey($key))->toPEM();
63
            default:
64
                throw new \InvalidArgumentException('Unsupported key type.');
65
        }
66
    }
67
}
68