function DeprecationHelper::backwardsCompatibleCall

Same name in other branches
  1. 11.x core/lib/Drupal/Component/Utility/DeprecationHelper.php \Drupal\Component\Utility\DeprecationHelper::backwardsCompatibleCall()

Helper to run a callback based on the installed version of a project.

With this helper, contributed or custom modules can run different code paths based on the version of a project (e.g. Drupal) using callbacks.

The below templates help code editors and PHPStan understand the return value of this function.

@template Current @template Deprecated

Parameters

string $currentVersion: Version to check against.

string $deprecatedVersion: Version that deprecated the old code path.

callable(): Current $currentCallable: Callback for the current version.

callable(): Deprecated $deprecatedCallable: Callback for deprecated code path.

Return value

Current|Deprecated

1 call to DeprecationHelper::backwardsCompatibleCall()
DeprecationHelperTest::testDeprecationHelper in core/tests/Drupal/Tests/Component/Utility/DeprecationHelperTest.php
@dataProvider deprecatedHelperTestCases

File

core/lib/Drupal/Component/Utility/DeprecationHelper.php, line 35

Class

DeprecationHelper
Provides a helper method for handling deprecated code paths in projects.

Namespace

Drupal\Component\Utility

Code

public static function backwardsCompatibleCall(string $currentVersion, string $deprecatedVersion, callable $currentCallable, callable $deprecatedCallable) : mixed {
    // Normalize the version string when it's a dev version to the first point release of that minor. E.g. 10.2.x-dev
    // and 10.2-dev both translate to 10.2.0
    $normalizedVersion = str_ends_with($currentVersion, '-dev') ? str_replace([
        '.x-dev',
        '-dev',
    ], '.0', $currentVersion) : $currentVersion;
    return version_compare($normalizedVersion, $deprecatedVersion, '>=') ? $currentCallable() : $deprecatedCallable();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.