77use Illuminate \Contracts \Database \Eloquent \CastsAttributes ;
88use Illuminate \Database \Eloquent \Model ;
99use Illuminate \Database \Query \Expression ;
10+ use Illuminate \Support \Facades \DB ;
1011use InvalidArgumentException ;
1112use MatanYadaev \EloquentSpatial \Objects \Geometry ;
1213
@@ -26,29 +27,35 @@ public function __construct(string $className)
2627 /**
2728 * @param Model $model
2829 * @param string $key
29- * @param string|null $wkb
30+ * @param string|Expression| null $wkbOrWKt
3031 * @param array<string, mixed> $attributes
3132 * @return Geometry|null
3233 */
33- public function get ($ model , string $ key , $ wkb , array $ attributes ): ?Geometry
34+ public function get ($ model , string $ key , $ wkbOrWKt , array $ attributes ): ?Geometry
3435 {
35- if (! $ wkb ) {
36+ if (! $ wkbOrWKt ) {
3637 return null ;
3738 }
3839
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 );
4047 }
4148
4249 /**
4350 * @param Model $model
4451 * @param string $key
4552 * @param Geometry|mixed|null $geometry
4653 * @param array<string, mixed> $attributes
47- * @return Expression|string| null
54+ * @return Expression|null
4855 *
4956 * @throws InvalidArgumentException
5057 */
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
5259 {
5360 if (! $ geometry ) {
5461 return null ;
@@ -61,6 +68,15 @@ public function set($model, string $key, $geometry, array $attributes): Expressi
6168 );
6269 }
6370
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 ];
6581 }
6682}
0 commit comments