PHP code example of gladehq / php-coerce

1. Go to this page and download the library: Download gladehq/php-coerce library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gladehq / php-coerce example snippets


use GladeHq\PhpCoerce\Coerce;

Coerce::toInteger('42');               // 42
Coerce::toInteger('abc');              // null (not 0)
Coerce::toInteger(42.9);              // null (no silent truncation)
Coerce::toBoolean('yes');             // true
Coerce::toFloat('1,234.56');          // 1234.56 (auto-detected US format)
Coerce::toDateTime('2024-01-15');     // DateTimeImmutable
Coerce::toEnum('active', Status::class); // Status::Active
Coerce::equals(0.1 + 0.2, 0.3);      // true (IEEE-754 safe comparison)
Coerce::toBcDecimal(3.14, 4);         // '3.1400' (financial-safe decimal string)
Coerce::toPercent('50%');             // 0.5
Coerce::isEmail('[email protected]'); // true

use GladeHq\PhpCoerce\Coerce;

$age     = Coerce::toInteger($request->input('age'));      // ?int
$price   = Coerce::toFloat($row['price']);                 // ?float
$active  = Coerce::toBoolean($env['FEATURE_FLAG']);        // ?bool
$status  = Coerce::toEnum($data['status'], Status::class); // ?Status

use GladeHq\PhpCoerce\Coerce;

$age      = Coerce::from($request->input('age'))->toPositiveIntOr(1);
$name     = Coerce::from($input)->toStringOrEmpty();
$status   = Coerce::from($value)->toEnum(Status::class);
$tags     = Coerce::from($input)->toArrayOr([], ',');
$email    = Coerce::from($input)->toNullIfBlank();
$discount = Coerce::from($input)->toPercent();   // '20%' → 0.2

Coerce::toBoolean(mixed $value): ?bool

Coerce::isTruthy(mixed $value): bool   // coerce($value) === true
Coerce::isFalsy(mixed $value): bool    // coerce($value) === false

Coerce::from($value)->toBoolean();         // ?bool
Coerce::from($value)->toBooleanOr(false);  // bool
Coerce::from($value)->isTruthy();          // bool
Coerce::from($value)->isFalsy();           // bool

Coerce::toInteger(mixed $value): ?int

Coerce::from($value)->toInteger();      // ?int
Coerce::from($value)->toIntegerOr(0);   // int

Coerce::toPositiveInt(mixed $value): ?int   // > 0
Coerce::toUnsignedInt(mixed $value): ?int   // >= 0

Coerce::from($value)->toPositiveInt();          // ?int
Coerce::from($value)->toPositiveIntOr(1);       // int
Coerce::from($value)->toUnsignedInt();          // ?int
Coerce::from($value)->toUnsignedIntOr(0);       // int

Coerce::toFloat(mixed $value): ?float

Coerce::from($value)->toFloat();         // ?float
Coerce::from($value)->toFloatOr(0.0);    // float

Coerce::toRoundedFloat(mixed $value, int $precision): ?float

Coerce::toRoundedFloat(3.14159, 2);     // 3.14
Coerce::toRoundedFloat('3.14159', 3);   // 3.142
Coerce::toRoundedFloat('abc', 2);       // null

Coerce::from($value)->toRoundedFloat(2);            // ?float
Coerce::from($value)->toRoundedFloatOr(2, 0.0);     // float

Coerce::toBcDecimal(mixed $value, int $scale = 10): ?string

Coerce::toBcDecimal(3.14);              // '3.1400000000'
Coerce::toBcDecimal(3.14, 2);          // '3.14'
Coerce::toBcDecimal('1,234.56', 4);    // '1234.5600'
Coerce::toBcDecimal(1e5, 2);           // '100000.00'
Coerce::toBcDecimal(INF);             // null
Coerce::toBcDecimal('abc');            // null

Coerce::from($value)->toBcDecimal();        // ?string (scale 10)
Coerce::from($value)->toBcDecimal(4);       // ?string (scale 4)

Coerce::toPercent(mixed $value): ?float

Coerce::toPercent('50%');     // 0.5
Coerce::toPercent('100%');    // 1.0
Coerce::toPercent('-50%');    // -0.5
Coerce::toPercent(50);        // 0.5   (50 / 100)
Coerce::toPercent(0.5);       // 0.5   (already a ratio)
Coerce::toPercent(1.5);       // 0.015 (1.5 / 100)
Coerce::toPercent('abc%');    // null

Coerce::from($value)->toPercent();            // ?float
Coerce::from($value)->toPercentOr(0.0);       // float

Coerce::toString(mixed $value): ?string
Coerce::toStringOrEmpty(mixed $value): string

Coerce::from($value)->toString();           // ?string
Coerce::from($value)->toStringOr('N/A');    // string
Coerce::from($value)->toStringOrEmpty();    // string

Coerce::toArray(mixed $value, ?string $separator = null): ?array

Coerce::toArray('["a","b"]');           // ['a', 'b']
Coerce::toArray('{"key":"val"}');       // ['key' => 'val']
Coerce::toArray('a, b, c', ',');        // ['a', 'b', 'c']
Coerce::toArray('one|two', '|');        // ['one', 'two']
Coerce::toArray('[]');                  // []
Coerce::toArray('{}');                  // []
Coerce::toArray(42);                    // [42]
Coerce::toArray(null);                  // null

Coerce::toArray('["a","b"]', ',');      // ['a', 'b'] (JSON wins)

Coerce::from($value)->toArray(',');          // ?array
Coerce::from($value)->toArrayOr([], ',');    // array

/**
 * @param callable(mixed): mixed $fn
 * @return array<int|string, mixed>|null
 */
Coerce::coerceEach(mixed $value, callable $fn): ?array

Coerce::coerceEach('[1,2,3]', fn($v) => Coerce::toInteger($v));
// [1, 2, 3]

Coerce::coerceEach('a,b,c', fn($v) => strtoupper($v));
// null — no separator provided, 'a,b,c' wraps to ['a,b,c']
// Pass separator via toArray first, or use the fluent API:

Coerce::from('a,b,c')->toArray(',');
// then map manually, or:

Coerce::coerceEach(['a', 'b', 'c'], fn($v) => strtoupper($v));
// ['A', 'B', 'C']

Coerce::coerceEach(null, fn($v) => $v);
// null

Coerce::from($value)->coerceEach(fn($v) => Coerce::toInteger($v));  // ?array

Coerce::toDateTime(mixed $value): ?DateTimeImmutable

Coerce::toDateTime(1705276800);              // DateTimeImmutable (2024-01-15)
Coerce::toDateTime('1705276800');            // null
Coerce::toDateTime((int) '1705276800');      // DateTimeImmutable (2024-01-15)

Coerce::setDateFormat('d/m/Y');
Coerce::toDateTime('15/01/2024');            // DateTimeImmutable
Coerce::toDateTime('15/01/2024 garbage');    // null (strict matching)
Coerce::toDateTime('2024-01-15');            // null (format mismatch)

Coerce::toDateTime('next monday');    // DateTimeImmutable (next Monday at 00:00:00)
Coerce::toDateTime('last friday');    // DateTimeImmutable (last Friday at 00:00:00)
Coerce::toDateTime('tomorrow');       // DateTimeImmutable (tomorrow at 00:00:00)
Coerce::toDateTime('yesterday');      // DateTimeImmutable (yesterday at 00:00:00)
Coerce::toDateTime('+2 weeks');       // DateTimeImmutable (14 days from now)
Coerce::toDateTime('now');            // DateTimeImmutable (current date and time)

Coerce::setDateFormat('Y-m-d');

Coerce::toDateTime('2024-01-15');     // DateTimeImmutable
Coerce::toDateTime('next monday');    // null (does not match Y-m-d)
Coerce::toDateTime('tomorrow');       // null (does not match Y-m-d)
Coerce::toDateTime('now');            // null (does not match Y-m-d)

Coerce::from($value)->toDateTime();                            // ?DateTimeImmutable
Coerce::from($value)->toDateTimeOr(new DateTimeImmutable());   // DateTimeImmutable

Coerce::toEnum(mixed $value, string $enumClass): ?BackedEnum

enum Status: string {
    case Active   = 'active';
    case Inactive = 'inactive';
}

enum Priority: int {
    case Low    = 1;
    case Medium = 2;
    case High   = 3;
}

Coerce::from($value)->toEnum(Status::class);                      // ?Status
Coerce::from($value)->toEnumOr(Status::class, Status::Active);    // Status

Coerce::equals(mixed $a, mixed $b): bool
Coerce::isOneOf(mixed $value, array $values): bool

Coerce::equals(42, '42');            // true  (numeric layer)
Coerce::equals(3.14, '3.14');        // true  (numeric layer)
Coerce::equals(true, 'yes');         // true  (boolean layer, one side is bool)
Coerce::equals(true, 1);             // true  (boolean layer, one side is bool)
Coerce::equals('1', 'true');         // false (neither side is bool)
Coerce::equals('0', 'false');        // false (neither side is bool)
Coerce::equals(null, null);          // true  (same type)

// IEEE-754 safe — these all return true
Coerce::equals(0.1 + 0.2, 0.3);     // true
Coerce::equals(1/3 * 3, 1.0);       // true

Coerce::isOneOf(42, [1, 42, 100]);   // true
Coerce::isOneOf('42', [1, 42]);      // true  (cross-type)
Coerce::isOneOf(99, [1, 42]);        // false

Coerce::isBlank(mixed $value): bool
Coerce::isPresent(mixed $value): bool

Coerce::from($value)->isBlank();         // bool
Coerce::from($value)->isPresent();       // bool
Coerce::from($value)->toNullIfBlank();   // mixed — returns null if blank, original value otherwise

$bio = Coerce::from($request->input('bio'))->toNullIfBlank(); // null or string

Coerce::isEmail(mixed $value): bool
Coerce::isUrl(mixed $value): bool

Coerce::isEmail('[email protected]');    // true
Coerce::isEmail('invalid');             // false
Coerce::isEmail(null);                  // false
Coerce::isEmail(42);                    // false

Coerce::isUrl('https://example.com');   // true
Coerce::isUrl('not-a-url');             // false
Coerce::isUrl(null);                    // false

Coerce::from($value)->isEmail();    // bool
Coerce::from($value)->isUrl();      // bool

// Auto (default): intelligently detects format
Coerce::toFloat('1,234.56');    // 1234.56 (detected US)
Coerce::toFloat('1.234,56');    // 1234.56 (detected EU)

// Force US format: comma = thousands separator, dot = decimal
Coerce::setNumberFormat('us');
Coerce::toFloat('1,234.56');    // 1234.56

// Force EU format: dot = thousands separator, comma = decimal
Coerce::setNumberFormat('eu');
Coerce::toFloat('1.234,56');    // 1234.56

// Auto (default): PHP native parsing
Coerce::toDateTime('2024-01-15');          // works
Coerce::toDateTime('Jan 15, 2024');        // works

// Custom format: strict matching, no trailing garbage
Coerce::setDateFormat('d/m/Y');
Coerce::toDateTime('15/01/2024');          // DateTimeImmutable
Coerce::toDateTime('2024-01-15');          // null (wrong format)
Coerce::toDateTime('15/01/2024 extra');    // null (trailing data rejected)

Coerce::configure([
    'truthy_values' => ['true', '1', 'yes', 'on', 'enabled', 'active'],
    'falsy_values'  => ['false', '0', 'no', 'off', 'disabled', 'inactive'],
]);

Coerce::toBoolean('enabled');     // true
Coerce::toBoolean('inactive');    // false

// Default: PHP_FLOAT_EPSILON (~2.2e-16)
Coerce::equals(0.1 + 0.2, 0.3);     // true

// Widen epsilon for less-precise comparisons
Configuration::setFloatEpsilon(0.01);
Coerce::equals(1.0, 1.005);          // true
Coerce::equals(1.0, 1.02);           // false

Coerce::configure([
    'number_format' => 'eu',
    'date_format'   => 'd/m/Y',
    'truthy_values' => ['true', '1', 'yes', 'on'],
    'falsy_values'  => ['false', '0', 'no', 'off'],
    'float_epsilon' => 0.0001,
]);

Coerce::resetConfiguration(); // Restores all defaults

$age       = Coerce::from($request->input('age'))->toIntegerOr(0);
$subscribe = Coerce::from($request->input('newsletter'))->toBooleanOr(false);
$tags      = Coerce::from($request->input('tags'))->toArrayOr([], ',');
$joinedAt  = Coerce::toDateTime($request->input('joined_at'));

$debug   = Coerce::toBoolean(env('APP_DEBUG'));               // ?bool
$port    = Coerce::from(env('PORT'))->toIntegerOr(8080);      // int
$timeout = Coerce::from(env('TIMEOUT'))->toFloatOr(30.0);     // float
$dsn     = Coerce::from(env('DATABASE_URL'))->toStringOr(''); // string

Coerce::setNumberFormat('eu');

foreach ($rows as $row) {
    $price = Coerce::toFloat($row['price']);    // "1.234,56" -> 1234.56
    $qty   = Coerce::toInteger($row['qty']);    // "42" -> 42, "abc" -> null
    $date  = Coerce::toDateTime($row['date']);  // "15/01/2024" -> DateTimeImmutable
}

$status    = Coerce::toEnum($response['status'], OrderStatus::class);
$createdAt = Coerce::toDateTime($response['created_at']);
$amount    = Coerce::toFloat($response['amount']);

if ($status === null) {
    throw new InvalidResponseException('Unknown order status: ' . $response['status']);
}

$config = [
    'retries' => Coerce::from($options['retries'] ?? null)->toIntegerOr(3),
    'timeout' => Coerce::from($options['timeout'] ?? null)->toFloatOr(30.0),
    'verbose' => Coerce::from($options['verbose'] ?? null)->toBooleanOr(false),
    'tags'    => Coerce::from($options['tags'] ?? null)->toArrayOr([]),
];

// Unlike empty(), zero and false are NOT blank
Coerce::isBlank(0);        // false
Coerce::isBlank(false);    // false
Coerce::isBlank('');       // true
Coerce::isBlank('   ');    // true
Coerce::isBlank(null);     // true
Coerce::isBlank([]);       // true

if (Coerce::isPresent($input)) {
    // We have a real, meaningful value
}

// String value matching int-backed enum
$priority = Coerce::toEnum('2', Priority::class); // Priority::Medium

// Enum instance passed through unchanged
$same = Coerce::toEnum(Status::Active, Status::class); // Status::Active

// Unknown value, returns null instead of throwing
$unknown = Coerce::toEnum('deleted', Status::class); // null

// Safe decimal strings for bcmath — no floating-point drift
$price    = Coerce::toBcDecimal($row['price'], 2);    // '1234.56'
$tax_rate = Coerce::toPercent($row['tax_rate']);       // 0.2 from '20%' or 20

if ($price !== null && $tax_rate !== null) {
    $tax = bcmul($price, (string) $tax_rate, 2);       // '246.91'
}

$email = Coerce::from($request->input('email'))->toNullIfBlank();

if ($email !== null && ! Coerce::isEmail($email)) {
    throw new ValidationException('Invalid email address.');
}

$website = Coerce::from($request->input('website'))->toNullIfBlank();

if ($website !== null && ! Coerce::isUrl($website)) {
    throw new ValidationException('Invalid URL.');
}

// JSON payload with mixed types — coerce all IDs to integers
$ids = Coerce::coerceEach($request->input('ids'), fn($v) => Coerce::toInteger($v));
// null if 'ids' is not array-like, or [1, 2, 3] after coercion

// Filter out nulls after coercion
$validIds = array_filter($ids ?? [], fn($v) => $v !== null);

$page     = Coerce::from($request->input('page'))->toPositiveIntOr(1);   // min page 1
$offset   = Coerce::from($request->input('offset'))->toUnsignedIntOr(0); // no negatives
$perPage  = Coerce::from($request->input('per_page'))->toPositiveIntOr(25);
bash
composer