PemPublicKeySerializer   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Importance

Changes 4
Bugs 1 Features 0
Metric Value
eloc 12
c 4
b 1
f 0
dl 0
loc 43
rs 10
wmc 3

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A parse() 0 8 1
A serialize() 0 9 1
1
<?php
2
declare(strict_types=1);
3
4
namespace Mdanter\Ecc\Serializer\PublicKey;
5
6
use Mdanter\Ecc\Crypto\Key\PublicKeyInterface;
7
8
/**
9
 *
10
 * @link https://tools.ietf.org/html/rfc5480#page-3
11
 */
12
class PemPublicKeySerializer implements PublicKeySerializerInterface
13
{
14
15
    /**
16
     * @var DerPublicKeySerializer
17
     */
18
    private $derSerializer;
19
20
    /**
21
     * @param DerPublicKeySerializer $serializer
22
     */
23
    public function __construct(DerPublicKeySerializer $serializer)
24
    {
25
        $this->derSerializer = $serializer;
26
    }
27
28
    /**
29
     * {@inheritDoc}
30
     * @see \Mdanter\Ecc\Serializer\PublicKey\PublicKeySerializerInterface::serialize()
31
     */
32
    public function serialize(PublicKeyInterface $key): string
33
    {
34
        $publicKeyInfo = $this->derSerializer->serialize($key);
35
36
        $content  = '-----BEGIN PUBLIC KEY-----'.PHP_EOL;
37
        $content .= trim(chunk_split(base64_encode($publicKeyInfo), 64, PHP_EOL)).PHP_EOL;
38
        $content .= '-----END PUBLIC KEY-----';
39
40
        return $content;
41
    }
42
43
    /**
44
     * {@inheritDoc}
45
     * @see \Mdanter\Ecc\Serializer\PublicKey\PublicKeySerializerInterface::parse()
46
     */
47
    public function parse(string $formattedKey): PublicKeyInterface
48
    {
49
        $formattedKey = str_replace('-----BEGIN PUBLIC KEY-----', '', $formattedKey);
50
        $formattedKey = str_replace('-----END PUBLIC KEY-----', '', $formattedKey);
51
        
52
        $data = base64_decode($formattedKey);
53
54
        return $this->derSerializer->parse($data);
55
    }
56
}
57