michael-rubel/nullify

Convert empty data of any type to null.

1.0.3 2024-03-18 17:34 UTC

This package is auto-updated.

Last update: 2024-11-06 18:17:41 UTC


README

Convert empty data of any type to null

Nullify

tests infection backward-compat phpstan

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);

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.