thecodingmachine/safe
Safe PHP functions: a drop-in wrapper around PHP’s native functions that converts warnings and notices into exceptions, improving type safety and error handling. Includes namespaced alternatives for many standard functions with IDE/static analysis support.
composer require thecodingmachine/safe — the package is lightweight (≈1MB) with no external dependencies beyond PHP ≥7.4.Safe\ equivalents. For example:
// Before (prone to silent failure)
$data = file_get_contents('config.json');
if ($data === false) { /* handle error */ }
// After (explicit exception)
try {
$data = Safe\file_get_contents('config.json');
} catch (Safe\Exception $e) {
logger()->error('Failed to load config', ['exception' => $e]);
throw new ConfigLoadException($e->getMessage(), 0, $e);
}
Safe\file_get_contents, Safe\fopen), JSON (Safe\json_decode), and string functions (Safe\sprintf) — these show the biggest ergonomics improvement.Safe\ prefix) to identify candidates — functions that return false or emit warnings are ideal. Prioritize critical paths (e.g., config loading, auth token validation).use Safe;
class ConfigService
{
public function load(string $file): array
{
return Safe\json_decode(
Safe\file_get_contents($file),
true
);
}
}
Safe\ErrorException (implements \Safe\Exception) to attach extra context:
try {
return Safe\json_decode($raw, true);
} catch (Safe\Exception $e) {
throw new JsonDecodingException($e->getMessage(), $e->getCode(), $e, ['file' => $file]);
}
expectThrows or custom assertions to validate exception triggers in integrations.\Safe\Exception (strictly typed), not Error. Use instanceof Safe\Exception for catching, not generic Throwable.Safe\ is PSR-4 autoloaded, but verify vendor/composer/installed.php has it./** @return non-empty-string */ or use @phpstan-assert annotations for wrapped calls.@-operator with Safe functions — suppressing exceptions defeats the purpose. If unavoidable, use try { ... } catch { ... } inside @ to preserve context.Safe\functions\functions.php as a reference — implement in Safe\MyApp\MyFunc() to avoid conflicts.phpstan with safe extension (via extension=safe.so if compiled, or via auto-prepend) to detect false returns in Safe function callers.How can I help you explore Laravel packages today?