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

AESEncryptedCollection   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 3

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 3
dl 0
loc 48
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 8 2
A set() 0 18 4
1
<?php
2
3
namespace RichardStyles\EloquentAES\Casts;
4
5
use Illuminate\Database\Eloquent\JsonEncodingException;
6
use Illuminate\Support\Collection;
7
8
class AESEncryptedCollection extends AESEncrypted
9
{
10
    /**
11
     * Cast the given value and decrypt
12
     *
13
     * @param  \Illuminate\Database\Eloquent\Model  $model
14
     * @param  string  $key
15
     * @param  mixed  $value
16
     * @param  array  $attributes
17
     * @return array
18
     */
19
    public function get($model, $key, $value, $attributes)
20
    {
21
        if (is_null($value)) {
22
            return null;
23
        }
24
25
        return new Collection(json_decode(parent::get($model, $key, $value, $attributes)));
26
    }
27
28
    /**
29
     * Prepare the given value for storage.
30
     *
31
     * @param  \Illuminate\Database\Eloquent\Model  $model
32
     * @param  string  $key
33
     * @param  mixed  $value
34
     * @param  array  $attributes
35
     * @return string
36
     */
37
    public function set($model, $key, $value, $attributes)
38
    {
39
        if (is_null($value)) {
40
            return null;
41
        }
42
43
        if ($value instanceof Collection) {
44
            $value = $value->toJson();
45
        } else {
46
            $value = json_encode($value);
47
48
            if ($value === false) {
49
                throw JsonEncodingException::forAttribute($this, $key, json_last_error_msg());
50
            }
51
        }
52
53
        return parent::set($model, $key, $value, $attributes);
54
    }
55
}
56