Completed
Push — master ( 23403c...97f02e )
by Oscar
02:10
created

Point::isValid()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 8.8571
c 0
b 0
f 0
cc 6
eloc 6
nc 4
nop 1
1
<?php
2
3
namespace SimpleCrud\Fields;
4
5
use SimpleCrud\SimpleCrud;
6
7
/**
8
 * To slugify values before save.
9
 */
10
class Point extends Field
11
{
12
    /**
13
     * {@inheritdoc}
14
     */
15 View Code Duplication
    public function getSelectExpression($as = null)
16
    {
17
        $tableName = $this->table->getName();
18
        $fieldName = $this->name;
19
20
        if ($as) {
21
            return "asText(`{$tableName}`.`{$fieldName}`) as `{$as}`";
22
        }
23
24
        return "asText(`{$tableName}`.`{$fieldName}`) as `{$fieldName}`";
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    public function getValueExpression($mark)
31
    {
32
        return "PointFromText($mark)";
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    public function dataFromDatabase($data)
39
    {
40
        //POINT(X Y)
41
        if ($data !== null) {
42
            $points = explode(' ', substr($data, 6, -1), 2);
43
44
            return [
45
                floatval($points[0]),
46
                floatval($points[1]),
47
            ];
48
        }
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function dataToDatabase($data)
55
    {
56
        if (self::isValid($data)) {
57
            return 'POINT('.implode(' ', $data).')';
58
        }
59
    }
60
61
    /**
62
     * Check whether the value is valid before save in the database
63
     *
64
     * @param mixed $data
65
     *
66
     * @return bool
67
     */
68
    private static function isValid($data)
69
    {
70
        if (!is_array($data)) {
71
            return false;
72
        }
73
74
        if (!isset($data[0]) || !isset($data[1]) || count($data) > 2) {
75
            return false;
76
        }
77
78
        return is_numeric($data[0]) && is_numeric($data[1]);
79
    }
80
}
81