Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
95.76% covered (success)
95.76%
226 / 236
72.73% covered (warning)
72.73%
16 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
BoundingBox
95.76% covered (success)
95.76%
226 / 236
72.73% covered (warning)
72.73%
16 / 22
82
0.00% covered (danger)
0.00%
0 / 1
 compute
100.00% covered (success)
100.00%
50 / 50
100.00% covered (success)
100.00%
1 / 1
17
 pathBoundingBox
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
14.04
 update
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
5
 result
87.50% covered (warning)
87.50%
7 / 8
0.00% covered (danger)
0.00%
0 / 1
5.05
 clearCurveState
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 resolveAbsolute
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
2
 visitMoveTo
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
1
 visitLineTo
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 visitHorizontalLineTo
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 visitVerticalLineTo
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 visitCurveTo
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 visitSmoothCurveTo
86.67% covered (warning)
86.67%
13 / 15
0.00% covered (danger)
0.00%
0 / 1
3.02
 visitQuadraticCurveTo
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 visitSmoothQuadraticCurveTo
85.71% covered (warning)
85.71%
12 / 14
0.00% covered (danger)
0.00%
0 / 1
3.03
 visitArcTo
100.00% covered (success)
100.00%
31 / 31
100.00% covered (success)
100.00%
1 / 1
2
 visitClosePath
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 visitCubicSegment
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
3
 visitQuadraticSegment
72.73% covered (warning)
72.73%
8 / 11
0.00% covered (danger)
0.00%
0 / 1
3.18
 cubicExtremaT
94.12% covered (success)
94.12%
16 / 17
0.00% covered (danger)
0.00%
0 / 1
9.02
 quadraticExtremumT
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
4
 evalCubic
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 evalQuadratic
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2
3declare(strict_types=1);
4
5namespace Phpdftk\SvgToPdf\Geometry;
6
7use Phpdftk\Svg\Element;
8use Phpdftk\Svg\Path;
9use Phpdftk\Svg\Path\ArcTo;
10use Phpdftk\Svg\Path\ClosePath;
11use Phpdftk\Svg\Path\CurveTo;
12use Phpdftk\Svg\Path\HorizontalLineTo;
13use Phpdftk\Svg\Path\LineTo;
14use Phpdftk\Svg\Path\MoveTo;
15use Phpdftk\Svg\Path\QuadraticCurveTo;
16use Phpdftk\Svg\Path\SmoothCurveTo;
17use Phpdftk\Svg\Path\SmoothQuadraticCurveTo;
18use Phpdftk\Svg\Path\VerticalLineTo;
19use Phpdftk\Svg\Shape\Circle;
20use Phpdftk\Svg\Shape\Ellipse;
21use Phpdftk\Svg\Shape\Line;
22use Phpdftk\Svg\Shape\Polygon;
23use Phpdftk\Svg\Shape\Polyline;
24use Phpdftk\Svg\Shape\Rect;
25use Phpdftk\SvgToPdf\Path\ArcToCubic;
26
27/**
28 * Axis-aligned bounding box used by `objectBoundingBox`-mode gradients
29 * (SVG 2 §13.6.5), clip paths (§14.4), and masks (§14.5). Returns null
30 * for elements whose bbox can't be computed — the caller (gradient /
31 * clip / mask painter) falls back to no paint per SVG 2's "invalid →
32 * no paint" rule.
33 *
34 * `<path>` bbox handling tracks every command's contribution: line
35 * endpoints, cubic / quadratic Bézier endpoints **and** interior extrema
36 * (found by solving the derivative-equals-zero equation per axis), and
37 * arc segments routed through the same arc→cubic conversion the painter
38 * uses so the bbox is consistent with what gets drawn.
39 */
40final class BoundingBox
41{
42    /** Treat any value below this magnitude as zero. */
43    private const float EPSILON = 1.0e-12;
44
45    /**
46     * @return array{minX: float, minY: float, width: float, height: float}|null
47     */
48    public static function compute(Element $element): ?array
49    {
50        if ($element instanceof Rect) {
51            $w = $element->width();
52            $h = $element->height();
53            return $w <= 0.0 || $h <= 0.0
54                ? null
55                : ['minX' => $element->x(), 'minY' => $element->y(), 'width' => $w, 'height' => $h];
56        }
57        if ($element instanceof Circle) {
58            $r = $element->r();
59            if ($r <= 0.0) {
60                return null;
61            }
62            return [
63                'minX' => $element->cx() - $r,
64                'minY' => $element->cy() - $r,
65                'width' => 2.0 * $r,
66                'height' => 2.0 * $r,
67            ];
68        }
69        if ($element instanceof Ellipse) {
70            $rx = $element->rx();
71            $ry = $element->ry();
72            if ($rx === null || $ry === null || $rx <= 0.0 || $ry <= 0.0) {
73                return null;
74            }
75            return [
76                'minX' => $element->cx() - $rx,
77                'minY' => $element->cy() - $ry,
78                'width' => 2.0 * $rx,
79                'height' => 2.0 * $ry,
80            ];
81        }
82        if ($element instanceof Line) {
83            $minX = min($element->x1(), $element->x2());
84            $minY = min($element->y1(), $element->y2());
85            $maxX = max($element->x1(), $element->x2());
86            $maxY = max($element->y1(), $element->y2());
87            return ['minX' => $minX, 'minY' => $minY, 'width' => $maxX - $minX, 'height' => $maxY - $minY];
88        }
89        if ($element instanceof Polyline || $element instanceof Polygon) {
90            $points = $element->points();
91            if ($points === []) {
92                return null;
93            }
94            $minX = $points[0][0];
95            $minY = $points[0][1];
96            $maxX = $minX;
97            $maxY = $minY;
98            foreach ($points as $p) {
99                $minX = min($minX, $p[0]);
100                $minY = min($minY, $p[1]);
101                $maxX = max($maxX, $p[0]);
102                $maxY = max($maxY, $p[1]);
103            }
104            return ['minX' => $minX, 'minY' => $minY, 'width' => $maxX - $minX, 'height' => $maxY - $minY];
105        }
106        if ($element instanceof Path) {
107            return self::pathBoundingBox($element);
108        }
109        return null;
110    }
111
112    /**
113     * @return array{minX: float, minY: float, width: float, height: float}|null
114     */
115    private static function pathBoundingBox(Path $path): ?array
116    {
117        $commands = $path->d()->commands;
118        if ($commands === []) {
119            return null;
120        }
121
122        $tracker = new self();
123        foreach ($commands as $command) {
124            match (true) {
125                $command instanceof MoveTo => $tracker->visitMoveTo($command),
126                $command instanceof LineTo => $tracker->visitLineTo($command),
127                $command instanceof HorizontalLineTo => $tracker->visitHorizontalLineTo($command),
128                $command instanceof VerticalLineTo => $tracker->visitVerticalLineTo($command),
129                $command instanceof CurveTo => $tracker->visitCurveTo($command),
130                $command instanceof SmoothCurveTo => $tracker->visitSmoothCurveTo($command),
131                $command instanceof QuadraticCurveTo => $tracker->visitQuadraticCurveTo($command),
132                $command instanceof SmoothQuadraticCurveTo => $tracker->visitSmoothQuadraticCurveTo($command),
133                $command instanceof ArcTo => $tracker->visitArcTo($command),
134                $command instanceof ClosePath => $tracker->visitClosePath(),
135                default => null,
136            };
137        }
138        return $tracker->result();
139    }
140
141    private ?float $minX = null;
142    private ?float $maxX = null;
143    private ?float $minY = null;
144    private ?float $maxY = null;
145    private float $currentX = 0.0;
146    private float $currentY = 0.0;
147    private float $subpathStartX = 0.0;
148    private float $subpathStartY = 0.0;
149    private ?float $lastCubicCtrlX = null;
150    private ?float $lastCubicCtrlY = null;
151    private ?float $lastQuadCtrlX = null;
152    private ?float $lastQuadCtrlY = null;
153
154    private function update(float $x, float $y): void
155    {
156        $this->minX = $this->minX === null ? $x : min($this->minX, $x);
157        $this->maxX = $this->maxX === null ? $x : max($this->maxX, $x);
158        $this->minY = $this->minY === null ? $y : min($this->minY, $y);
159        $this->maxY = $this->maxY === null ? $y : max($this->maxY, $y);
160    }
161
162    /**
163     * @return array{minX: float, minY: float, width: float, height: float}|null
164     */
165    private function result(): ?array
166    {
167        if ($this->minX === null || $this->maxX === null || $this->minY === null || $this->maxY === null) {
168            return null;
169        }
170        return [
171            'minX' => $this->minX,
172            'minY' => $this->minY,
173            'width' => $this->maxX - $this->minX,
174            'height' => $this->maxY - $this->minY,
175        ];
176    }
177
178    private function clearCurveState(): void
179    {
180        $this->lastCubicCtrlX = null;
181        $this->lastCubicCtrlY = null;
182        $this->lastQuadCtrlX = null;
183        $this->lastQuadCtrlY = null;
184    }
185
186    /**
187     * @return array{float, float}
188     */
189    private function resolveAbsolute(float $x, float $y, bool $absolute): array
190    {
191        return $absolute ? [$x, $y] : [$this->currentX + $x, $this->currentY + $y];
192    }
193
194    private function visitMoveTo(MoveTo $cmd): void
195    {
196        [$x, $y] = $this->resolveAbsolute($cmd->x, $cmd->y, $cmd->absolute);
197        $this->update($x, $y);
198        $this->currentX = $x;
199        $this->currentY = $y;
200        $this->subpathStartX = $x;
201        $this->subpathStartY = $y;
202        $this->clearCurveState();
203    }
204
205    private function visitLineTo(LineTo $cmd): void
206    {
207        [$x, $y] = $this->resolveAbsolute($cmd->x, $cmd->y, $cmd->absolute);
208        $this->update($x, $y);
209        $this->currentX = $x;
210        $this->currentY = $y;
211        $this->clearCurveState();
212    }
213
214    private function visitHorizontalLineTo(HorizontalLineTo $cmd): void
215    {
216        $x = $cmd->absolute ? $cmd->x : $this->currentX + $cmd->x;
217        $this->update($x, $this->currentY);
218        $this->currentX = $x;
219        $this->clearCurveState();
220    }
221
222    private function visitVerticalLineTo(VerticalLineTo $cmd): void
223    {
224        $y = $cmd->absolute ? $cmd->y : $this->currentY + $cmd->y;
225        $this->update($this->currentX, $y);
226        $this->currentY = $y;
227        $this->clearCurveState();
228    }
229
230    private function visitCurveTo(CurveTo $cmd): void
231    {
232        [$x1, $y1] = $this->resolveAbsolute($cmd->x1, $cmd->y1, $cmd->absolute);
233        [$x2, $y2] = $this->resolveAbsolute($cmd->x2, $cmd->y2, $cmd->absolute);
234        [$x, $y] = $this->resolveAbsolute($cmd->x, $cmd->y, $cmd->absolute);
235        $this->visitCubicSegment($this->currentX, $this->currentY, $x1, $y1, $x2, $y2, $x, $y);
236        $this->currentX = $x;
237        $this->currentY = $y;
238        $this->lastCubicCtrlX = $x2;
239        $this->lastCubicCtrlY = $y2;
240        $this->lastQuadCtrlX = null;
241        $this->lastQuadCtrlY = null;
242    }
243
244    private function visitSmoothCurveTo(SmoothCurveTo $cmd): void
245    {
246        // The first control point is the reflection of the previous
247        // cubic's last control about the current point; falls back to
248        // the current point itself when the previous command wasn't
249        // cubic (matches PathPainterState's behaviour).
250        $x1 = $this->lastCubicCtrlX === null
251            ? $this->currentX
252            : 2.0 * $this->currentX - $this->lastCubicCtrlX;
253        $y1 = $this->lastCubicCtrlY === null
254            ? $this->currentY
255            : 2.0 * $this->currentY - $this->lastCubicCtrlY;
256        [$x2, $y2] = $this->resolveAbsolute($cmd->x2, $cmd->y2, $cmd->absolute);
257        [$x, $y] = $this->resolveAbsolute($cmd->x, $cmd->y, $cmd->absolute);
258        $this->visitCubicSegment($this->currentX, $this->currentY, $x1, $y1, $x2, $y2, $x, $y);
259        $this->currentX = $x;
260        $this->currentY = $y;
261        $this->lastCubicCtrlX = $x2;
262        $this->lastCubicCtrlY = $y2;
263        $this->lastQuadCtrlX = null;
264        $this->lastQuadCtrlY = null;
265    }
266
267    private function visitQuadraticCurveTo(QuadraticCurveTo $cmd): void
268    {
269        [$qx, $qy] = $this->resolveAbsolute($cmd->x1, $cmd->y1, $cmd->absolute);
270        [$x, $y] = $this->resolveAbsolute($cmd->x, $cmd->y, $cmd->absolute);
271        $this->visitQuadraticSegment($this->currentX, $this->currentY, $qx, $qy, $x, $y);
272        $this->currentX = $x;
273        $this->currentY = $y;
274        $this->lastQuadCtrlX = $qx;
275        $this->lastQuadCtrlY = $qy;
276        $this->lastCubicCtrlX = null;
277        $this->lastCubicCtrlY = null;
278    }
279
280    private function visitSmoothQuadraticCurveTo(SmoothQuadraticCurveTo $cmd): void
281    {
282        $qx = $this->lastQuadCtrlX === null
283            ? $this->currentX
284            : 2.0 * $this->currentX - $this->lastQuadCtrlX;
285        $qy = $this->lastQuadCtrlY === null
286            ? $this->currentY
287            : 2.0 * $this->currentY - $this->lastQuadCtrlY;
288        [$x, $y] = $this->resolveAbsolute($cmd->x, $cmd->y, $cmd->absolute);
289        $this->visitQuadraticSegment($this->currentX, $this->currentY, $qx, $qy, $x, $y);
290        $this->currentX = $x;
291        $this->currentY = $y;
292        $this->lastQuadCtrlX = $qx;
293        $this->lastQuadCtrlY = $qy;
294        $this->lastCubicCtrlX = null;
295        $this->lastCubicCtrlY = null;
296    }
297
298    private function visitArcTo(ArcTo $cmd): void
299    {
300        [$endX, $endY] = $this->resolveAbsolute($cmd->x, $cmd->y, $cmd->absolute);
301        // Update the endpoint regardless so a zero-length arc still
302        // affects the bbox via its endpoints.
303        $this->update($endX, $endY);
304        $segments = ArcToCubic::convert(
305            $this->currentX,
306            $this->currentY,
307            $cmd->rx,
308            $cmd->ry,
309            $cmd->xAxisRotation,
310            $cmd->largeArc,
311            $cmd->sweep,
312            $endX,
313            $endY,
314        );
315        $segStartX = $this->currentX;
316        $segStartY = $this->currentY;
317        foreach ($segments as $seg) {
318            $this->visitCubicSegment(
319                $segStartX,
320                $segStartY,
321                $seg['x1'],
322                $seg['y1'],
323                $seg['x2'],
324                $seg['y2'],
325                $seg['x'],
326                $seg['y'],
327            );
328            $segStartX = $seg['x'];
329            $segStartY = $seg['y'];
330        }
331        $this->currentX = $endX;
332        $this->currentY = $endY;
333        $this->clearCurveState();
334    }
335
336    private function visitClosePath(): void
337    {
338        $this->update($this->subpathStartX, $this->subpathStartY);
339        $this->currentX = $this->subpathStartX;
340        $this->currentY = $this->subpathStartY;
341        $this->clearCurveState();
342    }
343
344    private function visitCubicSegment(
345        float $p0x,
346        float $p0y,
347        float $p1x,
348        float $p1y,
349        float $p2x,
350        float $p2y,
351        float $p3x,
352        float $p3y,
353    ): void {
354        // Endpoint of the segment (the start is the previous current
355        // point, already covered by an earlier update).
356        $this->update($p3x, $p3y);
357        foreach (self::cubicExtremaT($p0x, $p1x, $p2x, $p3x) as $t) {
358            $x = self::evalCubic($p0x, $p1x, $p2x, $p3x, $t);
359            $y = self::evalCubic($p0y, $p1y, $p2y, $p3y, $t);
360            $this->update($x, $y);
361        }
362        foreach (self::cubicExtremaT($p0y, $p1y, $p2y, $p3y) as $t) {
363            $x = self::evalCubic($p0x, $p1x, $p2x, $p3x, $t);
364            $y = self::evalCubic($p0y, $p1y, $p2y, $p3y, $t);
365            $this->update($x, $y);
366        }
367    }
368
369    private function visitQuadraticSegment(
370        float $p0x,
371        float $p0y,
372        float $p1x,
373        float $p1y,
374        float $p2x,
375        float $p2y,
376    ): void {
377        $this->update($p2x, $p2y);
378        $tx = self::quadraticExtremumT($p0x, $p1x, $p2x);
379        if ($tx !== null) {
380            $x = self::evalQuadratic($p0x, $p1x, $p2x, $tx);
381            $y = self::evalQuadratic($p0y, $p1y, $p2y, $tx);
382            $this->update($x, $y);
383        }
384        $ty = self::quadraticExtremumT($p0y, $p1y, $p2y);
385        if ($ty !== null) {
386            $x = self::evalQuadratic($p0x, $p1x, $p2x, $ty);
387            $y = self::evalQuadratic($p0y, $p1y, $p2y, $ty);
388            $this->update($x, $y);
389        }
390    }
391
392    /**
393     * Roots of `B'(t) = 0` for a cubic Bézier component, clipped to
394     * the open interval `(0, 1)` — endpoints are already covered by
395     * the segment's own endpoint contributions.
396     *
397     * @return list<float>
398     */
399    private static function cubicExtremaT(float $p0, float $p1, float $p2, float $p3): array
400    {
401        // B(t) = (1-t)³ p0 + 3(1-t)²t p1 + 3(1-t)t² p2 + t³ p3
402        // B'(t) = 3 [ (p1-p0) + 2t (p2 - 2p1 + p0) + t² (p3 - 3p2 + 3p1 - p0) ]
403        $a = $p3 - 3.0 * $p2 + 3.0 * $p1 - $p0;
404        $b = 2.0 * ($p2 - 2.0 * $p1 + $p0);
405        $c = $p1 - $p0;
406
407        if (abs($a) < self::EPSILON) {
408            // Reduced to linear: b·t + c = 0 → t = -c / b.
409            if (abs($b) < self::EPSILON) {
410                return [];
411            }
412            $t = -$c / $b;
413            return $t > 0.0 && $t < 1.0 ? [$t] : [];
414        }
415
416        $discriminant = $b * $b - 4.0 * $a * $c;
417        if ($discriminant < 0.0) {
418            return [];
419        }
420        $sqrtD = sqrt($discriminant);
421        $out = [];
422        foreach ([(-$b + $sqrtD) / (2.0 * $a), (-$b - $sqrtD) / (2.0 * $a)] as $t) {
423            if ($t > 0.0 && $t < 1.0) {
424                $out[] = $t;
425            }
426        }
427        return $out;
428    }
429
430    /**
431     * Root of `Q'(t) = 0` for a quadratic Bézier component, clipped to
432     * the open interval `(0, 1)`. Returns null when the quadratic
433     * collapses to a line (no interior extremum).
434     */
435    private static function quadraticExtremumT(float $p0, float $p1, float $p2): ?float
436    {
437        $denom = $p0 - 2.0 * $p1 + $p2;
438        if (abs($denom) < self::EPSILON) {
439            return null;
440        }
441        $t = ($p0 - $p1) / $denom;
442        return $t > 0.0 && $t < 1.0 ? $t : null;
443    }
444
445    private static function evalCubic(float $p0, float $p1, float $p2, float $p3, float $t): float
446    {
447        $s = 1.0 - $t;
448        return $s * $s * $s * $p0
449            + 3.0 * $s * $s * $t * $p1
450            + 3.0 * $s * $t * $t * $p2
451            + $t * $t * $t * $p3;
452    }
453
454    private static function evalQuadratic(float $p0, float $p1, float $p2, float $t): float
455    {
456        $s = 1.0 - $t;
457        return $s * $s * $p0 + 2.0 * $s * $t * $p1 + $t * $t * $p2;
458    }
459}