Skip to content

Commit

Permalink
Adjust GeometryCast regex to support geometry expression without SRID
Browse files Browse the repository at this point in the history
  • Loading branch information
nickknissen committed Jul 30, 2024
1 parent bb836ba commit 0b8bdc5
Showing 1 changed file with 8 additions and 16 deletions.
24 changes: 8 additions & 16 deletions src/GeometryCast.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,9 @@ public function get($model, string $key, $value, array $attributes): ?Geometry
}

if ($value instanceof ExpressionContract) {
$wkt = $this->extractWktFromExpression($value, $model->getConnection());
$srid = $this->extractSridFromExpression($value, $model->getConnection());
$expressionValues = $this->extractFromExpression($value, $model->getConnection());

return $this->className::fromWkt($wkt, $srid);
return $this->className::fromWkt($expressionValues['wkt'], $expressionValues['srid']);
}

return $this->className::fromWkb($value);
Expand Down Expand Up @@ -76,23 +75,16 @@ public function set($model, string $key, $value, array $attributes): ?Expression
return $value->toSqlExpression($model->getConnection());
}

private function extractWktFromExpression(ExpressionContract $expression, Connection $connection): string
{
$grammar = $connection->getQueryGrammar();
$expressionValue = $expression->getValue($grammar);

preg_match('/ST_GeomFromText\(\'(.+)\', .+(, .+)?\)/', (string) $expressionValue, $match);

return $match[1];
}

private function extractSridFromExpression(ExpressionContract $expression, Connection $connection): int
/**
* @return array{wkt: string, srid: int}
*/
private function extractFromExpression(ExpressionContract $expression, Connection $connection): array
{
$grammar = $connection->getQueryGrammar();
$expressionValue = $expression->getValue($grammar);

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

return (int) $match[1];
return ['wkt' => $matches[1], 'srid' => (int) ($matches[2] ?? 0)];
}
}

0 comments on commit 0b8bdc5

Please sign in to comment.