Completed
Push — master ( 4fb1d6...a24b8d )
by Oscar
01:43
created

Point::getFactory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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