Passed
Push — master ( 21ea66...db5c4e )
by Kirill
02:53
created

EncrypterFactory   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
eloc 14
c 1
b 0
f 0
dl 0
loc 54
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A createInjection() 0 3 1
A getEncrypter() 0 3 1
A getKey() 0 9 2
A generateKey() 0 6 2
1
<?php
2
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
declare(strict_types=1);
11
12
namespace Spiral\Encrypter;
13
14
use Defuse\Crypto\Exception\CryptoException;
15
use Defuse\Crypto\Key;
16
use Spiral\Core\Container\InjectorInterface;
17
use Spiral\Core\Container\SingletonInterface;
18
use Spiral\Encrypter\Config\EncrypterConfig;
19
use Spiral\Encrypter\Exception\EncrypterException;
20
21
/**
22
 * Only manages encrypter injections (factory).
23
 */
24
final class EncrypterFactory implements InjectorInterface, EncryptionInterface, SingletonInterface
25
{
26
    /** @var EncrypterConfig */
27
    protected $config = null;
28
29
    /**
30
     * @param EncrypterConfig $config
31
     */
32
    public function __construct(EncrypterConfig $config)
33
    {
34
        $this->config = $config;
35
    }
36
37
    /**
38
     * @inheritdoc
39
     * @codeCoverageIgnore
40
     */
41
    public function generateKey(): string
42
    {
43
        try {
44
            return Key::createNewRandomKey()->saveToAsciiSafeString();
45
        } catch (CryptoException $e) {
46
            throw new EncrypterException($e->getMessage(), $e->getCode(), $e);
47
        }
48
    }
49
50
    /**
51
     * @inheritdoc
52
     */
53
    public function getKey(): string
54
    {
55
        try {
56
            Key::loadFromAsciiSafeString($this->config->getKey());
57
        } catch (CryptoException $e) {
58
            throw new EncrypterException($e->getMessage(), $e->getCode(), $e);
59
        }
60
61
        return $this->config->getKey();
62
    }
63
64
    /**
65
     * @return EncrypterInterface
66
     */
67
    public function getEncrypter(): EncrypterInterface
68
    {
69
        return new Encrypter($this->getKey());
70
    }
71
72
    /**
73
     * {@inheritdoc}
74
     */
75
    public function createInjection(\ReflectionClass $class, string $context = null)
76
    {
77
        return $this->getEncrypter();
78
    }
79
}
80