Completed
Push — master ( 2f2681...17bcc4 )
by Richard
01:03
created

EncryptedCollection::set()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.7333
c 0
b 0
f 0
cc 3
nc 3
nop 4
1
<?php
2
3
4
namespace RichardStyles\EloquentEncryption\Casts;
5
6
7
use Illuminate\Database\Eloquent\JsonEncodingException;
8
use Illuminate\Support\Collection;
9
use Illuminate\Support\Collection as BaseCollection;
10
11
class EncryptedCollection extends Encrypted
12
{
13
    /**
14
     * Cast the given value and decrypt
15
     *
16
     * @param  \Illuminate\Database\Eloquent\Model  $model
17
     * @param  string  $key
18
     * @param  mixed  $value
19
     * @param  array  $attributes
20
     * @return int
21
     */
22
    public function get($model, $key, $value, $attributes)
23
    {
24
        return new BaseCollection(json_decode(parent::get($model, $key, $value, $attributes)));
25
    }
26
27
    /**
28
     * Prepare the given value for storage.
29
     *
30
     * @param  \Illuminate\Database\Eloquent\Model  $model
31
     * @param  string  $key
32
     * @param  array  $value
33
     * @param  array  $attributes
34
     * @return string
35
     */
36
    public function set($model, $key, $value, $attributes)
37
    {
38
        if($value instanceof Collection){
39
            $value = $value->toJson();
40
        }else {
41
            $value = json_encode($value);
42
43
            if ($value === false) {
44
                throw JsonEncodingException::forAttribute(
45
                    $this, $key, json_last_error_msg()
46
                );
47
            }
48
        }
49
        dd($value);
50
        return parent::set($model, $key, $value, $attributes);
51
    }
52
}
53