Search by

rogervila / php-clamp-polyfill

rogervila

PHP 8.6 clamp polyfill for older PHP versions

Package info

github.com/rogervila/php-clamp-polyfill

pkg:composer/rogervila/php-clamp-polyfill

Statistics

Installs: 29

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

1.0.0 2026-11-16 11:11 UTC

This package is auto-updated.

Last update: 2026-11-16 11:20:43 UTC


README

Status Latest Stable Version Total Downloads License

Polyfill for PHP 8.6 clamp() on older PHP versions.

On PHP 8.6+, the native function is used. On earlier versions, this package provides a compatible implementation.

Requirements

  • PHP < 8.6 to load the polyfill (safe no-op when clamp() already exists)

Install

Via Composer:

composer require rogervila/php-clamp-polyfill

Usage

echo clamp(-5, min: 0, max: 100), PHP_EOL;  // 0
echo clamp(55, min: 0, max: 100), PHP_EOL;  // 55
echo clamp(103, min: 0, max: 100), PHP_EOL; // 100

echo clamp('J', min: 'A', max: 'F'), PHP_EOL; // F

echo clamp(
    new DateTimeImmutable('2025-08-01'),
    min: new DateTimeImmutable('2025-08-15'),
    max: new DateTimeImmutable('2025-09-15'),
)->format('Y-m-d'), PHP_EOL; // 2025-08-15

Errors

Matches native PHP 8.6 behavior:

  • ValueError when $min > $max
  • ValueError when $min or $max is NAN
  • NAN as $value is returned unchanged

Tests

composer test

CI runs the same suite on PHP 8.5 (polyfill) and PHP 8.6 (native clamp()).

Author

Created by Roger Vilà

License

php-clamp-polyfill is open-sourced software licensed under the MIT license.