Skip to content

Commit 9d41384

Browse files
committed
Fix SRID and options not being optional for expression in GeometryCast
1 parent a6bae05 commit 9d41384

File tree

2 files changed

+24
-15
lines changed

2 files changed

+24
-15
lines changed

src/GeometryCast.php

+7-15
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,7 @@ public function get($model, string $key, $value, array $attributes): ?Geometry
3636
}
3737

3838
if ($value instanceof ExpressionContract) {
39-
$wkt = $this->extractWktFromExpression($value, $model->getConnection());
40-
$srid = $this->extractSridFromExpression($value, $model->getConnection());
39+
[$wkt, $srid, $options] = $this->extractFromExpression($value, $model->getConnection());
4140

4241
return $this->className::fromWkt($wkt, $srid);
4342
}
@@ -76,23 +75,16 @@ public function set($model, string $key, $value, array $attributes): ?Expression
7675
return $value->toSqlExpression($model->getConnection());
7776
}
7877

79-
private function extractWktFromExpression(ExpressionContract $expression, Connection $connection): string
80-
{
81-
$grammar = $connection->getQueryGrammar();
82-
$expressionValue = $expression->getValue($grammar);
83-
84-
preg_match('/ST_GeomFromText\(\'(.+)\', .+(, .+)?\)/', (string) $expressionValue, $match);
85-
86-
return $match[1];
87-
}
88-
89-
private function extractSridFromExpression(ExpressionContract $expression, Connection $connection): int
78+
/**
79+
* @return array{string, int, string}
80+
*/
81+
private function extractFromExpression(ExpressionContract $expression, Connection $connection): array
9082
{
9183
$grammar = $connection->getQueryGrammar();
9284
$expressionValue = $expression->getValue($grammar);
9385

94-
preg_match('/ST_GeomFromText\(\'.+\', (.+)(, .+)?\)/', (string) $expressionValue, $match);
86+
preg_match("/ST_GeomFromText\(\s*'([^']+)'\s*(?:,\s*(\d+))?\s*(?:,\s*'([^']+)')?\s*\)/", (string) $expressionValue, $matches);
9587

96-
return (int) $match[1];
88+
return [$matches[1], (int) ($matches[2] ?? 0), $matches[3] ?? ''];
9789
}
9890
}

tests/GeometryCastTest.php

+17
Original file line numberDiff line numberDiff line change
@@ -189,3 +189,20 @@
189189

190190
expect($testPlace->isDirty())->toBeFalse();
191191
});
192+
193+
it('handles multiple types of expression string', function (
194+
string $expression,
195+
float $latitude,
196+
float $longitude
197+
): void {
198+
$testPlace = TestPlace::factory()
199+
->create(['point' => DB::raw($expression)])
200+
->refresh();
201+
202+
expect($testPlace->point->latitude)->toEqual($latitude);
203+
expect($testPlace->point->longitude)->toEqual($longitude);
204+
})->with([
205+
["ST_GeomFromText('POINT(51.208773 3.272677)')", 3.272677, 51.208773],
206+
["ST_GeomFromText('POINT(51.208773 3.272677)', 4326)", 51.208773, 3.272677],
207+
["ST_GeomFromText('POINT(51.208773 3.272677)', 4326, 'axis-order=srid-defined')", 51.208773, 3.272677],
208+
]);

0 commit comments

Comments
 (0)