Completed
Push — master ( 0da900...d5ed8a )
by Oscar
01:30
created

Point::select()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
declare(strict_types = 1);
3
4
namespace SimpleCrud\Fields;
5
6
use Atlas\Query\Insert;
7
use Atlas\Query\Select;
8
use Atlas\Query\Update;
9
10
final class Point extends Field
11
{
12
    public function select(Select $query)
13
    {
14
        $name = $this->getName();
15
        $query->columns("asText({$this}) as `{$name}`");
16
    }
17
18
    public function format($value): ?array
19
    {
20
        if ($value === null) {
21
            return null;
22
        }
23
24
        //POINT(X Y)
25
        $points = explode(' ', substr((string) $value, 6, -1), 2);
26
27
        return [
28
            floatval($points[0]),
29
            floatval($points[1]),
30
        ];
31
    }
32
33
    public function insert(Insert $query, $value)
34
    {
35
        if (self::isValid($value)) {
36
            $value = sprintf('POINT(%s, %s)', $value[0], $value[1]);
37
        } else {
38
            $value = null;
39
        }
40
41
        $query->set($this->info['name'], $value);
42
    }
43
44
    public function update(Update $query, $value)
45
    {
46
        if (self::isValid($value)) {
47
            $value = sprintf('POINT(%s, %s)', $value[0], $value[1]);
48
        } else {
49
            $value = null;
50
        }
51
52
        $query->set($this->info['name'], $value);
53
    }
54
55
    /**
56
     * Check whether the value is valid before save in the database
57
     * @param mixed $data
58
     */
59
    private static function isValid($data): bool
60
    {
61
        if (!is_array($data)) {
62
            return false;
63
        }
64
65
        if (!isset($data[0]) || !isset($data[1]) || count($data) > 2) {
66
            return false;
67
        }
68
69
        return is_numeric($data[0]) && is_numeric($data[1]);
70
    }
71
}
72