• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

brick / geo / 13700983528

06 Mar 2025 02:28PM UTC coverage: 48.121% (+0.6%) from 47.546%
13700983528

Pull #55

github

web-flow
Merge 41526e1ed into 723c55ddf
Pull Request #55: Add LineInterpolatePoint for Postgis

15 of 21 new or added lines in 3 files covered. (71.43%)

54 existing lines in 10 files now uncovered.

1652 of 3433 relevant lines covered (48.12%)

967.63 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.83
/src/Engine/DatabaseEngine.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Brick\Geo\Engine;
6

7
use Brick\Geo\Curve;
8
use Brick\Geo\Exception\GeometryEngineException;
9
use Brick\Geo\Geometry;
10
use Brick\Geo\LineString;
11
use Brick\Geo\MultiCurve;
12
use Brick\Geo\MultiPoint;
13
use Brick\Geo\MultiSurface;
14
use Brick\Geo\MultiPolygon;
15
use Brick\Geo\Point;
16
use Brick\Geo\Polygon;
17
use Brick\Geo\Proxy;
18
use Brick\Geo\Proxy\ProxyInterface;
19
use Brick\Geo\Surface;
20

21
/**
22
 * Database implementation of the GeometryEngine.
23
 *
24
 * The target database must have support for GIS functions.
25
 */
26
abstract class DatabaseEngine implements GeometryEngine
27
{
28
    private readonly bool $useProxy;
29

30
    public function __construct(bool $useProxy)
31
    {
32
        $this->useProxy = $useProxy;
×
33
    }
34

35
    /**
36
     * Executes a SQL query.
37
     *
38
     * @psalm-param list<GeometryParameter|string|float|int> $parameters
39
     * @psalm-return list<mixed>
40
     *
41
     * @param string $query      The SQL query to execute.
42
     * @param array  $parameters The geometry data or scalar values to pass as parameters.
43
     *
44
     * @return array A numeric result array.
45
     *
46
     * @throws GeometryEngineException
47
     */
48
    abstract protected function executeQuery(string $query, array $parameters) : array;
49

50
    /**
51
     * Returns the syntax required to perform a ST_GeomFromText(), together with placeholders.
52
     *
53
     * This method may be overridden if necessary.
54
     */
55
    protected function getGeomFromTextSyntax(): string
56
    {
57
        return 'ST_GeomFromText(?, ?)';
123✔
58
    }
59

60
    /**
61
     * Returns the syntax required to perform a ST_GeomFromWKB(), together with placeholders.
62
     *
63
     * This method may be overridden if necessary.
64
     */
65
    protected function getGeomFromWKBSyntax(): string
66
    {
67
        return 'ST_GeomFromWKB(?, ?)';
421✔
68
    }
69

70
    /**
71
     * Returns the placeholder syntax for the given parameter.
72
     *
73
     * This method may be overridden to perform explicit type casts if necessary.
74
     */
75
    protected function getParameterPlaceholder(string|float|int $parameter): string
76
    {
77
        return '?';
133✔
78
    }
79

80
    /**
81
     * Builds and executes a SQL query for a GIS function.
82
     *
83
     * @psalm-param array<Geometry|string|float|int> $parameters
84
     * @psalm-return list<mixed>
85
     *
86
     * @param string $function        The SQL GIS function to execute.
87
     * @param array  $parameters      The Geometry objects or scalar values to pass as parameters.
88
     * @param bool   $returnsGeometry Whether the GIS function returns a Geometry.
89
     *
90
     * @return array A numeric result array.
91
     *
92
     * @throws GeometryEngineException
93
     */
94
    private function query(string $function, array $parameters, bool $returnsGeometry) : array
95
    {
96
        $queryParameters = [];
1,294✔
97
        $queryValues = [];
1,294✔
98

99
        foreach ($parameters as $parameter) {
1,294✔
100
            if ($parameter instanceof Geometry) {
1,294✔
101
                if ($parameter instanceof Proxy\ProxyInterface) {
1,294✔
102
                    $sendAsBinary = $parameter->isProxyBinary();
93✔
103
                } else {
104
                    $sendAsBinary = ! $parameter->isEmpty();
1,294✔
105
                }
106

107
                $queryParameters[] = $sendAsBinary
1,294✔
108
                    ? $this->getGeomFromWKBSyntax()
1,181✔
109
                    : $this->getGeomFromTextSyntax();
123✔
110

111
                $queryValues[] = new GeometryParameter($parameter, $sendAsBinary);
1,294✔
112
            } else {
113
                $queryParameters[] = $this->getParameterPlaceholder($parameter);
137✔
114
                $queryValues[] = $parameter;
137✔
115
            }
116
        }
117

118
        $query = sprintf('SELECT %s(%s)', $function, implode(', ', $queryParameters));
1,294✔
119

120
        if ($returnsGeometry) {
1,294✔
121
            $query = sprintf('
344✔
122
                SELECT
123
                    CASE WHEN ST_IsEmpty(g) THEN ST_AsText(g) ELSE NULL END,
124
                    CASE WHEN ST_IsEmpty(g) THEN NULL ELSE ST_AsBinary(g) END,
125
                    ST_GeometryType(g),
126
                    ST_SRID(g)
127
                FROM (%s AS g) AS q
128
            ', $query);
344✔
129
        }
130

131
        return $this->executeQuery($query, $queryValues);
1,294✔
132
    }
133

134
    /**
135
     * Queries a GIS function returning a boolean value.
136
     *
137
     * @param string                       $function   The SQL GIS function to execute.
138
     * @param Geometry|string|float|int ...$parameters The Geometry objects or scalar values to pass as parameters.
139
     *
140
     * @throws GeometryEngineException
141
     */
142
    private function queryBoolean(string $function, Geometry|string|float|int ...$parameters) : bool
143
    {
144
        [$result] = $this->query($function, $parameters, false);
848✔
145

146
        // SQLite3 returns -1 when calling a boolean GIS function on a NULL result,
147
        // MariaDB returns -1 when an unsupported operation is performed on a Z/M geometry.
148
        if ($result === null || $result === -1 || $result === '-1') {
732✔
149
            throw GeometryEngineException::operationYieldedNoResult();
96✔
150
        }
151

152
        return (bool) $result;
636✔
153
    }
154

155
    /**
156
     * Queries a GIS function returning a floating point value.
157
     *
158
     * @param string                       $function   The SQL GIS function to execute.
159
     * @param Geometry|string|float|int ...$parameters The Geometry objects or scalar values to pass as parameters.
160
     *
161
     * @throws GeometryEngineException
162
     */
163
    private function queryFloat(string $function, Geometry|string|float|int ...$parameters) : float
164
    {
165
        [$result] = $this->query($function, $parameters, false);
221✔
166

167
        if ($result === null) {
191✔
168
            throw GeometryEngineException::operationYieldedNoResult();
27✔
169
        }
170

171
        return (float) $result;
164✔
172
    }
173

174
    /**
175
     * Queries a GIS function returning a Geometry object.
176
     *
177
     * @param string                       $function   The SQL GIS function to execute.
178
     * @param Geometry|string|float|int ...$parameters The Geometry objects or scalar values to pass as parameters.
179
     *
180
     * @throws GeometryEngineException
181
     */
182
    protected function queryGeometry(string $function, Geometry|string|float|int ...$parameters) : Geometry
183
    {
184
        /** @var array{string|null, string|resource|null, string, int|numeric-string} $result */
185
        $result = $this->query($function, $parameters, true);
344✔
186

187
        [$wkt, $wkb, $geometryType, $srid] = $result;
276✔
188

189
        $srid = (int) $srid;
276✔
190

191
        if ($wkt !== null) {
276✔
192
            if ($this->useProxy) {
6✔
193
                $proxyClassName = $this->getProxyClassName($geometryType);
6✔
194

195
                return new $proxyClassName($wkt, false, $srid);
6✔
196
            }
197

198
            return Geometry::fromText($wkt, $srid);
×
199
        }
200

201
        if ($wkb !== null) {
270✔
202
            if (is_resource($wkb)) {
256✔
203
                $wkb = stream_get_contents($wkb);
67✔
204
            }
205

206
            if ($this->useProxy) {
256✔
207
                $proxyClassName = $this->getProxyClassName($geometryType);
256✔
208

209
                return new $proxyClassName($wkb, true, $srid);
256✔
210
            }
211

212
            return Geometry::fromBinary($wkb, $srid);
×
213
        }
214

215
        throw GeometryEngineException::operationYieldedNoResult();
14✔
216
    }
217

218
    /**
219
     * @psalm-return class-string<Proxy\ProxyInterface&Geometry>
220
     *
221
     * @throws GeometryEngineException
222
     */
223
    private function getProxyClassName(string $geometryType) : string
224
    {
225
        $proxyClasses = [
262✔
226
            'CIRCULARSTRING'     => Proxy\CircularStringProxy::class,
262✔
227
            'COMPOUNDCURVE'      => Proxy\CompoundCurveProxy::class,
262✔
228
            'CURVE'              => Proxy\CurveProxy::class,
262✔
229
            'CURVEPOLYGON'       => Proxy\CurvePolygonProxy::class,
262✔
230
            'GEOMCOLLECTION'     => Proxy\GeometryCollectionProxy::class, /* MySQL 8 - https://github.com/brick/geo/pull/33 */
262✔
231
            'GEOMETRY'           => Proxy\GeometryProxy::class,
262✔
232
            'GEOMETRYCOLLECTION' => Proxy\GeometryCollectionProxy::class,
262✔
233
            'LINESTRING'         => Proxy\LineStringProxy::class,
262✔
234
            'MULTICURVE'         => Proxy\MultiCurveProxy::class,
262✔
235
            'MULTILINESTRING'    => Proxy\MultiLineStringProxy::class,
262✔
236
            'MULTIPOINT'         => Proxy\MultiPointProxy::class,
262✔
237
            'MULTIPOLYGON'       => Proxy\MultiPolygonProxy::class,
262✔
238
            'MULTISURFACE'       => Proxy\MultiSurfaceProxy::class,
262✔
239
            'POINT'              => Proxy\PointProxy::class,
262✔
240
            'POLYGON'            => Proxy\PolygonProxy::class,
262✔
241
            'POLYHEDRALSURFACE'  => Proxy\PolyhedralSurfaceProxy::class,
262✔
242
            'SURFACE'            => Proxy\SurfaceProxy::class,
262✔
243
            'TIN'                => Proxy\TINProxy::class,
262✔
244
            'TRIANGLE'           => Proxy\TriangleProxy::class
262✔
245
        ];
262✔
246

247
        $geometryType = strtoupper($geometryType);
262✔
248
        $geometryType = preg_replace('/^ST_/', '', $geometryType);
262✔
249
        $geometryType = preg_replace('/ .*/', '', $geometryType);
262✔
250

251
        if (! isset($proxyClasses[$geometryType])) {
262✔
252
            throw new GeometryEngineException('Unknown geometry type: ' . $geometryType);
×
253
        }
254

255
        return $proxyClasses[$geometryType];
262✔
256
    }
257

258
    public function contains(Geometry $a, Geometry $b) : bool
259
    {
260
        return $this->queryBoolean('ST_Contains', $a, $b);
76✔
261
    }
262

263
    public function intersects(Geometry $a, Geometry $b) : bool
264
    {
265
        return $this->queryBoolean('ST_Intersects', $a, $b);
36✔
266
    }
267

268
    public function union(Geometry $a, Geometry $b) : Geometry
269
    {
270
        return $this->queryGeometry('ST_Union', $a, $b);
22✔
271
    }
272

273
    public function intersection(Geometry $a, Geometry $b) : Geometry
274
    {
275
        return $this->queryGeometry('ST_Intersection', $a, $b);
12✔
276
    }
277

278
    public function difference(Geometry $a, Geometry $b) : Geometry
279
    {
280
        return $this->queryGeometry('ST_Difference', $a, $b);
12✔
281
    }
282

283
    public function envelope(Geometry $g) : Geometry
284
    {
285
        return $this->queryGeometry('ST_Envelope', $g);
18✔
286
    }
287

288
    public function centroid(Geometry $g) : Point
289
    {
290
        /** @var Point */
291
        return $this->queryGeometry('ST_Centroid', $g);
45✔
292
    }
293

294
    public function pointOnSurface(Surface|MultiSurface $g) : Point
295
    {
296
        /** @var Point */
297
        return $this->queryGeometry('ST_PointOnSurface', $g);
42✔
298
    }
299

300
    public function length(Curve|MultiCurve $g) : float
301
    {
302
        return $this->queryFloat('ST_Length', $g);
95✔
303
    }
304

305
    public function area(Surface|MultiSurface $g) : float
306
    {
307
        return $this->queryFloat('ST_Area', $g);
66✔
308
    }
309

310
    public function azimuth(Point $observer, Point $subject) : float
311
    {
312
        return $this->queryFloat('ST_Azimuth', $observer, $subject);
12✔
313
    }
314

315
    public function boundary(Geometry $g) : Geometry
316
    {
317
        return $this->queryGeometry('ST_Boundary', $g);
36✔
318
    }
319

320
    public function isValid(Geometry $g) : bool
321
    {
322
        return $this->queryBoolean('ST_IsValid', $g);
46✔
323
    }
324

325
    public function isClosed(Geometry $g) : bool
326
    {
327
        return $this->queryBoolean('ST_IsClosed', $g);
276✔
328
    }
329

330
    public function isSimple(Geometry $g) : bool
331
    {
332
        return $this->queryBoolean('ST_IsSimple', $g);
102✔
333
    }
334

335
    public function isRing(Curve $curve) : bool
336
    {
337
        try {
338
            return $this->queryBoolean('ST_IsRing', $curve);
58✔
339
        } catch (GeometryEngineException) {
10✔
340
            // Not all RDBMS (hello, MySQL) support ST_IsRing(), but we have an easy fallback
341
            return $this->isClosed($curve) && $this->isSimple($curve);
10✔
342
        }
343
    }
344

345
    public function makeValid(Geometry $g) : Geometry
346
    {
347
        return $this->queryGeometry('ST_MakeValid', $g);
12✔
348
    }
349

350
    public function equals(Geometry $a, Geometry $b) : bool
351
    {
352
        return $this->queryBoolean('ST_Equals', $a, $b);
122✔
353
    }
354

355
    public function disjoint(Geometry $a, Geometry $b) : bool
356
    {
357
        return $this->queryBoolean('ST_Disjoint', $a, $b);
36✔
358
    }
359

360
    public function touches(Geometry $a, Geometry $b) : bool
361
    {
362
        return $this->queryBoolean('ST_Touches', $a, $b);
48✔
363
    }
364

365
    public function crosses(Geometry $a, Geometry $b) : bool
366
    {
367
        return $this->queryBoolean('ST_Crosses', $a, $b);
48✔
368
    }
369

370
    public function within(Geometry $a, Geometry $b) : bool
371
    {
372
        return $this->queryBoolean('ST_Within', $a, $b);
30✔
373
    }
374

375
    public function overlaps(Geometry $a, Geometry $b) : bool
376
    {
377
        return $this->queryBoolean('ST_Overlaps', $a, $b);
12✔
378
    }
379

380
    public function relate(Geometry $a, Geometry $b, string $matrix) : bool
381
    {
382
        return $this->queryBoolean('ST_Relate', $a, $b, $matrix);
24✔
383
    }
384

385
    public function locateAlong(Geometry $g, float $mValue) : Geometry
386
    {
387
        return $this->queryGeometry('ST_LocateAlong', $g, $mValue);
12✔
388
    }
389

390
    public function locateBetween(Geometry $g, float $mStart, float $mEnd) : Geometry
391
    {
392
        return $this->queryGeometry('ST_LocateBetween', $g, $mStart, $mEnd);
12✔
393
    }
394

395
    public function distance(Geometry $a, Geometry $b) : float
396
    {
397
        return $this->queryFloat('ST_Distance', $a, $b);
30✔
398
    }
399

400
    public function buffer(Geometry $g, float $distance) : Geometry
401
    {
402
        return $this->queryGeometry('ST_Buffer', $g, $distance);
18✔
403
    }
404

405
    public function convexHull(Geometry $g) : Geometry
406
    {
407
        return $this->queryGeometry('ST_ConvexHull', $g);
18✔
408
    }
409

410
    public function symDifference(Geometry $a, Geometry $b) : Geometry
411
    {
412
        return $this->queryGeometry('ST_SymDifference', $a, $b);
6✔
413
    }
414

415
    public function snapToGrid(Geometry $g, float $size) : Geometry
416
    {
417
        return $this->queryGeometry('ST_SnapToGrid', $g, $size);
24✔
418
    }
419

420
    public function simplify(Geometry $g, float $tolerance) : Geometry
421
    {
422
        return $this->queryGeometry('ST_Simplify', $g, $tolerance);
12✔
423
    }
424

425
    public function maxDistance(Geometry $a, Geometry $b) : float
426
    {
427
        return $this->queryFloat('ST_MaxDistance', $a, $b);
18✔
428
    }
429

430
    public function transform(Geometry $g, int $srid) : Geometry
431
    {
432
        return $this->queryGeometry('ST_Transform', $g, $srid);
4✔
433
    }
434

435
    public function split(Geometry $g, Geometry $blade) : Geometry
436
    {
437
        return $this->queryGeometry('ST_Split', $g, $blade);
8✔
438
    }
439

440
    /**
441
     * @throws GeometryEngineException
442
     */
443
    public function lineInterpolatePoint(LineString $linestring, float $fraction) : Point
444
    {
445
        $result = $this->queryGeometry('ST_LineInterpolatePoint', $linestring, $fraction);
12✔
446
        if (! $result instanceof Point) {
12✔
NEW
447
            throw new GeometryEngineException('This operation yielded wrong type: ' . $result::class);
×
448
        }
449

450
        return $result;
12✔
451
    }
452

453
    public function lineInterpolatePoints(LineString $linestring, float $fraction) : MultiPoint
454
    {
455
        $result = $this->queryGeometry('ST_LineInterpolatePoints', $linestring, $fraction);
15✔
456

457
        if ($result instanceof MultiPoint) {
13✔
458
            return $result;
10✔
459
        }
460

461
        if ($result->isEmpty()) {
3✔
462
            return new MultiPoint($result->coordinateSystem());
1✔
463
        }
464

465
        return MultiPoint::of($result);
2✔
466
    }
467
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc