Completed
Push — master ( dd0bc2...b5fd08 )
by Oscar
03:27
created

CryptTrait   C

Complexity

Total Complexity 58

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 58
c 2
b 0
f 0
lcom 1
cbo 0
dl 0
loc 51
rs 6.3006

3 Methods

Rating   Name   Duplication   Size   Complexity  
A key() 0 7 1
A encrypt() 0 8 2
A decrypt() 0 8 2

How to fix   Complexity   

Complex Class

Complex classes like CryptTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use CryptTrait, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace Psr7Middlewares\Utils;
4
5
use RuntimeException;
6
use phpseclib\Crypt\AES;
7
8
/**
9
 * Trait used by all middlewares that needs encrypt/decrypt functions
10
 */
11
trait CryptTrait
12
{
13
    protected $cipher;
14
15
    /**
16
     * Set the key
17
     * 
18
     * @param string $key
19
     *
20
     * @return self
21
     */
22
    public function key($key)
23
    {
24
        $this->cipher = new AES();
25
        $this->cipher->setKey($key);
26
27
        return $this;
28
    }
29
30
    /**
31
     * Encrypt the given value.
32
     *
33
     * @param string $value
34
     * 
35
     * @return string
36
     */
37
    protected function encrypt($value)
38
    {
39
        if ($this->cipher) {
40
            return bin2hex($this->cipher->encrypt($value));
41
        }
42
43
        return $value;
44
    }
45
46
    /**
47
     * Decrypt the given value.
48
     *
49
     * @param string $value
50
     * 
51
     * @return string
52
     */
53
    protected function decrypt($value)
54
    {
55
        if ($this->cipher) {
56
            return $this->cipher->decrypt(hex2bin($value));
57
        }
58
59
        return $value;
60
    }
61
}
62