Skip to content

Add function_exists( 'add_action' ) check to initialization file #1270

@salcode

Description

@salcode

When using CMB2 via composer and using a PHP based tool (e.g. PHP Code Sniffer), the PHP based tool throws an error.

Expected Behavior:

When installing CMB2 and PHP Code Sniffer via composer with a composer.json of

{
    "require": {
        "cmb2/cmb2": "^2.6"
    },
    "require-dev": {
        "squizlabs/php_codesniffer": "3.*"
    },
    "autoload"    : {
        "files": [
            "vendor/cmb2/cmb2/init.php"
        ]
    },
    "extra": {
        "installer-paths": {
            "vendor/cmb2/cmb2": ["cmb2/cmb2"]
        }
    }
}

I expect the following to run PHP Code Sniffer (phpcs)

$ composer install
$ ./vendor/bin/phpcs

Actual Behavior:

I get a fatal error because the function add_action() is undefined.

$ composer install
$ ./vendor/bin/phpcs
Fatal error: Uncaught Error: Call to undefined function add_action() in vendor/cmb2/cmb2/init.php:126

Possible Solution

If we add a function_exists() check for add_action() before calling it, we can prevent throwing this fatal error.

Possible Solution's Risk Level

This seems to be a relatively low risk change. Since we're checking if the function add_action() exists directly before calling it, the only behavior change we should get is avoiding throwing this fatal error.

Steps to reproduce (I have confirmed I can reproduce this issue on the develop branch):

  1. Clone https://github.com/salcode/salcode-cmb2-autoload-demo
  2. Run composer install
  3. Run ./vendor/bin/phpcs

Your Environment

Mac OS X Command Line

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions