Shared PHP utility functions of MLL
Install through composer
composer require mll-lab/php-utilsSee tests.
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\InvalidArgumentExceptiontryX(): returns the cast value ornull(likeEnum::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'); // nullSee tests for more examples.
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.
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.neonRequires spaze/phpstan-disallowed-calls.
See CHANGELOG.md.
See CONTRIBUTING.md.
This package is licensed using the MIT License.