1tomany / get-safely
A simple library to safely get scalar types from values of unknown origin or type
Installs: 19
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 0
Forks: 0
Open Issues: 0
pkg:composer/1tomany/get-safely
Requires
- php: >=8.4
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.82
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^12.2
README
This simple library exposes several PHP functions that assist with static analysis by ensuring values of unknown or mixed types are a scalar type.
Installation
composer require 1tomany/get-safely
Functions
get_string(): string
This function returns the $value argument if it is a string or implements the \Stringable interface, otherwise it returns the value of the $default argument. If the $default argument is of type callable, the $value is passed to it and the result of the callable is returned. An exception is thrown if the callable does not return a string.
Arguments
mixed $valuestring|callable $default = ''
get_string_loose(): string
This function is identical to get_string() except the $value argument is first cast to a string if it is a scalar value (boolean, int, float, or string in PHP).
Arguments
mixed $valuestring|callable $default = ''
Examples
<?php use function OneToMany\Getters\get_string; use function OneToMany\Getters\get_string_loose; // // get_string() Examples // // string(0) "" get_string(null); // string(3) "Vic" get_string('Vic'); // string(4) "nope" get_string(null, 'nope'); // string(8) "callable" get_string(null, fn ($v) => 'callable'); // string(3) "Vic" get_string(new class('Vic') implements \Stringable { function __construct(public readonly string $name) { } public function __toString(): string { return $this->name; } }, 'Neil'); // // get_string_loose() Examples // // string(0) "" get_string_loose(null); // string(1) "1" get_string_loose(true); // string(0) "" get_string_loose(false); // string(2) "10" get_string_loose(10); // string(4) "3.14" get_string_loose(3.14); // string(3) "Vic" get_string_loose([], 'Vic');
Credits
License
The MIT License