Question

I have a few plugins that start something like this:

namespace MyPlugin;

// If this file is called directly, abort.
if (! defined('WPINC')) {
    die;
}

/**
 * Define Constants
 *
 */

define(__NAMESPACE__ . '\NS', __NAMESPACE__ . '\\');

Now that I'm finally getting around to using PHP_Codesniffer to implement some PSR12 standards, I'm getting a warning:

A file should declare new symbols (classes, functions, constants, etc.) and cause no other side effects, or it should execute logic with side effects, but should not do both. The first symbol is defined on line 48 and the first side effect is on line 38.

I notice that Advanced Custom Fields, which I imagine is a pretty good standard, also breaks that recommendation:

if( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

Obviously I could ignore the warning, for example by wrapping it in // phpcs:disable and // phpcs:enable as per Codesniffer docs, but what would be an elegant way to adhere to it?

Was it helpful?

Solution

As fuxia says, the most elegant way to adhere to the rule is to just not include that code. If a file is written properly then it's not required to be safe.

Keep in mind that PSR12 is just one set of standards, and WordPress and many plugins do not follow it. They are more likely to follow the WordPress coding standards, which do not include this rule, I believe (there is a PHP CodeSniffer ruleset for WordPress's standards available here, if you want to go in that direction). Reasonably well written WordPress code and plugins are not necessarily going to adhere to PSR12, which means that if you follow their style your code will probably not adhere to PSR12.

It's up to you whether you'd prefer to follow PSR12 strictly, or make use of common WordPress patterns. In the vast majority of cases you will be fine using PSR12, your code will just look different to other code in the WordPress ecosystem.

However, there is an advantage of using the WordPress coding standards, which is that those are aware of WordPress's functions, so they will recognise things like whether you are properly escaping and sanitising using WordPress's own functions, for example.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top