Mula::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Lukeraymonddowning\Mula\Casts;
4
5
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
6
use Lukeraymonddowning\Mula\Facades;
7
8
class Mula implements CastsAttributes
9
{
10
    protected $columns = [];
11
12
    public function __construct(...$columns)
13
    {
14
        $this->columns = $columns;
15
    }
16
17
    public function get($model, string $key, $money, array $attributes)
18
    {
19
        return Facades\Mula::create(...$this->getMonetaryValues($money, $attributes));
20
    }
21
22
    protected function getMonetaryValues($money, $attributes)
23
    {
24
        return $this->expectsCurrencyAndAmountInSameColumn()
25
            ? explode('|', $money, 2)
26
            : [$attributes[$this->columns[0]], $attributes[$this->columns[1]]];
27
    }
28
29
    protected function expectsCurrencyAndAmountInSameColumn()
30
    {
31
        return empty($this->columns);
32
    }
33
34
    public function set($model, string $key, $money, array $attributes)
35
    {
36
        if ($this->expectsCurrencyAndAmountInSameColumn()) {
37
            return "{$money->value()}|{$money->currency()}";
38
        }
39
40
        return [
41
            $this->columns[0] => $money->value(),
42
            $this->columns[1] => $money->currency(),
43
        ];
44
    }
45
}
46