Encrypter   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

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

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getPrefix() 0 6 2
A getKey() 0 7 3
A encrypt() 0 3 1
A decrypt() 0 5 1
1
<?php
2
namespace Magros\Encryptable;
3
use Illuminate\Support\Facades\Config;
4
5
class Encrypter
6
{
7
    private $method = 'aes-128-ecb';
8
    private $key;
9
    private $prefix;
10
11
    /**
12
     * @param $value
13
     * @return string
14
     */
15
    public function encrypt($value)
16
    {
17
        return $this->getPrefix() . '_' . openssl_encrypt($value, $this->method, $this->getKey(), 0, $iv = '');
0 ignored issues
show
Bug introduced by
It seems like $this->getKey() can also be of type boolean and null; however, parameter $passphrase of openssl_encrypt() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

17
        return $this->getPrefix() . '_' . openssl_encrypt($value, $this->method, /** @scrutinizer ignore-type */ $this->getKey(), 0, $iv = '');
Loading history...
18
    }
19
20
    /**
21
     * @param $value
22
     * @return string
23
     */
24
    public function decrypt($value)
25
    {
26
        $value = str_replace("{$this->getPrefix()}_",'',$value);
27
28
        return openssl_decrypt($value, $this->method, $this->getKey(), 0, $iv = '');
0 ignored issues
show
Bug introduced by
It seems like $this->getKey() can also be of type boolean and null; however, parameter $passphrase of openssl_decrypt() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

28
        return openssl_decrypt($value, $this->method, /** @scrutinizer ignore-type */ $this->getKey(), 0, $iv = '');
Loading history...
29
    }
30
31
32
    /**
33
     * @return bool|null|string
34
     * @throws \Exception
35
     */
36
    public function getKey()
37
    {
38
        if ($this->key === null) {
39
            if(! Config::get('encrypt.key')) throw new \Exception('The .env value ENCRYPT_KEY has to be set');
40
            $this->key = substr(hash('sha256', Config::get('encrypt.key')), 0, 16);
41
        }
42
        return $this->key;
43
    }
44
45
    /**
46
     * @return mixed
47
     */
48
    public function getPrefix()
49
    {
50
        if(! $this->prefix){
51
            $this->prefix = Config::get('encrypt.prefix');
52
        }
53
        return $this->prefix;
54
    }
55
56
}