Skip to content

mll-lab/php-utils

Repository files navigation

php-utils

.github/workflows/format.yml .github/workflows/release.yml .github/workflows/validate.yml Code Coverage

Latest Stable Version Total Downloads

Shared PHP utility functions of MLL

Installation

Install through composer

composer require mll-lab/php-utils

Usage

See tests.

SafeCast

PHP's native type casts like (int) and (float) can produce unexpected results, especially when casting from strings. The SafeCast utility provides safe alternatives that validate input before casting:

Each type has two variants:

  • toX(): returns the cast value or throws \InvalidArgumentException
  • tryX(): returns the cast value or null (like Enum::tryFrom())
use MLL\Utils\SafeCast;

// Safe integer casting
SafeCast::toInt(42);           // 42
SafeCast::toInt('42');         // 42
SafeCast::toInt('hello');      // throws InvalidArgumentException
SafeCast::tryInt('hello');     // null

// Safe float casting
SafeCast::toFloat(3.14);       // 3.14
SafeCast::toFloat('3.14');     // 3.14
SafeCast::toFloat('abc');      // throws InvalidArgumentException
SafeCast::tryFloat('abc');     // null

// Safe string casting
SafeCast::toString(42);        // '42'
SafeCast::toString(null);      // ''
SafeCast::tryString([1, 2]);   // null

// Safe boolean casting
SafeCast::toBool(true);        // true
SafeCast::toBool(1);           // true
SafeCast::toBool('0');         // false
SafeCast::toBool('true');      // throws InvalidArgumentException
SafeCast::tryBool('true');     // null

See tests for more examples.

Holidays

You can add custom holidays by registering a method that returns a map of holidays for a given year. Set this up in a central place that always runs before your application, e.g. a bootstrap method.

use MLL\Holidays\BavarianHolidays;

BavarianHolidays::$loadUserDefinedHolidays = static function (int $year): array {
    switch ($year) {
        case 2019:
            return ['22.03' => 'Day of the Tentacle'];
        default:
            return [];
    }
};

Custom holidays have precedence over the holidays inherent to this library.

PHPStan extension

This library provides a PHPStan extension that is either registered through PHPStan Extension Installer or registered manually by adding the following to your phpstan.neon:

includes:
+- vendor/mll-lab/php-utils/extension.neon
+- vendor/mll-lab/php-utils/rules.neon

Requires spaze/phpstan-disallowed-calls.

Changelog

See CHANGELOG.md.

Contributing

See CONTRIBUTING.md.

License

This package is licensed using the MIT License.

About

Shared PHP utility functions of MLL

Resources

License

Contributing

Stars

Watchers

Forks

Packages

 
 
 

Contributors