phpstan / phpstan-strict-rules

Extra strict and opinionated rules for PHPStan
MIT License
592 stars 46 forks source link

Add rule to disallow error control operator #230

Closed o0h closed 11 months ago

o0h commented 11 months ago

Overview

This Pull Request introduces a new static analysis rule that prohibits the use of PHP's error control operator (@).

Specification

This rule will flag lines of code that use the error control operator @, issuing a warning or error for that line.

Background and Motivation

The error control operator is frequently misused, often exceeding its appropriate scope, to ignore or suppress errors. This misuse is well-known for posing risks that can degrade the quality of application code and complicate debugging.

By adding this new rule, we believe the following benefits can be achieved:

  1. Encourage the practice of proper error handling and clearer coding.
  2. Prevent the decrease in debuggability due to the use of the error control operator.

I believe that this rule will help PHPStan users to adopt a more strict coding style, thereby assisting in the development of more reliable software.

ondrejmirtes commented 11 months ago

Hello, thank you for your effort, but I disagree with the premise.

1) More often than not, you need @ for writing safer code. Like doing @file_get_contents('foo.txt') and then checking if the result is !== false. 2) You can configure your error handler to ignore the fact that an error is suppressed with @ and still report such error.

So I think for a safer application you can still use @ in the code but if you want to about the error you want suppressed, you can configure your error handler with https://www.php.net/manual/en/function.set-error-handler.php.

If you still want this rule for your own purposes, I encourage you to publish it as your own package, or perhaps configure this package https://github.com/ekino/phpstan-banned-code to achieve the same thing.

o0h commented 11 months ago

Thank you! It makes sense now that I understand that this feature was not included in the package by design. Maybe what I suggested was a bit of a niche demand. And phpstan-banned-code seems like a great package! Thanks for the introduction. It's good to know about it.