ket-php/utils-safe

Lightweight PHP utility for safely accessing variables, handling undefined values, and converting values to boolean without errors.

Installs: 5

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/ket-php/utils-safe

1.2 2025-12-09 09:09 UTC

This package is auto-updated.

Last update: 2025-12-09 11:03:02 UTC


README

Packagist Version Packagist Downloads Static Badge

Installation

Install via Composer:

composer require ket-php/utils-safe

Usage

Safe:

use KetPHP\Utils\Safe;
use KetPHP\Utils\Common\Cast;

// Simple value
$value = Safe::get('Hello'); 
echo $value; // Hello

// Value with default
$value = Safe::get(null, 'Default'); 
echo $value; // Default

// Using a callable
$value = Safe::get(fn() => 123); 
echo $value; // 123

// Transform only if value exists
$value = Safe::get('  John  ', 'Unknown', fn($v) => trim($v));
echo $value; // John

// Transform string function
$value = Safe::get('  John  ', 'Unknown', 'trim');
echo $value; // John

// Default value ignores transform
$value = Safe::get(null, 'Fallback', fn($v) => strtoupper($v));
echo $value; // Fallback

// Optional casting
$value = Safe::get('123', null, null, Cast::INT); 
echo $value; // 123 (integer)

$data = ['known' => 'value'];

// Without null coalescing
// WARNING: PHP would normally trigger a Notice (Undefined index)
$value = Safe::get($data['unknown'], 'Default');
echo $value; // Default (PHP Notice / E_USER_WARNING is triggered)

// You can suppress the warning using the @ operator
$value = Safe::get(@$data['unknown'], 'Default');
echo $value; // Default (no warning)

// With null coalescing
// Safe and no warning
$value = Safe::get($data['unknown'] ?? null, 'Default');
echo $value; // Default

Constants for Casting:

Constant Description
Cast::INT Cast to integer
Cast::FLOAT Cast to float
Cast::STRING Cast to string
Cast::BOOLEAN Cast to boolean
Cast::ARRAY Cast to array
Cast::OBJECT Cast to object

Truth:

use KetPHP\Utils\Truth;

// Non-strict mode (default)
var_dump(Truth::of(1)); // true
var_dump(Truth::of('on')); // true
var_dump(Truth::of('no')); // false
var_dump(Truth::of(null)); // false

// Strict mode
//
// In strict mode, any truthy list is ignored (both global and per-call custom lists). The ONLY values considered true are: 1, '1', true, 'true'
var_dump(Truth::of('true', true)); // true
var_dump(Truth::of('on', true)); // false
var_dump(Truth::of(1, true)); // true
var_dump(Truth::of(0, true)); // false

// Using a callable
var_dump(Truth::of(fn() => 'yes')); // true
var_dump(Truth::of(fn() => 'no')); // false

// Custom truthy list for a single call
$custom = ['foo', 'bar', 123];

var_dump(Truth::of('foo', false, $custom)); // true
var_dump(Truth::of('baz', false, $custom)); // false

// Configure global truthy values
Truth::configure(['sure', 'ok']);

var_dump(Truth::of('ok')); // true
var_dump(Truth::of('yes')); // false (old default removed)