Failed Conditions
Pull Request — master (#138)
by Florent
05:42 queued 02:52
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
 * @package Jose\Object
20
 */
21
trait JWKSetPEM
22
{
23
    /**
24
     * @return \Jose\Object\JWKInterface[]
25
     */
26
    abstract public function getKeys();
27
28
    /**
29
     * {@inheritdoc}
30
     */
31
    public function toPEM()
32
    {
33
        $keys = $this->getKeys();
34
        $result = [];
35
36
        foreach ($keys as $key) {
37
            if (!in_array($key->get('kty'), ['RSA', 'EC'])) {
38
                continue;
39
            }
40
41
            $pem = $this->getPEM($key);
42
            if ($key->has('kid')) {
43
                $result[$key->get('kid')] = $pem;
44
            } else {
45
                $result[] = $pem;
46
            }
47
        }
48
49
        return $result;
50
    }
51
52
    /**
53
     * @param \Jose\Object\JWKInterface $key
54
     *
55
     * @return string
56
     */
57
    private function getPEM(JWKInterface $key)
58
    {
59
        switch ($key->get('kty')) {
60
            case 'RSA':
61
                return (new RSAKey($key))->toPEM();
62
            case 'EC':
63
                return (new ECKey($key))->toPEM();
64
            default:
65
                throw new \InvalidArgumentException('Unsupported key type.');
66
        }
67
    }
68
}
69