LineString::set()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 4
c 2
b 0
f 0
dl 0
loc 7
rs 10
cc 1
nc 1
nop 4
1
<?php
2
namespace SimpleCMS\Region\Casts;
3
4
use Illuminate\Support\Arr;
5
use Illuminate\Support\Facades\DB;
6
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
7
8
class LineString implements CastsAttributes
9
{
10
    /**
11
     * Summary of select
12
     * @param mixed $field
13
     * @return string
14
     */
15
    public static function select($field): string
16
    {
17
        return "ST_AsText($field) as $field";
18
    }
19
20
    /**
21
     * Transform the attribute from the underlying model values.
22
     * 
23
     * @param  \Illuminate\Database\Eloquent\Model  $model
24
     * @param  string  $key
25
     * @param  mixed  $value
26
     * @param  array<string, mixed>  $attributes
27
     * @return mixed
28
     */
29
    public function get($model, $key, $value, $attributes)
30
    {
31
        if (empty($value)) {
32
            return null;
33
        }
34
        if (!is_string($value) || !mb_check_encoding($value, 'UTF-8')) {
35
            $tableName = $model->getTable();
36
            $keyName = $model->getKeyName();
37
            $keyValue = $model->$keyName;
38
            $value = DB::select("SELECT ST_AsText($key) as $key FROM $tableName WHERE $keyName = '$keyValue'")[0]->$key;
39
            if (empty($value)) {
40
                return null;
41
            }
42
        }
43
44
        $pointString = str_replace(['LINESTRING(', ')'], '', $value);
45
46
        $points = explode(',', $pointString);
47
48
        $decoded = array_map(function ($point) {
49
            $_value = array_reverse(explode(' ', trim($point)));
50
            return [(float) $_value[0], (float) $_value[1]];
51
        }, $points);
52
53
        return $decoded;
54
    }
55
56
    /**
57
     * Transform the attribute to its underlying model values.
58
     *
59
     * @param  \Illuminate\Database\Eloquent\Model  $model
60
     * @param  string  $key
61
     * @param  mixed  $value
62
     * @param  array<string, mixed>  $attributes
63
     * @return mixed
64
     */
65
    public function set($model, $key, $value, $attributes)
66
    {
67
        $srid = 4326;
68
        $array = Arr::map($value, function ($rs) {
69
            return Arr::join(array_reverse($rs), ' ');
70
        });
71
        return DB::raw("ST_GeomFromText('LINESTRING(" . Arr::join($array, ',') . ")',$srid)");
72
    }
73
}