michael-rubel / nullify
Convert empty data of any type to null.
Fund package maintenance!
paypal.com/donate/?hosted_button_id=KHLEL8PFS4AXJ
Requires
- php: ^8.0
Requires (Dev)
- illuminate/support: *
- infection/infection: ^0.26
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^9.5|^10.5
- roave/backward-compatibility-check: ^7.0|^8.0
- symfony/var-dumper: ^5.4|^6.1
README
Nullify
A plain PHP class to convert empty data of any type to null
PHP ^8.0
is required to use this class.
Installation
composer require michael-rubel/nullify
Usage
use MichaelRubel\Nullify\Nullify; Nullify::the($value);
- Note: the class checks also nested iterables and ArrayAccess objects.
Examples
$value = null; Nullify::the($value); // null $value = ''; Nullify::the($value); // null $value = []; Nullify::the($value); // null $value = (object) []; Nullify::the($value); // null $value = new \stdClass; Nullify::the($value); // null
⚡ Check nested elements:
$values = new Collection([ 'valid' => true, 'empty_array' => [], 'empty_string' => '', 'collection' => new Collection([ 'invalid' => new \stdClass, ]) ]); Nullify::the($values); // Illuminate\Support\Collection^ {#459 // #items: array:4 [ // "valid" => true // "empty_array" => null // "empty_string" => null // "collection" => Illuminate\Support\Collection^ {#461 // #items: array:1 [ // "invalid" => null // ] // #escapeWhenCastingToString: false // } // ] // #escapeWhenCastingToString: false // }
📚 If you use Laravel Collections, you can make a macro:
Collection::macro('nullify', function () { return $this->map(fn ($value) => Nullify::the($value)); }); collect(['', [], (object) [], new \stdClass, '✔']) ->nullify() ->toArray(); // [0 => null, 1 => null, 2 => null, 3 => null, 4 => '✔']
Testing
composer test
License
The MIT License (MIT). Please see License File for more information.