7
7
use Illuminate \Contracts \Database \Eloquent \CastsAttributes ;
8
8
use Illuminate \Database \Eloquent \Model ;
9
9
use Illuminate \Database \Query \Expression ;
10
+ use Illuminate \Support \Facades \DB ;
10
11
use InvalidArgumentException ;
11
12
use MatanYadaev \EloquentSpatial \Objects \Geometry ;
12
13
@@ -26,29 +27,35 @@ public function __construct(string $className)
26
27
/**
27
28
* @param Model $model
28
29
* @param string $key
29
- * @param string|null $wkb
30
+ * @param string|Expression| null $wkbOrWKt
30
31
* @param array<string, mixed> $attributes
31
32
* @return Geometry|null
32
33
*/
33
- public function get ($ model , string $ key , $ wkb , array $ attributes ): ?Geometry
34
+ public function get ($ model , string $ key , $ wkbOrWKt , array $ attributes ): ?Geometry
34
35
{
35
- if (! $ wkb ) {
36
+ if (! $ wkbOrWKt ) {
36
37
return null ;
37
38
}
38
39
39
- return $ this ->className ::fromWkb ($ wkb );
40
+ if ($ wkbOrWKt instanceof Expression) {
41
+ $ wkt = $ this ->extractWktFromExpression ($ wkbOrWKt );
42
+
43
+ return $ this ->className ::fromWkt ($ wkt );
44
+ }
45
+
46
+ return $ this ->className ::fromWkb ($ wkbOrWKt );
40
47
}
41
48
42
49
/**
43
50
* @param Model $model
44
51
* @param string $key
45
52
* @param Geometry|mixed|null $geometry
46
53
* @param array<string, mixed> $attributes
47
- * @return Expression|string| null
54
+ * @return Expression|null
48
55
*
49
56
* @throws InvalidArgumentException
50
57
*/
51
- public function set ($ model , string $ key , $ geometry , array $ attributes ): Expression |string | null
58
+ public function set ($ model , string $ key , $ geometry , array $ attributes ): Expression |null
52
59
{
53
60
if (! $ geometry ) {
54
61
return null ;
@@ -61,6 +68,15 @@ public function set($model, string $key, $geometry, array $attributes): Expressi
61
68
);
62
69
}
63
70
64
- return $ geometry ->toWkt ();
71
+ $ wkt = $ geometry ->toWkt (withFunction: true );
72
+
73
+ return DB ::raw ("ST_GeomFromText(' {$ wkt }') " );
74
+ }
75
+
76
+ private function extractWktFromExpression (Expression $ expression ): string
77
+ {
78
+ preg_match ('/ST_GeomFromText\( \'(.+) \'\)/ ' , (string ) $ expression , $ match );
79
+
80
+ return $ match [1 ];
65
81
}
66
82
}
0 commit comments