phpmath / geometry
A PHP library to work with immutable 2D geometry.
Requires
- php: ^8.4
Requires (Dev)
- phpmath/coding-standard: ^2.0
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-24 12:59:40 UTC
README
A PHP library to work with immutable 2D geometry.
Documentation
The full documentation is at https://phpmath.github.io/geometry/. Every change is listed in the changelog and every release on the releases page.
Install
composer require phpmath/geometry
Requirements
- PHP 8.4 or newer
Usage
Every shape is an immutable value object with float coordinates. Operations never change the instance they
are called on, they return a new instance. Invalid input is rejected with a specific exception from the
PHPMath\Geometry\Exception namespace.
use PHPMath\Geometry\Circle; use PHPMath\Geometry\Line; use PHPMath\Geometry\Point; use PHPMath\Geometry\Polygon; use PHPMath\Geometry\Segment; $a = new Point(0, 0); $b = new Point(3, 4); $a->distanceTo($b); // 5.0 $a->midpointTo($b); // Point(1.5, 2.0) $segment = new Segment($a, $b); $segment->intersectionWith(new Segment(new Point(0, 4), new Point(3, 0))); // Point(1.5, 2.0) $line = Line::through($a, $b); $line->distanceTo(new Point(4, 3)); // 0.8 (perpendicular distance) $circle = new Circle(new Point(0, 0), 5); $circle->intersectionsWith(new Circle(new Point(6, 0), 5)); // [Point(3, 4), Point(3, -4)] $polygon = new Polygon([new Point(0, 0), new Point(4, 0), new Point(4, 4), new Point(0, 4)]); $polygon->area(); // 16.0 $polygon->centroid(); // Point(2.0, 2.0) $polygon->contains(new Point(1, 1)); // true
Features
Point:distanceTo(),midpointTo(),translate()andequals()with a tolerance.Segment:length(),midpoint(),intersectionWith()andcontains().Line(through two points withLine::through(), or from a point and an angle):intersectionWith(),distanceTo()andisParallelTo().Circle:area(),circumference(),contains()andintersectionsWith().Rectangle(axis-aligned, alsoRectangle::fromCorners()):area(),perimeter(),contains()andintersects().Polygon(at least three points):area()(shoelace),perimeter(),centroid(),contains()(ray casting),isConvex()andorientation().- Exceptions for negative radius or size, non-finite values, degenerate segments and lines, and polygons with too few points.
Tolerance based methods default to Point::DEFAULT_TOLERANCE (1e-9). Boundaries are inclusive: a point on a
circle, rectangle or polygon edge is contained. Angles are in radians, counter-clockwise from the positive x axis.
Development
composer test
composer test-coverage
composer analyse
composer check-style
composer fix-style
Contributing
All contributions are welcome. Open an issue or a pull request on GitHub. Please follow the coding standard and add tests.
Security
If you discover a security issue, please create an issue in the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.