nette/safe

🛡 PHP functions rewritten to throw exceptions instead of returning false or triggering errors.

v0.9 2019-12-11 17:44 UTC

This package is auto-updated.

Last update: 2024-10-09 00:16:54 UTC


README

Downloads this Month Build Status Latest Stable Version License

PHP functions smarten up to throw exceptions instead of returning false or triggering errors.

Good programmers do not ignore the errors

At least they shouldn't. PHP is a language with a relatively lax approach to errors, and therefore it requires the programmer to make more effort in handling them. Almost all PHP functions report errors using a return value, and the programmer must constantly check them for error states. There is a risk of forgetting it. Example:

// we are making copy of file
copy('/oldfile', '/newfile');
unlink('/oldfile');

If the first line fails, the file is permanently deleted. It would be much more useful if PHP throws an exception.

The problem of return values is also that it is not clear exactly what error occurred. Conversely eceptions have a text message and optionally an error code.

The solution is Nette\Safe

The use is extremely simple. Before each PHP function that should throws an exception instead of a warning, simply type Safe:

use Nette\Safe;

// we are making copy of file
Safe::copy('/oldfile', '/newfile');
Safe::unlink('/oldfile');

If the first line fails, exception Nette\Safe\FilesystemException is thrown and the file is not deleted.

Installation

composer require nette/safe

It requires PHP version 7.1 and supports PHP up to 7.4.

Exceptions

Nette\Safe throws exception Nette\Safe\Exception. For finer resolution you can catch its descendants, click to see:

Function & Exception List