-
-
Notifications
You must be signed in to change notification settings - Fork 32
/
DatabaseEngine.php
439 lines (368 loc) · 13.5 KB
/
DatabaseEngine.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
<?php
declare(strict_types=1);
namespace Brick\Geo\Engine;
use Brick\Geo\Curve;
use Brick\Geo\Exception\GeometryEngineException;
use Brick\Geo\Geometry;
use Brick\Geo\MultiCurve;
use Brick\Geo\MultiSurface;
use Brick\Geo\MultiPolygon;
use Brick\Geo\Point;
use Brick\Geo\Polygon;
use Brick\Geo\Proxy;
use Brick\Geo\Surface;
/**
* Database implementation of the GeometryEngine.
*
* The target database must have support for GIS functions.
*/
abstract class DatabaseEngine implements GeometryEngine
{
private bool $useProxy;
public function __construct(bool $useProxy)
{
$this->useProxy = $useProxy;
}
/**
* Executes a SQL query.
*
* @psalm-param list<GeometryParameter|scalar|null> $parameters
*
* @param string $query The SQL query to execute.
* @param array $parameters The geometry data or scalar values to pass as parameters.
*
* @return array A numeric result array.
*
* @throws GeometryEngineException
*/
abstract protected function executeQuery(string $query, array $parameters) : array;
/**
* Returns the syntax required to perform a ST_GeomFromText(), together with placeholders.
*
* This method may be overridden if necessary.
*/
protected function getGeomFromTextSyntax(): string
{
return 'ST_GeomFromText(?, ?)';
}
/**
* Returns the syntax required to perform a ST_GeomFromWKB(), together with placeholders.
*
* This method may be overridden if necessary.
*/
protected function getGeomFromWKBSyntax(): string
{
return 'ST_GeomFromWKB(?, ?)';
}
/**
* Returns the placeholder syntax for the given parameter.
*
* This method may be overridden to perform explicit type casts if necessary.
*
* @param scalar|null $parameter
*/
protected function getParameterPlaceholder(mixed $parameter): string
{
return '?';
}
/**
* Builds and executes a SQL query for a GIS function.
*
* @psalm-param array<Geometry|scalar|null> $parameters
*
* @param string $function The SQL GIS function to execute.
* @param array $parameters The Geometry objects or scalar values to pass as parameters.
* @param bool $returnsGeometry Whether the GIS function returns a Geometry.
*
* @return array A numeric result array.
*
* @throws GeometryEngineException
*/
private function query(string $function, array $parameters, bool $returnsGeometry) : array
{
$queryParameters = [];
$queryValues = [];
foreach ($parameters as $parameter) {
if ($parameter instanceof Geometry) {
if ($parameter instanceof Proxy\ProxyInterface) {
$sendAsBinary = $parameter->isProxyBinary();
} else {
$sendAsBinary = ! $parameter->isEmpty();
}
$queryParameters[] = $sendAsBinary
? $this->getGeomFromWKBSyntax()
: $this->getGeomFromTextSyntax();
$queryValues[] = new GeometryParameter($parameter, $sendAsBinary);
} else {
$queryParameters[] = $this->getParameterPlaceholder($parameter);
$queryValues[] = $parameter;
}
}
$query = sprintf('SELECT %s(%s)', $function, implode(', ', $queryParameters));
if ($returnsGeometry) {
$query = sprintf('
SELECT
CASE WHEN ST_IsEmpty(g) THEN ST_AsText(g) ELSE NULL END,
CASE WHEN ST_IsEmpty(g) THEN NULL ELSE ST_AsBinary(g) END,
ST_GeometryType(g),
ST_SRID(g)
FROM (%s AS g) AS q
', $query);
}
return $this->executeQuery($query, $queryValues);
}
/**
* Queries a GIS function returning a boolean value.
*
* @psalm-param Geometry|scalar|null ...$parameters
*
* @param string $function The SQL GIS function to execute.
* @param mixed ...$parameters The Geometry objects or scalar values to pass as parameters.
*
* @throws GeometryEngineException
*/
private function queryBoolean(string $function, ...$parameters) : bool
{
[$result] = $this->query($function, $parameters, false);
// SQLite3 returns -1 when calling a boolean GIS function on a NULL result,
// MariaDB returns -1 when an unsupported operation is performed on a Z/M geometry.
if ($result === null || $result === -1 || $result === '-1') {
throw GeometryEngineException::operationYieldedNoResult();
}
return (bool) $result;
}
/**
* Queries a GIS function returning a floating point value.
*
* @psalm-param Geometry|scalar|null ...$parameters
*
* @param string $function The SQL GIS function to execute.
* @param mixed ...$parameters The Geometry objects or scalar values to pass as parameters.
*
* @throws GeometryEngineException
*/
private function queryFloat(string $function, ...$parameters) : float
{
[$result] = $this->query($function, $parameters, false);
if ($result === null) {
throw GeometryEngineException::operationYieldedNoResult();
}
return (float) $result;
}
/**
* Queries a GIS function returning a Geometry object.
*
* @psalm-param Geometry|scalar|null ...$parameters
*
* @param string $function The SQL GIS function to execute.
* @param mixed ...$parameters The Geometry objects or scalar values to pass as parameters.
*
* @throws GeometryEngineException
*/
private function queryGeometry(string $function, ...$parameters) : Geometry
{
/** @var array{string|null, string|resource|null, string, int|numeric-string} $result */
$result = $this->query($function, $parameters, true);
[$wkt, $wkb, $geometryType, $srid] = $result;
$srid = (int) $srid;
if ($wkt !== null) {
if ($this->useProxy) {
$proxyClassName = $this->getProxyClassName($geometryType);
return new $proxyClassName($wkt, false, $srid);
}
return Geometry::fromText($wkt, $srid);
}
if ($wkb !== null) {
if (is_resource($wkb)) {
$wkb = stream_get_contents($wkb);
}
if ($this->useProxy) {
$proxyClassName = $this->getProxyClassName($geometryType);
return new $proxyClassName($wkb, true, $srid);
}
return Geometry::fromBinary($wkb, $srid);
}
throw GeometryEngineException::operationYieldedNoResult();
}
/**
* @psalm-return class-string<Proxy\ProxyInterface&Geometry>
*
* @throws GeometryEngineException
*/
private function getProxyClassName(string $geometryType) : string
{
$proxyClasses = [
'CIRCULARSTRING' => Proxy\CircularStringProxy::class,
'COMPOUNDCURVE' => Proxy\CompoundCurveProxy::class,
'CURVE' => Proxy\CurveProxy::class,
'CURVEPOLYGON' => Proxy\CurvePolygonProxy::class,
'GEOMCOLLECTION' => Proxy\GeometryCollectionProxy::class, /* MySQL 8 - https://github.com/brick/geo/pull/33 */
'GEOMETRY' => Proxy\GeometryProxy::class,
'GEOMETRYCOLLECTION' => Proxy\GeometryCollectionProxy::class,
'LINESTRING' => Proxy\LineStringProxy::class,
'MULTICURVE' => Proxy\MultiCurveProxy::class,
'MULTILINESTRING' => Proxy\MultiLineStringProxy::class,
'MULTIPOINT' => Proxy\MultiPointProxy::class,
'MULTIPOLYGON' => Proxy\MultiPolygonProxy::class,
'MULTISURFACE' => Proxy\MultiSurfaceProxy::class,
'POINT' => Proxy\PointProxy::class,
'POLYGON' => Proxy\PolygonProxy::class,
'POLYHEDRALSURFACE' => Proxy\PolyhedralSurfaceProxy::class,
'SURFACE' => Proxy\SurfaceProxy::class,
'TIN' => Proxy\TINProxy::class,
'TRIANGLE' => Proxy\TriangleProxy::class
];
$geometryType = strtoupper($geometryType);
$geometryType = preg_replace('/^ST_/', '', $geometryType);
$geometryType = preg_replace('/ .*/', '', $geometryType);
if (! isset($proxyClasses[$geometryType])) {
throw new GeometryEngineException('Unknown geometry type: ' . $geometryType);
}
return $proxyClasses[$geometryType];
}
public function contains(Geometry $a, Geometry $b) : bool
{
return $this->queryBoolean('ST_Contains', $a, $b);
}
public function intersects(Geometry $a, Geometry $b) : bool
{
return $this->queryBoolean('ST_Intersects', $a, $b);
}
public function union(Geometry $a, Geometry $b) : Geometry
{
return $this->queryGeometry('ST_Union', $a, $b);
}
public function intersection(Geometry $a, Geometry $b) : Geometry
{
return $this->queryGeometry('ST_Intersection', $a, $b);
}
public function difference(Geometry $a, Geometry $b) : Geometry
{
return $this->queryGeometry('ST_Difference', $a, $b);
}
public function envelope(Geometry $g) : Geometry
{
return $this->queryGeometry('ST_Envelope', $g);
}
/**
* @psalm-suppress LessSpecificReturnStatement
* @psalm-suppress MoreSpecificReturnType
*/
public function centroid(Geometry $g) : Point
{
return $this->queryGeometry('ST_Centroid', $g);
}
public function pointOnSurface(Surface|MultiSurface $g) : Geometry
{
return $this->queryGeometry('ST_PointOnSurface', $g);
}
public function length(Curve|MultiCurve $g) : float
{
return $this->queryFloat('ST_Length', $g);
}
public function area(Surface|MultiSurface $g) : float
{
return $this->queryFloat('ST_Area', $g);
}
public function azimuth(Point $observer, Point $subject) : float
{
return $this->queryFloat('ST_Azimuth', $observer, $subject);
}
public function boundary(Geometry $g) : Geometry
{
return $this->queryGeometry('ST_Boundary', $g);
}
public function isValid(Geometry $g) : bool
{
return $this->queryBoolean('ST_IsValid', $g);
}
public function isClosed(Geometry $g) : bool
{
return $this->queryBoolean('ST_IsClosed', $g);
}
public function isSimple(Geometry $g) : bool
{
return $this->queryBoolean('ST_IsSimple', $g);
}
public function isRing(Curve $curve) : bool
{
try {
return $this->queryBoolean('ST_IsRing', $curve);
} catch (GeometryEngineException $e) {
// Not all RDBMS (hello, MySQL) support ST_IsRing(), but we have an easy fallback
return $this->isClosed($curve) && $this->isSimple($curve);
}
}
public function equals(Geometry $a, Geometry $b) : bool
{
return $this->queryBoolean('ST_Equals', $a, $b);
}
public function disjoint(Geometry $a, Geometry $b) : bool
{
return $this->queryBoolean('ST_Disjoint', $a, $b);
}
public function touches(Geometry $a, Geometry $b) : bool
{
return $this->queryBoolean('ST_Touches', $a, $b);
}
public function crosses(Geometry $a, Geometry $b) : bool
{
return $this->queryBoolean('ST_Crosses', $a, $b);
}
public function within(Geometry $a, Geometry $b) : bool
{
return $this->queryBoolean('ST_Within', $a, $b);
}
public function overlaps(Geometry $a, Geometry $b) : bool
{
return $this->queryBoolean('ST_Overlaps', $a, $b);
}
public function relate(Geometry $a, Geometry $b, string $matrix) : bool
{
return $this->queryBoolean('ST_Relate', $a, $b, $matrix);
}
public function locateAlong(Geometry $g, float $mValue) : Geometry
{
return $this->queryGeometry('ST_LocateAlong', $g, $mValue);
}
public function locateBetween(Geometry $g, float $mStart, float $mEnd) : Geometry
{
return $this->queryGeometry('ST_LocateBetween', $g, $mStart, $mEnd);
}
public function distance(Geometry $a, Geometry $b) : float
{
return $this->queryFloat('ST_Distance', $a, $b);
}
public function buffer(Geometry $g, float $distance) : Geometry
{
return $this->queryGeometry('ST_Buffer', $g, $distance);
}
public function convexHull(Geometry $g) : Geometry
{
return $this->queryGeometry('ST_ConvexHull', $g);
}
public function symDifference(Geometry $a, Geometry $b) : Geometry
{
return $this->queryGeometry('ST_SymDifference', $a, $b);
}
public function snapToGrid(Geometry $g, float $size) : Geometry
{
return $this->queryGeometry('ST_SnapToGrid', $g, $size);
}
public function simplify(Geometry $g, float $tolerance) : Geometry
{
return $this->queryGeometry('ST_Simplify', $g, $tolerance);
}
public function maxDistance(Geometry $a, Geometry $b) : float
{
return $this->queryFloat('ST_MaxDistance', $a, $b);
}
public function boundingPolygons(Polygon $p) : MultiPolygon
{
throw GeometryEngineException::unimplementedMethod(__METHOD__);
}
public function transform(Geometry $g, int $srid) : Geometry
{
return $this->queryGeometry('ST_Transform', $g, $srid);
}
}