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

brick / geo / 13349921516

16 Feb 2025 12:21AM UTC coverage: 82.226% (+34.9%) from 47.314%
13349921516

push

github

BenMorel
Use PHP 8.4 lazy proxies

26 of 47 new or added lines in 2 files covered. (55.32%)

55 existing lines in 4 files now uncovered.

1485 of 1806 relevant lines covered (82.23%)

1752.67 hits per line

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

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

3
declare(strict_types=1);
4

5
namespace Brick\Geo\Engine;
6

7
use Brick\Geo\CircularString;
8
use Brick\Geo\CompoundCurve;
9
use Brick\Geo\Curve;
10
use Brick\Geo\CurvePolygon;
11
use Brick\Geo\Exception\GeometryEngineException;
12
use Brick\Geo\Geometry;
13
use Brick\Geo\GeometryCollection;
14
use Brick\Geo\LineString;
15
use Brick\Geo\MultiCurve;
16
use Brick\Geo\MultiLineString;
17
use Brick\Geo\MultiPoint;
18
use Brick\Geo\MultiSurface;
19
use Brick\Geo\MultiPolygon;
20
use Brick\Geo\Point;
21
use Brick\Geo\Polygon;
22
use Brick\Geo\PolyhedralSurface;
23
use Brick\Geo\Surface;
24
use Brick\Geo\TIN;
25
use Brick\Geo\Triangle;
26

27
/**
28
 * Database implementation of the GeometryEngine.
29
 *
30
 * The target database must have support for GIS functions.
31
 */
32
abstract class DatabaseEngine implements GeometryEngine
33
{
34
    private readonly bool $useProxy;
35

36
    public function __construct(bool $useProxy)
37
    {
38
        $this->useProxy = $useProxy;
×
39
    }
40

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

56
    /**
57
     * Returns the syntax required to perform an ST_GeomFromText(), together with placeholders.
58
     *
59
     * This method may be overridden if necessary.
60
     */
61
    protected function getGeomFromTextSyntax(): string
62
    {
63
        return 'ST_GeomFromText(?, ?)';
120✔
64
    }
65

66
    /**
67
     * Returns the syntax required to perform an ST_GeomFromWKB(), together with placeholders.
68
     *
69
     * This method may be overridden if necessary.
70
     */
71
    protected function getGeomFromWKBSyntax(): string
72
    {
73
        return 'ST_GeomFromWKB(?, ?)';
409✔
74
    }
75

76
    /**
77
     * Returns the placeholder syntax for the given parameter.
78
     *
79
     * This method may be overridden to perform explicit type casts if necessary.
80
     */
81
    protected function getParameterPlaceholder(string|float|int $parameter): string
82
    {
83
        return '?';
102✔
84
    }
85

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

105
        foreach ($parameters as $parameter) {
1,263✔
106
            if ($parameter instanceof Geometry) {
1,263✔
107
                $sendAsBinary = ! $parameter->isEmpty();
1,263✔
108

109
                $queryParameters[] = $sendAsBinary
1,263✔
110
                    ? $this->getGeomFromWKBSyntax()
1,153✔
111
                    : $this->getGeomFromTextSyntax();
120✔
112

113
                $queryValues[] = new GeometryParameter($parameter, $sendAsBinary);
1,263✔
114
            } else {
115
                $queryParameters[] = $this->getParameterPlaceholder($parameter);
106✔
116
                $queryValues[] = $parameter;
106✔
117
            }
118
        }
119

120
        $query = sprintf('SELECT %s(%s)', $function, implode(', ', $queryParameters));
1,263✔
121

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

133
        return $this->executeQuery($query, $queryValues);
1,263✔
134
    }
135

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

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

154
        return (bool) $result;
636✔
155
    }
156

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

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

173
        return (float) $result;
164✔
174
    }
175

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

189
        [$wkt, $wkb, $geometryType, $srid] = $result;
247✔
190

191
        $srid = (int) $srid;
247✔
192

193
        if ($wkt !== null) {
247✔
194
            if ($this->useProxy) {
5✔
NEW
195
                $geometryClass = $this->getGeometryClass($geometryType);
5✔
NEW
196
                $reflectionClass = new \ReflectionClass($geometryClass);
5✔
197

NEW
198
                return $reflectionClass->newLazyProxy(fn() => $geometryClass::fromText($wkt, $srid));
5✔
199
            }
200

201
            return Geometry::fromText($wkt, $srid);
×
202
        }
203

204
        if ($wkb !== null) {
242✔
205
            if (is_resource($wkb)) {
228✔
206
                $wkb = stream_get_contents($wkb);
59✔
207
            }
208

209
            if ($this->useProxy) {
228✔
210
                $geometryClass = $this->getGeometryClass($geometryType);
228✔
211
                $reflectionClass = new \ReflectionClass($geometryClass);
228✔
212

213
                return $reflectionClass->newLazyProxy(fn() => $geometryClass::fromBinary($wkb, $srid));
228✔
214
            }
215

216
            return Geometry::fromBinary($wkb, $srid);
×
217
        }
218

219
        throw GeometryEngineException::operationYieldedNoResult();
14✔
220
    }
221

222
    /**
223
     * @return class-string<Geometry>
224
     *
225
     * @throws GeometryEngineException
226
     */
227
    private function getGeometryClass(string $geometryType) : string
228
    {
229
        $geometryClasses = [
233✔
230
            'CIRCULARSTRING'     => CircularString::class,
233✔
231
            'COMPOUNDCURVE'      => CompoundCurve::class,
233✔
232
            'CURVE'              => Curve::class,
233✔
233
            'CURVEPOLYGON'       => CurvePolygon::class,
233✔
234
            'GEOMCOLLECTION'     => GeometryCollection::class, /* MySQL 8 - https://github.com/brick/geo/pull/33 */
233✔
235
            'GEOMETRY'           => Geometry::class,
233✔
236
            'GEOMETRYCOLLECTION' => GeometryCollection::class,
233✔
237
            'LINESTRING'         => LineString::class,
233✔
238
            'MULTICURVE'         => MultiCurve::class,
233✔
239
            'MULTILINESTRING'    => MultiLineString::class,
233✔
240
            'MULTIPOINT'         => MultiPoint::class,
233✔
241
            'MULTIPOLYGON'       => MultiPolygon::class,
233✔
242
            'MULTISURFACE'       => MultiSurface::class,
233✔
243
            'POINT'              => Point::class,
233✔
244
            'POLYGON'            => Polygon::class,
233✔
245
            'POLYHEDRALSURFACE'  => PolyhedralSurface::class,
233✔
246
            'SURFACE'            => Surface::class,
233✔
247
            'TIN'                => TIN::class,
233✔
248
            'TRIANGLE'           => Triangle::class
233✔
249
        ];
233✔
250

251
        $geometryType = strtoupper($geometryType);
233✔
252
        $geometryType = preg_replace('/^ST_/', '', $geometryType);
233✔
253
        $geometryType = preg_replace('/ .*/', '', $geometryType);
233✔
254

255
        if (! isset($geometryClasses[$geometryType])) {
233✔
256
            throw new GeometryEngineException('Unknown geometry type: ' . $geometryType);
×
257
        }
258

259
        return $geometryClasses[$geometryType];
233✔
260
    }
261

262
    public function contains(Geometry $a, Geometry $b) : bool
263
    {
264
        return $this->queryBoolean('ST_Contains', $a, $b);
76✔
265
    }
266

267
    public function intersects(Geometry $a, Geometry $b) : bool
268
    {
269
        return $this->queryBoolean('ST_Intersects', $a, $b);
36✔
270
    }
271

272
    public function union(Geometry $a, Geometry $b) : Geometry
273
    {
274
        return $this->queryGeometry('ST_Union', $a, $b);
22✔
275
    }
276

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

282
    public function difference(Geometry $a, Geometry $b) : Geometry
283
    {
284
        return $this->queryGeometry('ST_Difference', $a, $b);
12✔
285
    }
286

287
    public function envelope(Geometry $g) : Geometry
288
    {
289
        return $this->queryGeometry('ST_Envelope', $g);
18✔
290
    }
291

292
    public function centroid(Geometry $g) : Point
293
    {
294
        /** @var Point */
295
        return $this->queryGeometry('ST_Centroid', $g);
45✔
296
    }
297

298
    public function pointOnSurface(Surface|MultiSurface $g) : Point
299
    {
300
        /** @var Point */
301
        return $this->queryGeometry('ST_PointOnSurface', $g);
42✔
302
    }
303

304
    public function length(Curve|MultiCurve $g) : float
305
    {
306
        return $this->queryFloat('ST_Length', $g);
95✔
307
    }
308

309
    public function area(Surface|MultiSurface $g) : float
310
    {
311
        return $this->queryFloat('ST_Area', $g);
66✔
312
    }
313

314
    public function azimuth(Point $observer, Point $subject) : float
315
    {
316
        return $this->queryFloat('ST_Azimuth', $observer, $subject);
12✔
317
    }
318

319
    public function boundary(Geometry $g) : Geometry
320
    {
321
        return $this->queryGeometry('ST_Boundary', $g);
36✔
322
    }
323

324
    public function isValid(Geometry $g) : bool
325
    {
326
        return $this->queryBoolean('ST_IsValid', $g);
46✔
327
    }
328

329
    public function isClosed(Geometry $g) : bool
330
    {
331
        return $this->queryBoolean('ST_IsClosed', $g);
276✔
332
    }
333

334
    public function isSimple(Geometry $g) : bool
335
    {
336
        return $this->queryBoolean('ST_IsSimple', $g);
102✔
337
    }
338

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

349
    public function makeValid(Geometry $g) : Geometry
350
    {
351
        return $this->queryGeometry('ST_MakeValid', $g);
12✔
352
    }
353

354
    public function equals(Geometry $a, Geometry $b) : bool
355
    {
356
        return $this->queryBoolean('ST_Equals', $a, $b);
122✔
357
    }
358

359
    public function disjoint(Geometry $a, Geometry $b) : bool
360
    {
361
        return $this->queryBoolean('ST_Disjoint', $a, $b);
36✔
362
    }
363

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

369
    public function crosses(Geometry $a, Geometry $b) : bool
370
    {
371
        return $this->queryBoolean('ST_Crosses', $a, $b);
48✔
372
    }
373

374
    public function within(Geometry $a, Geometry $b) : bool
375
    {
376
        return $this->queryBoolean('ST_Within', $a, $b);
30✔
377
    }
378

379
    public function overlaps(Geometry $a, Geometry $b) : bool
380
    {
381
        return $this->queryBoolean('ST_Overlaps', $a, $b);
12✔
382
    }
383

384
    public function relate(Geometry $a, Geometry $b, string $matrix) : bool
385
    {
386
        return $this->queryBoolean('ST_Relate', $a, $b, $matrix);
24✔
387
    }
388

389
    public function locateAlong(Geometry $g, float $mValue) : Geometry
390
    {
391
        return $this->queryGeometry('ST_LocateAlong', $g, $mValue);
12✔
392
    }
393

394
    public function locateBetween(Geometry $g, float $mStart, float $mEnd) : Geometry
395
    {
396
        return $this->queryGeometry('ST_LocateBetween', $g, $mStart, $mEnd);
12✔
397
    }
398

399
    public function distance(Geometry $a, Geometry $b) : float
400
    {
401
        return $this->queryFloat('ST_Distance', $a, $b);
30✔
402
    }
403

404
    public function buffer(Geometry $g, float $distance) : Geometry
405
    {
406
        return $this->queryGeometry('ST_Buffer', $g, $distance);
18✔
407
    }
408

409
    public function convexHull(Geometry $g) : Geometry
410
    {
411
        return $this->queryGeometry('ST_ConvexHull', $g);
18✔
412
    }
413

414
    public function symDifference(Geometry $a, Geometry $b) : Geometry
415
    {
416
        return $this->queryGeometry('ST_SymDifference', $a, $b);
6✔
417
    }
418

419
    public function snapToGrid(Geometry $g, float $size) : Geometry
420
    {
421
        return $this->queryGeometry('ST_SnapToGrid', $g, $size);
24✔
422
    }
423

424
    public function simplify(Geometry $g, float $tolerance) : Geometry
425
    {
426
        return $this->queryGeometry('ST_Simplify', $g, $tolerance);
12✔
427
    }
428

429
    public function maxDistance(Geometry $a, Geometry $b) : float
430
    {
431
        return $this->queryFloat('ST_MaxDistance', $a, $b);
18✔
432
    }
433

434
    public function transform(Geometry $g, int $srid) : Geometry
435
    {
436
        return $this->queryGeometry('ST_Transform', $g, $srid);
4✔
437
    }
438

439
    public function split(Geometry $g, Geometry $blade) : Geometry
440
    {
441
        return $this->queryGeometry('ST_Split', $g, $blade);
8✔
442
    }
443
}
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