RangeCast::get()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
nc 2
nop 4
dl 0
loc 9
c 0
b 0
f 0
cc 2
rs 10
1
<?php
2
3
namespace Belamov\PostgresRange\Casts;
4
5
use Belamov\PostgresRange\Ranges\Range;
6
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
7
use Illuminate\Database\Eloquent\Model;
8
9
abstract class RangeCast implements CastsAttributes
10
{
11
    /**
12
     * @param  Model  $model
13
     * @param  string  $key
14
     * @param  Range  $value
15
     * @param  array  $attributes
16
     * @return array
17
     */
18
    public function set($model, $key, $value, $attributes): array
19
    {
20
        return [
21
            $key => $this->serializeRange($value),
22
        ];
23
    }
24
25
    /**
26
     * @param  Range|null  $range
27
     * @return string|null
28
     */
29
    protected function serializeRange(?Range $range): ?string
30
    {
31
        if ($range === null) {
32
            return null;
33
        }
34
35
        return (string) $range;
36
    }
37
38
    /**
39
     * @param  Model  $model
40
     * @param  string  $key
41
     * @param  mixed  $value
42
     * @param  array  $attributes
43
     * @return Range|null
44
     */
45
    public function get($model, $key, $value, $attributes): ?Range
46
    {
47
        $matches = $this->parseStringRange($value);
48
49
        if (empty($matches)) {
50
            return null;
51
        }
52
53
        return $this->getRangeInstance($matches);
54
    }
55
56
    /**
57
     * @param  $value
58
     * @return array
59
     */
60
    protected function parseStringRange($value): array
61
    {
62
        $matches = [];
63
        preg_match('/([\[(])(.*),(.*)([])])/', $value, $matches);
64
65
        return $matches;
66
    }
67
68
    /**
69
     * @param  array  $params
70
     * @return Range
71
     */
72
    abstract protected function getRangeInstance(array $params): Range;
73
}
74