PHP Toolkit

ToolkitCodingStandards

PHP_CodeSniffer sniffs used by this project: enforce Yoda comparisons and ban the short ternary where it hides falsy-value bugs.

composer require wp-php-toolkit/toolkit-coding-standards

This package is not a general-purpose style guide. It holds project-specific PHP_CodeSniffer rules for review comments the toolkit wants automated: comparisons should follow the WordPress Yoda style, and short ternaries should not hide whether a fallback is meant for null only or for all falsy values.

Use it in this monorepo, or in a project that intentionally wants the same review tradeoffs. If your project does not follow WordPress-style comparisons, the Yoda sniff is probably the wrong rule for you.

Reference the standard from your phpcs.xml

The component is a PHPCS ruleset, so the useful examples are configuration and before/after code rather than runtime snippets. Activate both sniffs at once by referencing WordPressToolkitCodingStandards:

<?xml version="1.0"?>
<ruleset name="My Project">
  <file>src/</file>

  <!-- Activate both toolkit sniffs -->
  <rule ref="WordPressToolkitCodingStandards"/>

  <!-- Or pick them individually -->
  <!-- <rule ref="WordPressToolkitCodingStandards.PHP.EnforceYodaComparison"/> -->
  <!-- <rule ref="WordPressToolkitCodingStandards.PHP.DisallowShortTernary"/> -->
</ruleset>

Then run phpcs and phpcbf the usual way:

vendor/bin/phpcs --standard=phpcs.xml .
vendor/bin/phpcbf --standard=phpcs.xml .

EnforceYodaComparison: catches accidental assignment

Yoda comparisons (true === $x) make typo-induced assignments easier to catch and match the WordPress style used throughout the toolkit:

// Bug: single = inside a condition. Always truthy, mutates $status.
if ( $status = 'published' ) {
    publish_post( $post );
}

// Yoda style: writing this typo would be a parse error.
if ( 'published' === $status ) {
    publish_post( $post );
}

The sniff covers ===, !==, ==, and !=, and stays quiet when both sides are dynamic.

Why ban the short ternary

Developers confuse the short ternary ($a ?: $b) with the null-coalescing operator ($a ?? $b). They differ on falsy-but-not-null values: 0 ?: 'fallback' returns 'fallback', but 0 ?? 'fallback' returns 0. The sniff bans ?: entirely so reviewers don't have to relitigate this on every PR.

Review-friendly replacements

When the fallback should apply only to null, use ??. When the fallback should apply to every falsy value, write the full ternary so the intent is visible in review.

// Only missing values fall back. 0 and "" are preserved.
$limit = $request_limit ?? 20;

// Any falsy value falls back. The duplicated condition is intentional.
$title = $raw_title ? $raw_title : 'Untitled';

See also