Completed
Branch 2.x (1d3586)
by Julián
07:39
created

HandlerTrait::encryptSessionData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
1
<?php
2
3
/*
4
 * sessionware (https://github.com/juliangut/sessionware).
5
 * PSR7 session management middleware.
6
 *
7
 * @license BSD-3-Clause
8
 * @link https://github.com/juliangut/sessionware
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
declare(strict_types=1);
13
14
namespace Jgut\Sessionware\Handler;
15
16
use Defuse\Crypto\Core;
17
use Defuse\Crypto\Crypto;
18
use Jgut\Sessionware\Configuration;
19
20
/**
21
 * Session handler utility trait.
22
 */
23
trait HandlerTrait
24
{
25
    /**
26
     * @var Configuration
27
     */
28
    protected $configuration;
29
30
    /**
31
     * Set configuration.
32
     *
33
     * @param Configuration $configuration
34
     *
35
     * @return static
36
     */
37
    public function setConfiguration(Configuration $configuration)
38
    {
39
        $this->configuration = $configuration;
40
41
        return $this;
42
    }
43
44
    /**
45
     * Checks if configuration is set.
46
     *
47
     * @throws \RuntimeException
48
     */
49
    protected function testConfiguration()
50
    {
51
        if ($this->configuration === null) {
52
            throw new \RuntimeException('Configuration must be set prior to use');
53
        }
54
    }
55
56
    /**
57
     * Encrypt session data based on configuration encryption key.
58
     *
59
     * @param string $plainData
60
     *
61
     * @return string
62
     */
63
    protected function encryptSessionData(string $plainData) : string
64
    {
65
        if (!$this->configuration->getEncryptionKey()) {
66
            return $plainData;
67
        }
68
69
        $encryptionKey = str_pad($this->configuration->getEncryptionKey(), 32, '=');
70
71
        return Crypto::encryptWithPassword($plainData, $encryptionKey);
72
    }
73
74
    /**
75
     * Decrypt session data based on configuration encryption key.
76
     *
77
     * @param string $encryptedData
78
     *
79
     * @return string
80
     */
81
    protected function decryptSessionData(string $encryptedData) : string
82
    {
83
        if (!$this->configuration->getEncryptionKey()) {
84
            return $encryptedData;
85
        }
86
87
        $encryptionKey = str_pad($this->configuration->getEncryptionKey(), 32, '=');
88
89
        return Crypto::decryptWithPassword($encryptedData, $encryptionKey);
90
    }
91
}
92