Download the PHP package 1tomany/nullify without Composer
On this page you can find all versions of the php package 1tomany/nullify. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package nullify
String Nullifier for PHP
This simple library exposes a single function named nullify() in the global namespace. By default, the function trims the string passed into it and returns null if the trimmed value is an empty string, or the trimmed string otherwise.
Installation
Usage
The nullify() function has the following signature:
If the $trim argument is set to false, the string is not trimmed. An empty string will still return null, otherwise, the original string is returned. If an object implementing \Stringable is passed in, the object will be converted to a string first.
Purpose
Dealing with falsy and empty values in PHP has always been a challenge. If you've used the language long enough, you've probably been bitten by empty('0') returning true even though the string '0' clearly isn't empty. My preference is to typehint strings as non-empty-string|null to clearly indicate what kinds of values that variable holds.
Take the following basic DTO as an example:
Because of the ambiguity of the $name property, it's cumbersome to determine if it is empty or not:
For all practical purposes, $name is empty, but determining that is cumbersome.
A much clearer DTO would be written like this:
It's immediately clear what data $name holds, and testing if $name is empty or not is a cinch:
These are also clear because nullify() has removed any ambiguity around falsy or empty values:
Examples
$string |
$trim |
nullify() |
|---|---|---|
null |
true |
null |
'' |
true |
null |
'' |
false |
null |
' ' |
true |
null |
' ' |
false |
' ' |
'0' |
true |
'0' |
'0' |
false |
'0' |
' 0 ' |
true |
'0' |
' 0 ' |
false |
' 0 ' |
' PHP ' |
true |
'PHP' |
' PHP ' |
false |
' PHP ' |
' 🐘🎉 ' |
true |
'🐘🎉' |
Credits
License
The MIT License