WordPressCS 3.0.0 is now available

A wapuu in a dark grey hoodie using a silver coloured laptop with the WordPress logo on the laptop cover.
Image credits: Marktimemedia

This post announces the immediate availability of the long-awaited WordPressCS 3.0.0 release.

This is an important release which makes significant changes to improve the accuracy, performance, stability and maintainability of all sniffssniff A module for PHP Code Sniffer that analyzes code for a specific problem. Multiple stiffs are combined to create a PHPCS standard. The term is named because it detects code smells, similar to how a dog would "sniff" out food., as well as makes WordPressCS much better at handling modern PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher.

Most rules which were proposed in the Make post from March 2020 have been added to the Coding standards guidelines.
Proposed rules which yielded a lot of discussion or to which objections were raised, have not been added.
The intention is to publish separate Make posts for each of these over time, to discuss these more controversial proposals further.

For a large number of the new rules, sniffs have been added to WordPressCS to enforce these rules.
More sniffs may be added in future WordPressCS releases to comprehensively cover the new and updated rules.

New architecture

WordPressCS previously had only one runtime dependency, which was PHP_CodeSniffer and end-users would need to manually register WordPressCS with PHP_CodeSniffer (or use a Composer pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party to do so).

As of WordPressCS 3.0.0, WordPressCS will have four run-time dependencies and because of this, Composer will be the only supported way to install WordPressCS.

Mind: it is still perfectly possible to install WordPressCS and its dependencies without using Composer. It is just not an installation method for which support will be provided.

The image shows the new architecture of WordPressCS 3.0.0.

Everything is build on top of PHP_CodeSniffer - which comes with the Generic, PEAR, PSR1, PSR2, PSR12, Squiz, and Zend standards.

On top of PHP_CodeSniffer, there is the PHPCSUtils package.

And then there are the WordPressCS and PHPCSExtra packages which both  are build on top of PHPCSUtils.

WordPressCS comes with the WordPress, WordPress-Core, WordPress-Extra and WordPress-Docs rulesets.

PHPCSExtra comes with the Universal, NormalizedArrays and Modernizer rulesets.

To the side of this stack, it shows another package: the Composer PHPCS Plugin.
This package makes sure that all external standards are automatically and correctly registered with PHP_CodeSniffer.

PHPCSUtils is a set of utility functions for use with PHP_CodeSniffer.
PHPCSExtra is an additional set of sniffs.
Composer Installer is a Composer plugin which will make sure that WordPressCS, PHPCSUtils as well as PHPCSExtra will be registered correctly with PHP_CodeSniffer.

New, non-WordPress-specific, sniffs will now be added to PHPCSExtra, while all WordPress-specific sniffs continue to be maintained in WordPressCS.
Some of the pre-existing WordPressCS sniffs, which could benefit the wider PHP community, have been removed and replaced by similar (and improved!) sniffs which were added to PHPCSExtra.

Upgrading to WordPressCS 3.0.0

WordPressCS 3.0.0 contains breaking changes, both for people using ignore annotations, people maintaining custom rulesets, as well as for sniffsniff A module for PHP Code Sniffer that analyzes code for a specific problem. Multiple stiffs are combined to create a PHPCS standard. The term is named because it detects code smells, similar to how a dog would "sniff" out food. developers who maintain a custom PHPCSPHP Code Sniffer PHP Code Sniffer, a popular tool for analyzing code quality. The WordPress Coding Standards rely on PHPCS. standard based on WordPressCS.

Aside from the changelog, WordPressCS 3.0.0 comes with detailed upgrade guides for both end-users/ruleset maintainers as well as a separate upgrade guide for developers who have built a coding standard on top of WordPressCS.

Please read the provided documentation carefully before you upgrade.

WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. will upgrade to WordPressCS 3.0.0 in the near future as well. Follow TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. ticketticket Created for both bug reports and feature development on the bug tracker. #59161 if you want to stay informed and be sure to run composer update --with-all-dependencies once the patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing. has been committed to benefit from the latest & greatest sniff goodies.

Why did it take so long for this release to be “ready” ?

This release is basically the result of four big projects combined. It wasn’t necessarily the intention when work on WordPressCS 3.0.0 started that these projects would be combined into one release, but internal and external influences had an impact on timing, which made it so.

Also, please keep in mind that this project is basically maintained by a very, very small group of unpaid volunteers, who also have real jobs to do.

The four big projects we are talking about are:

  1. A big refactor.
  2. Adding new rules based on the Make post from March 2020.
  3. Making the sniffs compatible with PHP 7.4, 8.0, 8.1 and 8.2 (* 8.2 in so far currently possible as PHP_CodeSniffer doesn’t fully support all 8.2 syntaxes yet).
  4. Improving the available documentation.

Now let’s talk a little about each of these.

The refactor

WordPressCS previously had only one runtime dependency, which was PHP_CodeSniffer and end-users would need to manually register WordPressCS with PHP_CodeSniffer (or use a Composer plugin to do so).
PHP_CodeSniffer offers some limited “utility” functions for sniffs and some basic abstracts.

But… WordPressCS – and other external standards, like PHPCompatibility – wanted more utility functions and better abstracts to be available, so these projects added their own and these utilities then had to be maintained in each of those projects.

To improve this situation, it was originally proposed for the non-standard specific utilities to be added to PHP_CodeSniffer. After nearly a year of work on this, lots of discussion and waiting, it was eventually decided in the summer of 2019 that these utilities should live in a separate project.

Moving this work to a separate project was a setback and meant having to rework a lot.
This separate project was published as PHPCSUtils in January 2020.

By that time, PHP 8.0 also started to come into play and it was becoming very clear that this would involve lots of changes for Coding Standards projects and both PHP_CodeSniffer, as well as the utilities, would have to be made compatible with PHP 8.0 before a new version of WordPressCS could be released.

In practical terms, most non-WordPress-specific utility functions are now available via PHPCSUtils.
The remaining utility functions, i.e. the few exceptions + the WordPress-specific utilities, have all been moved to separate “helper” classes and traits to make the code more re-usable for sniffs not based on the WordPressCS specific base Sniff class.

New rules

The Make post from March 2020 proposed a lot of new rules, which resulted in a healthy discussion on the post and save for a few rules, most of the new rules met with approval.

This meant two things:

  1. Research needed to be done whether there were any pre-existing sniffs that could be used to implement the approved rules.
  2. For anything for which no sniff existed, a new sniff would need to be written.

A whopping 35 new sniffs were written for this release, 32 of these were added to PHPCSExtra, and 3 to WordPressCS itself.

To see a list of all the rules included in a particular standard, use:

vendor/bin/phpcs -e --standard=WordPress

(you can replace WordPress with, for instance, WordPress-Core or Universal or PSR12 to see the sniffs included in a particular standard)

Making sniffs compatible with PHP 7.4, 8.0, 8.1 (and 8.2)

Making a PHP project compatible with a new PHP version is one thing, doing so for a static analysis tool is something else altogether.

Making sniffs compatible with a new PHP version, basically involves three things:

  1. Making sure the existing code will run on the new PHP version without errors or notices.
  2. Making sure that sniffs do not throw a false positive/negative when confronted with a new syntax.
    Example: if a sniff looks for function calls to analyse and excludes method calls – function calls preceded by a -> or :: -, for PHP 8.0, these sniffs needed to be adjusted to also exclude function calls preceded by the nullsafe object operator ?->.
  3. Add explicit support for new PHP features.
    Example: if a sniff would examine the name of a class-like structure, like a class, interface, or trait, the sniff would probably benefit from new code to also examine the names of PHP 8.1 enum structures.

Now, aside from 1, for 2 and 3, WordPressCS has a BIG dependency on PHP_CodeSniffer itself as PHP_CodeSniffer needs to support the new syntaxes first before an individual sniff can start to support them.

At the time work started for WordPressCS 3.0.0, PHP_CodeSniffer didn’t fully support PHP 7.4 yet, which added quite some new syntaxes and then PHP 8.0, 8.1 and 8.2 came along adding yet even more.

PHP 7.4, 8.0, 8.1, 8.2 added more new syntaxes to PHP than all of the PHP 5 and 7 releases before it combined.

Now you may ask yourself: “Why should the sniffs take all those new PHP syntaxes into account ?” After all, WordPress still supports PHP 7.0 (PHP 5.6 prior to WP 6.3), so those syntaxes cannot be used in code written for WordPress Core…

Well, the WordPress Coding StandardsWordPress Coding Standards The Accessibility, PHP, JavaScript, CSS, HTML, etc. coding standards as published in the WordPress Coding Standards Handbook. May also refer to The collection of PHP_CodeSniffer rules (sniffs) used to format and validate PHP code developed for WordPress according to the PHP coding standards. are a community standard and WordPressCS codifies this into automated checks and as such, WordPressCS is not only used by WordPress Core, but also by the wider WordPress community, including agencies, plugin and theme authors etc.
And plugins and themes may have a higher minimum supported PHP version, especially when we’re talking in-company/closed source plugins and themes.

Aside from that, sooner or later, WP will raise the minimum supported PHP version to a version including these new syntaxes, so the work would need to be done anyway and it’s easier to do this when what’s changed in PHP is still fresh in our minds.

So, a new waiting game started, where PHPCS needed to be updated first, then PHPCSUtils and only then could support for the new syntaxes be added to WordPressCS.

Safe for the PHP 8.2 Disjunctive Normal Form Types, which isn’t supported yet by PHP_CodeSniffer itself, all new syntaxes which were introduced in recent PHP versions are now taken into account in all sniffs in as far as our (my) imagination reached.

If you run into a situation where a sniff appears to not be fully compatible with modern PHP syntaxes yet, please open a bug report.

Improving the documentation

PHPCS has a built-in sniff documentation feature. Until recently, WordPressCS didn’t really support this feature and WordPress sniffs didn’t provide the documentation needed.

A start was made to add documentation to sniffs during the contributor dayContributor Day Contributor Days are standalone days, frequently held before or after WordCamps but they can also happen at any time. They are events where people get together to work on various areas of https://make.wordpress.org/ There are many teams that people can participate in, each with a different focus. https://2017.us.wordcamp.org/contributor-day/ https://make.wordpress.org/support/handbook/getting-started/getting-started-at-a-contributor-day/. at WordCampWordCamp WordCamps are casual, locally-organized conferences covering everything related to WordPress. They're one of the places where the WordPress community comes together to teach one another what they’ve learned throughout the year and share the joy. Learn more. Europe 2019.

This effort has continued during the WordPressCS 3.0.0 cycle and the majority of sniffs used by and provided by WordPressCS now include documentation with code samples of what a sniff expects.

To view the documentation for any of the included standards use:

vendor/bin/phpcs --generator=Text --standard=WordPress

(you can replace WordPress with, for instance, WordPress-Core or Universal or PSR12 to see the documentation for other standards)

The future of WordPressCS

While WordPressCS is currently in a good place with this release, this won’t last long with the pace at which PHP is going.

WordPressCS 3.0.0 has costs thousands of hours of work and the vast majority of work has been done by one, mostly unpaid, contributor, with code review support from two fellow maintainers.

If we are being realistic, the bus factor of WordPressCS is 1, which is the most dangerous situation for any project to be in.

A large part of the WordPress community, including WordPress Core, relies heavily on the WordPress Coding Standards for code quality and security checks and while the community has been pretty vocal with copious complaints about the delayed release, barely anyone has stepped up and actually contributed.

The majority of the work for WordPressCS requires specialized knowledge. Knowledge which can be learned with enough time investment, but in recent years nobody has stepped up to do so.

This is an unsustainable situation and it ends now.

Unless funding is found to continue maintaining WordPressCS and its dependencies, the future is bleak and maintenance will be halted.

Let this be a call to action for the corporate/agency users of WordPressCS to come together and figure out a way to fund the continued maintenance and development of WordPressCS as that one person on which the whole project, including all dependencies, leans, is done with the current status quo.

If you want to help change this situation, please reach out to the WordPressCS maintainer team (@jrf, @GaryJ, @dingo_d) via WordPress SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. to discuss.

Props to @GaryJ, @dingo_d and @milana_cap for reviewing the post before publication.

#modernizewp, #codingstandards, #php, #wpcs

Proposal: Disallow assignments in conditions and remove the Yoda condition requirement for PHP

After discussion with several coreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. committers and WordPress leads, the title and the contents of the text were changed to clarify that this is a proposal and not a decision set in stone.

This proposal is the continuation of the long discussion on the WordPress Coding Standards (WPCS) repo.

Yoda conditions (or Yoda notation) is the programming style where the parts of an expression in the condition are reversed from the ‘typical’ order.

In a large part of the world, the natural reading order is left to right (LTR). This is what most programming languages adhere to. That means the variable assignments or echo/print statements are written with the variable first:

$post_type = 'post';

echo $post_type;

With the same idea in mind, conditions can also be written left to right, like:

if ( $post_type == 'post' ) {
    $category = get_the_category();
}

With Yoda conditions applied, the above condition would be written as:

if ( 'post' == $post_type ) {
    $category = get_the_category();
}

The idea behind it is that writing the value on the left side of the condition will prevent accidentally assigning the value to the variable since assignments can’t be made to values.

if ( $post_type = 'post' ) {
    $category = get_the_category();
}

While seemingly helpful at first glance, the obvious problem with them is the decreased readability of code, especially for people with reading disabilities such as dyslexia.

How we got here

When the handbook rule about Yoda conditions was introduced there was barely any static analysis tooling available in the PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher world. The only ‘foolproof’ way to prevent accidental assignment in conditions was to invert the order of the value being checked and the variable.

Automated checking for assignments in conditions via PHP_CodeSniffer (PHPCSPHP Code Sniffer PHP Code Sniffer, a popular tool for analyzing code quality. The WordPress Coding Standards rely on PHPCS.), the underlying tooling for WPCSWPCS The collection of PHP_CodeSniffer rules (sniffs) used to format and validate PHP code developed for WordPress according to the WordPress Coding Standards. May also be an acronym referring to the Accessibility, PHP, JavaScript, CSS, HTML, etc. coding standards as published in the WordPress Coding Standards Handbook., became available in 2017. Moreover, the current sniffsniff A module for PHP Code Sniffer that analyzes code for a specific problem. Multiple stiffs are combined to create a PHPCS standard. The term is named because it detects code smells, similar to how a dog would "sniff" out food. enforcing Yoda condition in the WPCS doesn’t protect against accidental assignments in conditions.

Today there is tooling in place that can help with identifying assignments in conditions, making the Yoda rules obsolete.

Keep in mind that strict comparisons (===) are already strongly encouraged and a part of the WordPress-Core ruleset (warning), making accidental assignments even less likely.

A thorough analysis was made by Lucas Bustamante in the WPCS ticketticket Created for both bug reports and feature development on the bug tracker. on the impact this could have on the plugins in the WordPress directory. The analysis showed that Yoda conditions are used in 18.02% of the plugins, so the majority of pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party developers are using non-Yoda conditions.

What to do next?

The discussion in the WPCS ticket is long and opinionated, but comes down to these points:

Disallow Yoda condition

  • Drop the handbook rule that requires Yoda conditions and instead explicitly disallow using them.

Remove Yoda condition as a requirement

  • Discourage, but don’t disallow Yoda conditions. Just don’t report if the code is or is not using Yoda conditions. The rule would also be dropped from the handbook.

In both cases, assignments in conditions will still be checked for and forbidden.

Impact on the Core code

Disallowing Yoda conditions for WordPress Core would mean that all existing patches on open tickets for Core would need to be revisited and fixed accordingly, which could burden the contributors.

Running the same analysis as Lucas did for plugins, over the WordPress Core, there were 5427 Yoda conditions, and 312 non-Yoda conditions.

Luckily, these are violations that can be automatically fixed using phpcbf tool, but care should be taken to check if all the violations were correctly fixed.

If Yoda conditions are discouraged (option 2), and the existing Yoda conditions in the Core code remain, that would mean less work for the Core contributorsCore Contributors Core contributors are those who have worked on a release of WordPress, by creating the functions or finding and patching bugs. These contributions are done through Trac. https://core.trac.wordpress.org., but also would add lots of inconsistencies in the Core code (mixed Yoda and non-Yoda conditions).

Next steps

The chosen way forward is to remove the Yoda condition as a requirement (remove it from the handbook) but not disallow it for the time being.

For WPCS, that would mean the removal of the Yoda conditions requirement (and sniff) in WPCS 3.0, with a notice that non-Yoda conditions will start to be required in WPCS 4.0 version.

Work is currently actively ongoing to prepare for the WPCS 3.0.0 release. There will be a minimum of six months between the 3.0.0 and the 4.0.0 release to allow time for Core and other projects to adjust.

Once WPCS 4.0.0 version is released, a one-time-only auto-fix of all the remaining Yoda conditions in Core will be made, and any patches to the Core which go in after that will have to use non-Yoda.

How to enforce the non-Yoda conditions in your code

If you are a WordPress plugin or theme developer, and you’d like to enforce non-Yoda conditions in your code, you can use the Generic.ControlStructures.DisallowYodaConditions sniff. In your phpcs.xml.dist file you should add the following sniff:

<?xml version="1.0"?>
<ruleset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" name="Example Project" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/squizlabs/PHP_CodeSniffer/master/phpcs.xsd">

    <!-- Your custom rules. -->

    <!-- Disallow Yoda conditions in your codebase. -->
    <rule ref="Generic.ControlStructures.DisallowYodaConditions"/>

</ruleset>

If you want to change the Yoda conditions to non-Yoda conditions, use the phpcbf tool (part of PHPCS) with the Slevomat coding standards. Specifically, the SlevomatCodingStandard.ControlStructures.DisallowYodaComparison sniff that has the fixer for the Yoda conditions.

Props to Juliette Reinders Folmer and Gary Jones for the proofreading and adding valuable feedback on the text. Also, a big props to Lucas Bustamante for the impact analysis on WordPress plugins.

#codingstandards, #php, #wpcs

Updating the Coding standards for modern PHP

Until May last year, contributions to WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. were bound to PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher 5.2 syntax and most plugins and themes stuck to the PHP 5.2 minimum requirement as well.

However, with the change to PHP 5.6 as the minimum PHP version for WordPress Core, new PHP features have become available for use in WP Core and with the outlook of a minimum version of PHP 7.x in the (near) future, even more interesting language features will soon become available for use in WordPress Core, plugins and themes.

With that in mind, we’d like to define coding standards for a number of these constructs and propose to implement automated checking for these in the WordPress Coding StandardsWordPress Coding Standards The Accessibility, PHP, JavaScript, CSS, HTML, etc. coding standards as published in the WordPress Coding Standards Handbook. May also refer to The collection of PHP_CodeSniffer rules (sniffs) used to format and validate PHP code developed for WordPress according to the PHP coding standards. tooling in the near future.

While it may still be a while before some of these features will actually be adopted for use in WordPress Core, defining the coding standards in advance will allow for a consistent code base when they do get adopted and will allow for plugins and themes, which are not necessarily bound to the PHP 5.6 minimum, to safeguard their code consistency when they start using more modern PHP already.

To be honest, none of these proposals are terribly exciting and some may not even seem worth mentioning. Most follow either prior art in WordPress Core or industry standards for the same, but in the spirit of openness, we’d like to verify our take on these before implementing them.

Continue reading

#modernizewp, #codingstandards, #php, #wpcs

PHP Coding Standards Changes

This is a follow-up to several changes proposed a few months ago.

While reading these changes, it’s important to keep in mind that they only apply to WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.: you can (and should) choose practices that best suits your development style for your own plugins and themes. The coding standards are intentionally opinionated, and will always lean towards readability and accessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility) over being able to use every possible language feature.

Closures (Anonymous Functions)

There was quite a lot of discussion around this proposal, particularly with regards to allowing closures as hook callbacks. Thank you everyone for your input, and for keeping disagreements respectful. 🙂

We do need a decision, however, and there were several key points that led to this:

  • It’s currently difficult to remove closures as hook callbacks. #46635 has several interesting proposals to address this in an entirely backward compatible manner.
  • While WordPress Core should strive to allow any callback to be unhooked, plugins have no such restriction.
  • The WordPress JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. Coding Standards allow for closures to be used, we should be aiming to bring the PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher standards in line with that.
  • The broader PHP world has embraced closures for many years, and have found ways to use them responsibly. We shouldn’t ignore PHP usage outside of WordPress.

With these points in mind, a conservative, but practical step is to allow closures as function callbacks, but not as hook callbacks in Core. Ultimately, we should be able to allow any sort of complex callback to be attached to hooksHooks In WordPress theme and development, hooks are functions that can be applied to an action or a Filter in WordPress. Actions are functions performed when a certain event occurs in WordPress. Filters allow you to modify certain functions. Arguments used to hook both filters and actions look the same., but the Core APIs aren’t quite ready for it yet.

Coding Standards Change

Where appropriate, closures may be used as an alternative to creating new functions to pass as callbacks.

Closures must not be passed as filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. or action callbacks, as they cannot be removed by remove_action() / remove_filter() (see #46635 for a proposal to address this).

Short Array Syntax

A little less controversial, but still with varying opinions, was the proposal to require short array syntax ( [ 1, 2, 3 ] ) instead of long array syntax ( array( 1, 2, 3 ) ) for declaring arrays.

While I’m personally partial to short array syntax, there were two particularly convincing arguments for using long array syntax:

  • It’s easier to distinguish from other forms of braces, particularly for those with vision difficulties.
  • It’s much more descriptive for beginners.

So, this change to the coding standards is the opposite of what was originally proposed, but is ultimately the more inclusive option.

Coding Standards Change

Arrays must be declared using long array syntax in WordPress Core.

Short Ternary Operator

The original proposal was to allow the short ternary operator, but this change reverses that. There’s a good argument that it looks too much like the null coalesce operator, especially as they perform different functions.

Take the following example from Core:

$height = isset( $data['height'] ) ? $data['height'] : 0;

It’s not possible to reduce this line with the short ternary operator, but it can be trivially reduced with the null coalesce operator:

$height = $data['height'] ?? 0;

The vast majority of other ternary operators in Core (which don’t have an isset() test) look something like this:

$class = $thumb ? ' class="has-media-icon"' : '';

This also can’t be reduced using the short ternary operator.

As the null coalesce operator is a useful addition (which we’ll be able to use once the minimum PHP version bumps to 7+), whereas the short ternary operator can only be used in a handful of cases in Core, it’s better to avoid the potential confusion, and not use the short ternary operator.

Coding Standards Change

The short ternary operator must not be used.

Assignments Within Conditionals

Particularly when there are multiple conditions, it can be quite difficult to spot assignments occurring in a conditional. This arguably falls under the Clever Code guidelines, but hasn’t been formalised.

I got a little ahead of myself with this one, and have already removed all assignments in conditionals from Core. Adding this change to the standard formalises the practice.

Coding Standards Change

Assignments within conditionals must not be used.

#php, #wpcs

Coding Standards Updates for PHP 5.6

With the minimum PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher version increasing to 5.6 as of WordPress 5.2, now’s a good time to be reviewing the WordPress Coding StandardsWordPress Coding Standards The Accessibility, PHP, JavaScript, CSS, HTML, etc. coding standards as published in the WordPress Coding Standards Handbook. May also refer to The collection of PHP_CodeSniffer rules (sniffs) used to format and validate PHP code developed for WordPress according to the PHP coding standards..

Here is a set of changes that I’d like to propose.

Anonymous Functions (Closures)

Anonymous functions are a useful way to keep short logic blocks inline with a related function call. For example, this preg_replace_callback() call could be written like so:

$caption = preg_replace_callback(
	'/<[a-zA-Z0-9]+(?: [^<>]+>)*/',
	function ( $matches ) {
		return preg_replace( '/[\r\n\t]+/', ' ', $matches[0] );
	},
	$caption
);

This improves the readability of the codebase, as the developer doesn’t need to jump around the file to see what’s happening.

Coding Standards Proposal

Where the developer feels is appropriate, anonymous functions may be used as an alternative to creating new functions to pass as callbacks.

Anonymous functions must not be passed as filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output. or action callbacks in WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress., as they cannot be removed by remove_action() / remove_filter() (see #46635 for a proposal to address this). Outside of Core, developers may pass anonymous functions as filter or action callbacks at their own discretion.

Namespaces

Namespaces are a neat way to encapsulate functionality, and are a common feature in modern PHP development practices. As we’ve discovered in the past, however, introducing namespaces to the WordPress codebase is a difficult problem, which will require careful architecture and implementation.

Side note: there’s currently no timeline for introducing namespaces to WordPress Core, expressions of interest are welcome. 🙂

Coding Standards Proposal

At this time, namespaces must not be used in WordPress Core.

Short Array Syntax

Rather than declaring arrays using the array( 1, 2, 3 ) syntax, they can now be shortened to [ 1, 2, 3 ]. This matches how arrays are declared in the WordPress JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. Coding Standards.

To allow for plugins and themes that support older versions of WordPress, I’d like to propose that WordPress Core switches to short array syntax immediately, but plugins and themes may choose which they use. A future iteration would make short array syntax a requirement.

Coding Standards Proposal

Arrays must be declared using short array syntax in WordPress Core. Arrays may be declared using short array syntax outside of Core.

Short Ternary Syntax

A fairly common pattern when setting a variable’s value looks something like this:

$a = $b ? $b : $c;

The short ternary syntax allows this to be shortened, like so:

$a = $b ?: $c;

It’s important to note that this is different to the null coalesce operator, which was added in PHP 7. If $b is undefined, the short ternary syntax will emit a notice.

Coding Standards Proposal

Short ternary syntax may be used where appropriate.

Assignments within conditionals

While this isn’t directly related to the PHP version bump, I’d like to propose disallowing assignments within conditionals. Particularly when there are multiple conditions, it can be quite difficult to spot assignments occurring in a conditional. This arguably falls under the Clever Code guidelines, but hasn’t been formalised.

For example, this if statement would be written like so:

$sticky_posts = get_option( 'sticky_posts' );
if ( 'post' === $post_type && $sticky_posts ) {
	// ...
}

Coding Standards Proposal

Assignments within conditionals are not allowed.

Other New Features

Any other new features available in PHP 5.6 can be used, though we should continue to carefully consider their value and (in the case of newer PHP modules) availability on all hosts.


How do you feel about these changes? Are there other changes related to PHP 5.6 that you’d like to suggest?

#php, #wpcs

Dev Chat Summary: May 30th (4.9.7 week 2)

This post summarizes the dev chat meeting from May 30th (agenda, Slack archive).

4.9.7 planning

  • No pressing need for quick 4.9.7 release, so aiming for ~6-8 week release cycle for 4.9.7
  • Leads nominated so far: @sergeybiryukov able to help as deputy (e.g., committing, backporting); @danieltj, @desrosj, and @tristangemus open to help contribute during 4.9.7
  • Please comment on this post, pingPing The act of sending a very small amount of data to an end point. Ping is used in computer science to illicit a response from a target server to test it’s connection. Ping is also a term used by Slack users to @ someone or send them a direct message (DM). Users might say something along the lines of “Ping me when the meeting starts.” @jeffpaul, or comment during the next dev chat for nominations (self or otherwise) for release leads on 4.9.7

Updates from focus leads and component maintainers

  • The PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher team posted a summary from their meeting last week covering the “Upgrade PHP” page and possible GutenbergGutenberg The Gutenberg project is the new Editor Interface for WordPress. The editor improves the process and experience of creating new content, making writing rich content much simpler. It uses ‘blocks’ to add richness rather than shortcodes, custom HTML etc. https://wordpress.org/gutenberg/ blocks. Please join them this coming Monday, June 4th at 15:00 UTC in #core-php
  • The GDPR Compliance team met earlier today and of note will be changing the SlackSlack Slack is a Collaborative Group Chat Platform https://slack.com/. The WordPress community has its own Slack Channel at https://make.wordpress.org/chat/. channel and post tags to CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. Privacy this Friday, June 1st. Please join them next Wednesday, June 6th at 15:00 UTC in #core-privacy

Guidelines for fixing coding standard violations

  • Now that r42343 has landed, Core is accepting patches to fix coding standards (CS) violations. The meeting attendees agreed on the following guidelines:
    • Patches for any CS fixes are welcome, as long as they’re not so extensive that it would require refreshing an unreasonable amount of regular patches.
    • In order to avoid wasting time, patches for violations which cannot be automatically fixed by `phpcbf` should be given preference over ones that can be automatically fixed.
    • Regardless of many files are touched in a CS patchpatch A special text file that describes changes to code, by identifying the files and lines which are added, removed, and altered. It may also be referred to as a diff. A patch can be applied to a codebase for testing., the corresponding commits should be limited to fixing a single file in each commit.
    • CS patches should be treated just like any other patch, and reviewed critically before being committed. That also applies to any changes made by `phpcbf`.
    • Commits for new features, bugbug A bug is an error or unexpected result. Performance improvements, code optimization, and are considered enhancements, not defects. After feature freeze, only bugs are dealt with, with regressions (adverse changes from the previous version) being the highest priority. fixes, and other “logic” changes should not include unrelated CS fixes. Coding standards fixes should be done in a separate commit. If a line is already being changed to fix a bug, etc, then it should have CS violations fixed at the same time. If fixing the violation for that line would introduce changes beyond that line, though, then the CS fixes should be done in a separate commit.
  • Does anyone strongly object to those, before they’re added to Handbook?

General announcements

  • @danieltj has begun a proposal draft for Dark Mode on GitHubGitHub GitHub is a website that offers online implementation of git repositories that can easily be shared, copied and modified by other developers. Public repositories are free to host, private repositories require a paid subscription. GitHub introduced the concept of the ‘pull request’ where code changes done in branches by contributors can be reviewed and discussed before being merged be the repository owner. https://github.com/ and is open to help, so please review if you’re interested/available
  • @mikeschinkel looking for feedback on #12955
  • @jeremyfelt looking for another +1 from somebody who tests out the patch on #44240
  • @yguez looking for feedback on patch on #44094

Next meeting

The next meeting will take place on June 6, 2018 at 20:00 UTC / June 6, 2018 at 20:00 UTC in the #core Slack channel. Please feel free to drop in with any updates or questions. If you have items to discuss but cannot make the meeting, please leave a comment on this post so that we can take them into account.

#4-9-7, #core, #core-php, #core-privacy, #dev-chat, #gdpr-compliance, #privacy, #summary, #wpcs

Dev Chat Agenda: May 30th (4.9.7 week 2)

This is the agenda for the weekly dev meeting on May 30, 2018 at 20:00 UTC / May 30, 2018 at 20:00 UTC:

If you have anything to propose to add to the agenda or specific items related to the above, please leave a comment below. See you there!

#4-9-7, #agenda, #core, #dev-chat, #wpcs