nette / safe
🛡 PHP functions rewritten to throw exceptions instead of returning false or triggering errors.
Installs: 331 987
Dependents: 6
Suggesters: 0
Security: 0
Stars: 17
Watchers: 14
Forks: 1
Open Issues: 0
Requires
- php: >=7.1
Requires (Dev)
- nette/tester: ^2.2
- phpstan/phpstan: ^0.12
- tracy/tracy: ^2.3
This package is auto-updated.
Last update: 2024-12-09 00:48:17 UTC
README
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: