Completed
Pull Request — master (#3)
by
unknown
01:48
created

AESEncryptedObject::set()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.7998
c 0
b 0
f 0
cc 3
nc 3
nop 4
1
<?php
2
3
namespace RichardStyles\EloquentAES\Casts;
4
5
use Illuminate\Database\Eloquent\JsonEncodingException;
6
7
class AESEncryptedObject extends AESEncrypted
8
{
9
    /**
10
     * Cast the given value and decrypt
11
     *
12
     * @param  \Illuminate\Database\Eloquent\Model  $model
13
     * @param  string  $key
14
     * @param  mixed  $value
15
     * @param  array  $attributes
16
     * @return array
17
     */
18
    public function get($model, $key, $value, $attributes)
19
    {
20
        if (is_null($value)) {
21
            return null;
22
        }
23
24
        $decoded = parent::get($model, $key, $value, $attributes);
25
26
        // The encrypter should already json-decode this, but we’ll handle it too just in case.
27
        if (is_string($decoded)) {
28
            $decoded = json_decode($decoded, false);
29
        }
30
31
        return $decoded;
32
    }
33
34
    /**
35
     * Prepare the given value for storage.
36
     *
37
     * @param  \Illuminate\Database\Eloquent\Model  $model
38
     * @param  string  $key
39
     * @param  mixed  $value
40
     * @param  array  $attributes
41
     * @return string
42
     */
43
    public function set($model, $key, $value, $attributes)
44
    {
45
        if (is_null($value)) {
46
            return null;
47
        }
48
49
        $value = json_encode($value);
50
51
        if ($value === false) {
52
            throw JsonEncodingException::forAttribute($this, $key, json_last_error_msg());
53
        }
54
55
        return parent::set($model, $key, $value, $attributes);
56
    }
57
}
58