From 42dd2b5a7d03bcaf7e8eda2c0728866c82125f87 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Fri, 4 Aug 2023 00:19:43 +0200 Subject: [PATCH 01/49] Commit WIP. --- .../GutenbergPrefixAllGlobals.php | 1071 +++++++++++++++++ 1 file changed, 1071 insertions(+) create mode 100644 test/php/gutenberg-coding-standards/Gutenberg/Sniffs/CodeAnalysis/GutenbergPrefixAllGlobals.php diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/CodeAnalysis/GutenbergPrefixAllGlobals.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/CodeAnalysis/GutenbergPrefixAllGlobals.php new file mode 100644 index 00000000000000..1351220a2a4c73 --- /dev/null +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/CodeAnalysis/GutenbergPrefixAllGlobals.php @@ -0,0 +1,1071 @@ + true, + 'wp' => true, + '_' => true, + 'php' => true, // See #1728, the 'php' prefix is reserved by PHP itself. + ); + + /** + * Target prefixes after validation. + * + * All prefixes are lowercased for case-insensitive compare. + * + * @since 0.12.0 + * + * @var string[] + */ + private $validated_prefixes = array(); + + /** + * Target namespace prefixes after validation with regex indicator. + * + * All prefixes are lowercased for case-insensitive compare. + * If the prefix doesn't already contain a namespace separator, but does contain + * non-word characters, these will have been replaced with regex syntax to allow + * for namespace separators and the `is_regex` indicator will have been set to `true`. + * + * @since 1.2.0 + * + * @var array + */ + private $validated_namespace_prefixes = array(); + + /** + * Cache of previously set prefixes. + * + * Prevents having to do the same prefix validation over and over again. + * + * @since 0.12.0 + * + * @var string[] + */ + private $previous_prefixes = array(); + + /** + * A list of core hooks that are allowed to be called by plugins and themes. + * + * @since 0.14.0 + * @since 3.0.0 Renamed from `$whitelisted_core_hooks` to `$allowed_core_hooks`. + * + * @var array + */ + protected $allowed_core_hooks = array( + 'widget_title' => true, + 'add_meta_boxes' => true, + ); + + /** + * A list of core constants that are allowed to be defined by plugins and themes. + * + * @since 1.0.0 + * @since 3.0.0 Renamed from `$whitelisted_core_constants` to `$allowed_core_constants`. + * + * Source: {@link https://core.trac.wordpress.org/browser/trunk/src/wp-includes/default-constants.php#L0} + * The constants are listed in the order they are found in the source file + * to make life easier for future updates. + * Only overrulable constants are listed, i.e. those defined within core within + * a `if ( ! defined() ) {}` wrapper. + * + * @var array + */ + protected $allowed_core_constants = array( + 'WP_MEMORY_LIMIT' => true, + 'WP_MAX_MEMORY_LIMIT' => true, + 'WP_CONTENT_DIR' => true, + 'WP_DEBUG' => true, + 'WP_DEBUG_DISPLAY' => true, + 'WP_DEBUG_LOG' => true, + 'WP_CACHE' => true, + 'SCRIPT_DEBUG' => true, + 'MEDIA_TRASH' => true, + 'SHORTINIT' => true, + 'WP_CONTENT_URL' => true, + 'WP_PLUGIN_DIR' => true, + 'WP_PLUGIN_URL' => true, + 'PLUGINDIR' => true, + 'WPMU_PLUGIN_DIR' => true, + 'WPMU_PLUGIN_URL' => true, + 'MUPLUGINDIR' => true, + 'COOKIEHASH' => true, + 'USER_COOKIE' => true, + 'PASS_COOKIE' => true, + 'AUTH_COOKIE' => true, + 'SECURE_AUTH_COOKIE' => true, + 'LOGGED_IN_COOKIE' => true, + 'TEST_COOKIE' => true, + 'COOKIEPATH' => true, + 'SITECOOKIEPATH' => true, + 'ADMIN_COOKIE_PATH' => true, + 'PLUGINS_COOKIE_PATH' => true, + 'COOKIE_DOMAIN' => true, + 'RECOVERY_MODE_COOKIE' => true, + 'FORCE_SSL_ADMIN' => true, + 'FORCE_SSL_LOGIN' => true, + 'AUTOSAVE_INTERVAL' => true, + 'EMPTY_TRASH_DAYS' => true, + 'WP_POST_REVISIONS' => true, + 'WP_CRON_LOCK_TIMEOUT' => true, + 'WP_DEFAULT_THEME' => true, + ); + + /** + * List of all PHP native functions. + * + * Using this list rather than a call to `function_exists()` prevents + * false negatives from user-defined functions when those would be + * autoloaded via a Composer autoload files directives. + * + * @var array + */ + private $built_in_functions; + + + /** + * Returns an array of tokens this test wants to listen for. + * + * @since 0.12.0 + * + * @return array + */ + public function register() { + // Get a list of all PHP native functions. + $all_functions = get_defined_functions(); + $this->built_in_functions = array_flip( $all_functions['internal'] ); + + // Set the sniff targets. + $targets = array( + \T_NAMESPACE => \T_NAMESPACE, + \T_FUNCTION => \T_FUNCTION, + \T_CONST => \T_CONST, + \T_VARIABLE => \T_VARIABLE, + \T_DOLLAR => \T_DOLLAR, // Variable variables. + \T_FN_ARROW => \T_FN_ARROW, // T_FN_ARROW is only used for skipping over (for now). + ); + $targets += Tokens::$ooScopeTokens; // T_ANON_CLASS is only used for skipping over test classes. + $targets += Collections::listOpenTokensBC(); + + // Add function call target for hook names and constants defined using define(). + $parent = parent::register(); + if ( ! empty( $parent ) ) { + $targets[] = \T_STRING; + } + + return $targets; + } + + /** + * Groups of functions to restrict. + * + * @since 0.12.0 + * + * @return array + */ + public function getGroups() { + // Only retrieve functions which are not used for deprecated hooks. + $this->target_functions = WPHookHelper::get_functions( false ); + $this->target_functions['define'] = true; + + return parent::getGroups(); + } + + /** + * Processes this test, when one of its tokens is encountered. + * + * @since 0.12.0 + * + * @param int $stackPtr The position of the current token in the stack. + * + * @return int|void Integer stack pointer to skip forward or void to continue + * normal file processing. + */ + public function process_token( $stackPtr ) { + + // Allow overruling the prefixes set in a ruleset via the command line. + $cl_prefixes = Helper::getConfigData( 'prefixes' ); + if ( ! empty( $cl_prefixes ) ) { + $cl_prefixes = trim( $cl_prefixes ); + if ( '' !== $cl_prefixes ) { + $this->prefixes = array_filter( array_map( 'trim', explode( ',', $cl_prefixes ) ) ); + } + } + + $this->prefixes = RulesetPropertyHelper::merge_custom_array( $this->prefixes, array(), false ); + if ( empty( $this->prefixes ) ) { + // No prefixes passed, nothing to do. + return; + } + + $this->validate_prefixes(); + if ( empty( $this->validated_prefixes ) ) { + // No _valid_ prefixes passed, nothing to do. + return; + } + + // Ignore test classes. + if ( isset( Tokens::$ooScopeTokens[ $this->tokens[ $stackPtr ]['code'] ] ) + && true === $this->is_test_class( $this->phpcsFile, $stackPtr ) + ) { + if ( $this->tokens[ $stackPtr ]['scope_condition'] === $stackPtr && isset( $this->tokens[ $stackPtr ]['scope_closer'] ) ) { + // Skip forward to end of test class. + return $this->tokens[ $stackPtr ]['scope_closer']; + } + return; + } + + if ( \T_ANON_CLASS === $this->tokens[ $stackPtr ]['code'] ) { + // Token was only registered to allow skipping over test classes. + return; + } + + /* + * Ignore the contents of arrow functions which do not declare closures. + * + * - Parameters declared by arrow functions do not need to be prefixed (handled elsewhere). + * - New variables declared within an arrow function are local to the arrow function, so can be ignored. + * - A `global` statement is not allowed within an arrow function. + * + * Note: this does mean some convoluted code may get ignored (false negatives), but this is currently + * not reliably solvable as PHPCS does not add arrow functions to the 'conditions' array. + */ + if ( \T_FN_ARROW === $this->tokens[ $stackPtr ]['code'] + && isset( $this->tokens[ $stackPtr ]['scope_closer'] ) + ) { + $has_closure = $this->phpcsFile->findNext( \T_CLOSURE, ( $stackPtr + 1 ), $this->tokens[ $stackPtr ]['scope_closer'] ); + if ( false !== $has_closure ) { + // Skip to the start of the closure. + return $has_closure; + } + + // Skip the arrow function completely. + return $this->tokens[ $stackPtr ]['scope_closer']; + } + + if ( \T_STRING === $this->tokens[ $stackPtr ]['code'] ) { + // Disallow excluding function groups for this sniff. + $this->exclude = array(); + + return parent::process_token( $stackPtr ); + + } elseif ( \T_DOLLAR === $this->tokens[ $stackPtr ]['code'] ) { + + return $this->process_variable_variable( $stackPtr ); + + } elseif ( \T_VARIABLE === $this->tokens[ $stackPtr ]['code'] ) { + + return $this->process_variable_assignment( $stackPtr ); + + } elseif ( isset( Collections::listOpenTokensBC()[ $this->tokens[ $stackPtr ]['code'] ] ) ) { + return $this->process_list_assignment( $stackPtr ); + + } elseif ( \T_NAMESPACE === $this->tokens[ $stackPtr ]['code'] ) { + $namespace_name = Namespaces::getDeclaredName( $this->phpcsFile, $stackPtr ); + + if ( false === $namespace_name || '' === $namespace_name || '\\' === $namespace_name ) { + return; + } + + foreach ( $this->validated_namespace_prefixes as $key => $prefix_info ) { + if ( false === $prefix_info['is_regex'] ) { + if ( stripos( $namespace_name, $prefix_info['prefix'] ) === 0 ) { + $this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: allowed prefixes', $key ); + return; + } + } else { + // Ok, so this prefix should be used as a regex. + $regex = '`^' . $prefix_info['prefix'] . '`i'; + if ( preg_match( $regex, $namespace_name ) > 0 ) { + $this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: allowed prefixes', $key ); + return; + } + } + } + + // Still here ? In that case, we have a non-prefixed namespace name. + $recorded = $this->phpcsFile->addError( + self::ERROR_MSG, + $stackPtr, + 'NonPrefixedNamespaceFound', + array( + 'Namespaces declared', + $namespace_name, + ) + ); + + if ( true === $recorded ) { + $this->record_potential_prefix_metric( $stackPtr, $namespace_name ); + } + + return; + + } else { + + // Namespaced methods, classes and constants do not need to be prefixed. + $namespace = Namespaces::determineNamespace( $this->phpcsFile, $stackPtr ); + if ( '' !== $namespace && '\\' !== $namespace ) { + return; + } + + $item_name = ''; + $error_text = 'Unknown syntax used'; + $error_code = 'NonPrefixedSyntaxFound'; + + switch ( $this->tokens[ $stackPtr ]['code'] ) { + case \T_FUNCTION: + // Methods in a class do not need to be prefixed. + if ( Scopes::isOOMethod( $this->phpcsFile, $stackPtr ) === true ) { + return; + } + + if ( DeprecationHelper::is_function_deprecated( $this->phpcsFile, $stackPtr ) === true ) { + /* + * Deprecated functions don't have to comply with the naming conventions, + * otherwise functions deprecated in favour of a function with a compliant + * name would still trigger an error. + */ + return; + } + + $item_name = FunctionDeclarations::getName( $this->phpcsFile, $stackPtr ); + if ( isset( $this->built_in_functions[ $item_name ] ) ) { + // Backfill for PHP native function. + return; + } + + $error_text = 'Functions declared in the global namespace'; + $error_code = 'NonPrefixedFunctionFound'; + break; + + case \T_CLASS: + case \T_INTERFACE: + case \T_TRAIT: + case \T_ENUM: + $item_name = ObjectDeclarations::getName( $this->phpcsFile, $stackPtr ); + $error_text = 'Classes declared'; + $error_code = 'NonPrefixedClassFound'; + + switch ( $this->tokens[ $stackPtr ]['code'] ) { + case \T_CLASS: + if ( class_exists( '\\' . $item_name, false ) ) { + // Backfill for PHP native class. + return; + } + break; + + case \T_INTERFACE: + if ( interface_exists( '\\' . $item_name, false ) ) { + // Backfill for PHP native interface. + return; + } + + $error_text = 'Interfaces declared'; + $error_code = 'NonPrefixedInterfaceFound'; + break; + + case \T_TRAIT: + // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.trait_existsFound + if ( function_exists( '\trait_exists' ) && trait_exists( '\\' . $item_name, false ) ) { + // Backfill for PHP native trait. + return; + } + + $error_text = 'Traits declared'; + $error_code = 'NonPrefixedTraitFound'; + break; + + case \T_ENUM: + // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.enum_existsFound + if ( function_exists( '\enum_exists' ) && enum_exists( '\\' . $item_name, false ) ) { + // Backfill for PHP native enum. + return; + } + + $error_text = 'Enums declared'; + $error_code = 'NonPrefixedEnumFound'; + break; + } + + break; + + case \T_CONST: + // Constants in an OO construct do not need to be prefixed. + if ( true === Scopes::isOOConstant( $this->phpcsFile, $stackPtr ) ) { + return; + } + + $constant_name_ptr = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true ); + if ( false === $constant_name_ptr ) { + // Live coding. + return; + } + + $item_name = $this->tokens[ $constant_name_ptr ]['content']; + if ( \defined( '\\' . $item_name ) ) { + // Backfill for PHP native constant. + return; + } + + if ( isset( $this->allowed_core_constants[ $item_name ] ) ) { + // Defining a WP Core constant intended for overruling. + return; + } + + $error_text = 'Global constants defined'; + $error_code = 'NonPrefixedConstantFound'; + break; + + default: + // Left empty on purpose. + break; + + } + + if ( empty( $item_name ) || $this->is_prefixed( $stackPtr, $item_name ) === true ) { + return; + } + + $recorded = $this->phpcsFile->addError( + self::ERROR_MSG, + $stackPtr, + $error_code, + array( + $error_text, + $item_name, + ) + ); + + if ( true === $recorded ) { + $this->record_potential_prefix_metric( $stackPtr, $item_name ); + } + } + } + + /** + * Handle variable variables defined in the global namespace. + * + * @since 0.12.0 + * + * @param int $stackPtr The position of the current token in the stack. + * + * @return int|void Integer stack pointer to skip forward or void to continue + * normal file processing. + */ + protected function process_variable_variable( $stackPtr ) { + static $indicators = array( + \T_OPEN_CURLY_BRACKET => true, + \T_VARIABLE => true, + ); + + // Is this a variable variable ? + // Not concerned with nested ones as those will be recognized on their own token. + $next_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true ); + if ( false === $next_non_empty || ! isset( $indicators[ $this->tokens[ $next_non_empty ]['code'] ] ) ) { + return; + } + + if ( \T_OPEN_CURLY_BRACKET === $this->tokens[ $next_non_empty ]['code'] + && isset( $this->tokens[ $next_non_empty ]['bracket_closer'] ) + ) { + // Skip over the variable part. + $next_non_empty = $this->tokens[ $next_non_empty ]['bracket_closer']; + } + + $maybe_assignment = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $next_non_empty + 1 ), null, true, null, true ); + + while ( false !== $maybe_assignment + && \T_OPEN_SQUARE_BRACKET === $this->tokens[ $maybe_assignment ]['code'] + && isset( $this->tokens[ $maybe_assignment ]['bracket_closer'] ) + ) { + $maybe_assignment = $this->phpcsFile->findNext( + Tokens::$emptyTokens, + ( $this->tokens[ $maybe_assignment ]['bracket_closer'] + 1 ), + null, + true, + null, + true + ); + } + + if ( false === $maybe_assignment ) { + return; + } + + if ( ! isset( Tokens::$assignmentTokens[ $this->tokens[ $maybe_assignment ]['code'] ] ) ) { + // Not an assignment. + return; + } + + $error = self::ERROR_MSG; + + /* + * Local variable variables in a function do not need to be prefixed. + * But a variable variable could evaluate to the name of an imported global + * variable. + * Not concerned with imported variable variables (global.. ) as that has been + * forbidden since PHP 7.0. Presuming cross-version code and if not, that + * is for the PHPCompatibility standard to detect. + */ + $functionPtr = Conditions::getLastCondition( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); + if ( false !== $functionPtr ) { + $has_global = $this->phpcsFile->findPrevious( \T_GLOBAL, ( $stackPtr - 1 ), $this->tokens[ $functionPtr ]['scope_opener'] ); + if ( false === $has_global ) { + // No variable import happening. + return; + } + + $error = 'Variable variable which could potentially override an imported global variable detected. ' . $error; + } + + $variable_name = $this->phpcsFile->getTokensAsString( $stackPtr, ( ( $next_non_empty - $stackPtr ) + 1 ) ); + + // Still here ? In that case, the variable name should be prefixed. + $recorded = $this->phpcsFile->addWarning( + $error, + $stackPtr, + 'NonPrefixedVariableFound', + array( + 'Global variables defined', + $variable_name, + ) + ); + + if ( true === $recorded ) { + $this->record_potential_prefix_metric( $stackPtr, $variable_name ); + } + + // Skip over the variable part of the variable. + return ( $next_non_empty + 1 ); + } + + /** + * Check that defined global variables are prefixed. + * + * @since 0.12.0 + * @since 2.2.0 Added $in_list parameter. + * + * @param int $stackPtr The position of the current token in the stack. + * @param bool $in_list Whether or not this is a variable in a list assignment. + * Defaults to false. + * + * @return int|void Integer stack pointer to skip forward or void to continue + * normal file processing. + */ + protected function process_variable_assignment( $stackPtr, $in_list = false ) { + /* + * We're only concerned with variables which are being defined. + * `is_assigment()` will not recognize property assignments, which is good in this case. + * However it will also not recognize $b in `foreach( $a as $b )` as an assignment, so + * we need a separate check for that. + */ + if ( false === $in_list + && false === VariableHelper::is_assignment( $this->phpcsFile, $stackPtr ) + && Context::inForeachCondition( $this->phpcsFile, $stackPtr ) !== 'afterAs' + ) { + return; + } + + $is_error = true; + $variable_name = substr( $this->tokens[ $stackPtr ]['content'], 1 ); // Strip the dollar sign. + + // Bow out early if we know for certain no prefix is needed. + if ( 'GLOBALS' !== $variable_name + && $this->variable_prefixed_or_allowed( $stackPtr, $variable_name ) === true + ) { + return; + } + + if ( 'GLOBALS' === $variable_name ) { + $array_open = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true ); + if ( false === $array_open || \T_OPEN_SQUARE_BRACKET !== $this->tokens[ $array_open ]['code'] ) { + // Live coding or something very silly. + return; + } + + $array_key = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $array_open + 1 ), null, true, null, true ); + if ( false === $array_key ) { + // No key found, nothing to do. + return; + } + + $stackPtr = $array_key; + $variable_name = TextStrings::stripQuotes( $this->tokens[ $array_key ]['content'] ); + + // Check whether a prefix is needed. + if ( isset( Tokens::$stringTokens[ $this->tokens[ $array_key ]['code'] ] ) + && $this->variable_prefixed_or_allowed( $stackPtr, $variable_name ) === true + ) { + return; + } + + if ( \T_DOUBLE_QUOTED_STRING === $this->tokens[ $array_key ]['code'] ) { + // If the array key is a double quoted string, try again with only + // the part before the first variable (if any). + $exploded = explode( '$', $variable_name ); + $first = rtrim( $exploded[0], '{' ); + if ( '' !== $first ) { + if ( $this->variable_prefixed_or_allowed( $array_key, $first ) === true ) { + return; + } + } else { + // If the first part was dynamic, throw a warning. + $is_error = false; + } + } elseif ( ! isset( Tokens::$stringTokens[ $this->tokens[ $array_key ]['code'] ] ) ) { + // Dynamic array key, throw a warning. + $is_error = false; + } + } else { + // Function parameters do not need to be prefixed. + if ( false === $in_list ) { + $functionPtr = Parentheses::getLastOwner( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); + if ( false !== $functionPtr ) { + return; + } + unset( $functionPtr ); + } + + // Properties in a class do not need to be prefixed. + if ( false === $in_list && true === Scopes::isOOProperty( $this->phpcsFile, $stackPtr ) ) { + return; + } + + // Local variables in a function do not need to be prefixed unless they are being imported. + $functionPtr = Conditions::getLastCondition( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); + if ( false !== $functionPtr ) { + $has_global = $this->phpcsFile->findPrevious( \T_GLOBAL, ( $stackPtr - 1 ), $this->tokens[ $functionPtr ]['scope_opener'] ); + if ( false === $has_global + || Conditions::getLastCondition( $this->phpcsFile, $has_global, Collections::functionDeclarationTokens() ) !== $functionPtr + ) { + // No variable import happening in the current scope. + return; + } + + // Ok, this may be an imported global variable. + $end_of_statement = $this->phpcsFile->findNext( array( \T_SEMICOLON, \T_CLOSE_TAG ), ( $has_global + 1 ) ); + if ( false === $end_of_statement ) { + // No semi-colon - live coding. + return; + } + + for ( $ptr = ( $has_global + 1 ); $ptr <= $end_of_statement; $ptr++ ) { + // Move the stack pointer to the next variable. + $ptr = $this->phpcsFile->findNext( \T_VARIABLE, $ptr, $end_of_statement, false, null, true ); + + if ( false === $ptr ) { + // Reached the end of the global statement without finding the variable, + // so this must be a local variable. + return; + } + + if ( substr( $this->tokens[ $ptr ]['content'], 1 ) === $variable_name ) { + break; + } + } + + unset( $has_global, $end_of_statement, $ptr, $imported ); + } + } + + // Still here ? In that case, the variable name should be prefixed. + $recorded = MessageHelper::addMessage( + $this->phpcsFile, + self::ERROR_MSG, + $stackPtr, + $is_error, + 'NonPrefixedVariableFound', + array( + 'Global variables defined', + '$' . $variable_name, + ) + ); + + if ( true === $recorded ) { + $this->record_potential_prefix_metric( $stackPtr, $variable_name ); + } + } + + /** + * Check that global variables declared via a list construct are prefixed. + * + * @internal No need to take special measures for nested lists. Nested or not, + * each list part can only contain one variable being written to. + * + * @since 2.2.0 + * + * @param int $stackPtr The position of the current token in the stack. + * + * @return int|void Integer stack pointer to skip forward or void to continue + * normal file processing. + */ + protected function process_list_assignment( $stackPtr ) { + $list_open_close = Lists::getOpenClose( $this->phpcsFile, $stackPtr ); + if ( false === $list_open_close ) { + // Short array, not short list. + return; + } + + $var_pointers = $this->get_list_variables( $stackPtr, $list_open_close ); + foreach ( $var_pointers as $ptr ) { + $this->process_variable_assignment( $ptr, true ); + } + + // No need to re-examine these variables. + return $list_open_close['closer']; + } + + /** + * Process the parameters of a matched function. + * + * @since 0.12.0 + * + * @param int $stackPtr The position of the current token in the stack. + * @param string $group_name The name of the group which was matched. + * @param string $matched_content The token content (function name) which was matched. + * @param array $parameters Array with information about the parameters. + * + * @return void + */ + public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { + if ( 'define' === $matched_content ) { + $target_param = PassedParameters::getParameterFromStack( $parameters, 1, 'constant_name' ); + + } else { + $target_param = WPHookHelper::get_hook_name_param( $matched_content, $parameters ); + } + + if ( false === $target_param ) { + return; + } + + $is_error = true; + $clean_content = TextStrings::stripQuotes( $target_param['clean'] ); + + if ( ( 'define' !== $matched_content + && isset( $this->allowed_core_hooks[ $clean_content ] ) ) + || ( 'define' === $matched_content + && isset( $this->allowed_core_constants[ $clean_content ] ) ) + ) { + return; + } + + if ( $this->is_prefixed( $target_param['start'], $clean_content ) === true ) { + return; + } else { + // This may be a dynamic hook/constant name. + $first_non_empty = $this->phpcsFile->findNext( + Tokens::$emptyTokens, + $target_param['start'], + ( $target_param['end'] + 1 ), + true + ); + + if ( false === $first_non_empty ) { + return; + } + + $first_non_empty_content = TextStrings::stripQuotes( $this->tokens[ $first_non_empty ]['content'] ); + + // Try again with just the first token if it's a text string. + if ( isset( Tokens::$stringTokens[ $this->tokens[ $first_non_empty ]['code'] ] ) + && $this->is_prefixed( $target_param['start'], $first_non_empty_content ) === true + ) { + return; + } + + if ( \T_DOUBLE_QUOTED_STRING === $this->tokens[ $first_non_empty ]['code'] ) { + // If the first part of the parameter is a double quoted string, try again with only + // the part before the first variable (if any). + $exploded = explode( '$', $first_non_empty_content ); + $first = rtrim( $exploded[0], '{' ); + if ( '' !== $first ) { + if ( $this->is_prefixed( $target_param['start'], $first ) === true ) { + return; + } + } else { + // Start of hook/constant name is dynamic, throw a warning. + $is_error = false; + } + } elseif ( ! isset( Tokens::$stringTokens[ $this->tokens[ $first_non_empty ]['code'] ] ) ) { + // Dynamic hook/constant name, throw a warning. + $is_error = false; + } + } + + if ( 'define' === $matched_content ) { + if ( \defined( '\\' . $clean_content ) ) { + // Backfill for PHP native constant. + return; + } + + if ( strpos( $clean_content, '\\' ) !== false ) { + // Namespaced or unreachable constant. + return; + } + + $data = array( 'Global constants defined' ); + $error_code = 'NonPrefixedConstantFound'; + if ( false === $is_error ) { + $error_code = 'VariableConstantNameFound'; + } + } else { + $data = array( 'Hook names invoked' ); + $error_code = 'NonPrefixedHooknameFound'; + if ( false === $is_error ) { + $error_code = 'DynamicHooknameFound'; + } + } + + $data[] = $clean_content; + + $recorded = MessageHelper::addMessage( $this->phpcsFile, self::ERROR_MSG, $first_non_empty, $is_error, $error_code, $data ); + + if ( true === $recorded ) { + $this->record_potential_prefix_metric( $stackPtr, $clean_content ); + } + } + + /** + * Check if a function/class/constant/variable name is prefixed with one of the expected prefixes. + * + * @since 0.12.0 + * @since 0.14.0 Allows for other non-word characters as well as underscores to better support hook names. + * @since 1.0.0 Does not require a word seperator anymore after a prefix. + * This allows for improved code style independent checking, + * i.e. allows for camelCase naming and the likes. + * @since 1.0.1 - Added $stackPtr parameter. + * - The function now also records metrics about the prefixes encountered. + * + * @param int $stackPtr The position of the token to record the metric against. + * @param string $name Name to check for a prefix. + * + * @return bool True when the name is one of the prefixes or starts with an allowed prefix. + * False otherwise. + */ + private function is_prefixed( $stackPtr, $name ) { + foreach ( $this->validated_prefixes as $prefix ) { + if ( stripos( $name, $prefix ) === 0 ) { + $this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: allowed prefixes', $prefix ); + return true; + } + } + + return false; + } + + /** + * Check if a variable name might need a prefix. + * + * Prefix is not needed for: + * - superglobals, + * - WP native globals, + * - variables which are already prefixed. + * + * @since 0.12.0 + * @since 1.0.1 Added $stackPtr parameter. + * @since 3.0.0 Renamed from `variable_prefixed_or_whitelisted()` to `variable_prefixed_or_allowed()`. + * + * @param int $stackPtr The position of the token to record the metric against. + * @param string $name Variable name without the dollar sign. + * + * @return bool True if the variable name is allowed or already prefixed. + * False otherwise. + */ + private function variable_prefixed_or_allowed( $stackPtr, $name ) { + // Ignore superglobals and WP global variables. + if ( Variables::isSuperglobalName( $name ) || WPGlobalVariablesHelper::is_wp_global( $name ) ) { + return true; + } + + return $this->is_prefixed( $stackPtr, $name ); + } + + /** + * Validate an array of prefixes as passed through a custom property or via the command line. + * + * Checks that the prefix: + * - is not one of the blocked ones. + * - complies with the PHP rules for valid function, class, variable, constant names. + * + * @since 0.12.0 + */ + private function validate_prefixes() { + if ( $this->previous_prefixes === $this->prefixes ) { + return; + } + + // Set the cache *before* validation so as to not break the above compare. + $this->previous_prefixes = $this->prefixes; + + // Validate the passed prefix(es). + $prefixes = array(); + $ns_prefixes = array(); + foreach ( $this->prefixes as $key => $prefix ) { + $prefixLC = strtolower( $prefix ); + + if ( isset( $this->prefix_blocklist[ $prefixLC ] ) ) { + $this->phpcsFile->addError( + 'The "%s" prefix is not allowed.', + 0, + 'ForbiddenPrefixPassed', + array( $prefix ) + ); + continue; + } + + $prefix_length = strlen( $prefix ); + if ( function_exists( 'iconv_strlen' ) ) { + $prefix_length = iconv_strlen( $prefix, Helper::getEncoding( $this->phpcsFile ) ); + } + + if ( $prefix_length < self::MIN_PREFIX_LENGTH ) { + $this->phpcsFile->addError( + 'The "%s" prefix is too short. Short prefixes are not unique enough and may cause name collisions with other code.', + 0, + 'ShortPrefixPassed', + array( $prefix ) + ); + continue; + } + + /* + * Validate the prefix against characters allowed for function, class, constant names etc. + * Note: this does not use the PHPCSUtils `NamingConventions::isValidIdentifierName()` method + * as we want to allow namespace separators in the prefixes. + */ + if ( preg_match( '`^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff\\\\]*$`', $prefix ) !== 1 ) { + + $this->phpcsFile->addWarning( + 'The "%s" prefix is not a valid namespace/function/class/variable/constant prefix in PHP.', + 0, + 'InvalidPrefixPassed', + array( $prefix ) + ); + } + + // Lowercase the prefix to allow for direct compare. + $prefixes[ $key ] = $prefixLC; + + /* + * Replace non-word characters in the prefix with a regex snippet, but only if the + * string doesn't already contain namespace separators. + */ + $is_regex = false; + if ( strpos( $prefix, '\\' ) === false && preg_match( '`[_\W]`', $prefix ) > 0 ) { + $prefix = preg_replace( '`([_\W])`', '[\\\\\\\\$1]', $prefixLC ); + $is_regex = true; + } + + $ns_prefixes[ $prefixLC ] = array( + 'prefix' => $prefix, + 'is_regex' => $is_regex, + ); + } + + // Set the validated prefixes caches. + $this->validated_prefixes = $prefixes; + $this->validated_namespace_prefixes = $ns_prefixes; + } + + /** + * Record the "potential prefix" metric. + * + * @since 1.0.1 + * + * @param int $stackPtr The position of the token to record the metric against. + * @param string $construct_name Name of the global construct to try and distill a potential prefix from. + * + * @return void + */ + private function record_potential_prefix_metric( $stackPtr, $construct_name ) { + if ( preg_match( '`^([A-Z]*[a-z0-9]*+)`', ltrim( $construct_name, '\$_' ), $matches ) > 0 + && isset( $matches[1] ) && '' !== $matches[1] + ) { + $this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: potential prefixes - start of non-prefixed construct', strtolower( $matches[1] ) ); + } + } +} From d7f7212254a2d0a2b016ac4c4f00e2d87992eea1 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Mon, 7 Aug 2023 22:26:04 +0200 Subject: [PATCH 02/49] Commit WIP. --- .../PrefixAllGlobalsSniff.php | 217 ++++++++++++++++++ 1 file changed, 217 insertions(+) create mode 100644 test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php new file mode 100644 index 00000000000000..2d6132e49d21f1 --- /dev/null +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php @@ -0,0 +1,217 @@ +onRegisterEvent(); + + return array( T_FUNCTION, T_CLASS ); + } + + /** + * Processes function and class tokens. + * + * @param File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; + + if ( 'T_FUNCTION' === $token['type'] ) { + $this->processFunctionToken( $phpcsFile, $stackPtr ); + return; + } + + if ( 'T_CLASS' === $token['type'] ) { + $this->processClassToken( $phpcsFile, $stackPtr ); + } + } + + /** + * Functions should be wrapped with !function_exists() to avoid fatal errors. + * E.g.: + * if ( ! function_exists( 'wp_get_navigation' ) ) { + * function wp_get_navigation( $slug ) { ... } + * } + * + * @param File $phpcsFile The file being scanned. + * @param int $stackPointer The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + private function processFunctionToken( File $phpcsFile, $stackPointer ) { + $tokens = $phpcsFile->getTokens(); + $functionToken = $phpcsFile->findNext( T_STRING, $stackPointer ); + + $wrappingTokensToCheck = array( + T_CLASS, + T_INTERFACE, + T_TRAIT, + ); + + foreach ( $wrappingTokensToCheck as $wrappingTokenToCheck ) { + if ( false !== $phpcsFile->getCondition( $functionToken, $wrappingTokenToCheck, false ) ) { + // This sniff only processes functions, not class methods. + return; + } + } + + $functionName = $tokens[ $functionToken ]['content']; + foreach ( $this->whitelisted_functions as $functionRegExp ) { + if ( preg_match( $functionRegExp, $functionName ) ) { + // Ignore whitelisted function names. + return; + } + } + + foreach ( $this->blacklisted_functions as $functionRegExp ) { + if ( preg_match( $functionRegExp, $functionName ) ) { + $errorMessage = $this->getFunctionNameErrorMessage( $functionName, $functionRegExp ); + $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameViolatesNamingConvention' ); + return; + } + } + } + + /** + * Classes should be wrapped with !function_exists() to avoid fatal errors. + * E.g.: + * if ( class_exists( 'WP_Navigation' ) ) { + * return; + * } + * + * Alternatively: + * + * if ( ! class_exists( 'WP_Navigation' ) ) { + * class WP_Navigation { ... } + * } + * + * @param File $phpcsFile The file being scanned. + * @param int $stackPointer The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + private function processClassToken( File $phpcsFile, $stackPointer ) { + $tokens = $phpcsFile->getTokens(); + $classToken = $phpcsFile->findNext( T_STRING, $stackPointer ); + $className = $tokens[ $classToken ]['content']; + + foreach ( $this->whitelisted_classes as $classnameRegExp ) { + if ( preg_match( $classnameRegExp, $className ) ) { + // Ignore whitelisted class names. + return; + } + } + + foreach ( $this->blacklisted_classes as $classnameRegExp ) { + if ( preg_match( $classnameRegExp, $className ) ) { + $errorMessage = $this->getClassNameErrorMessage( $className, $classnameRegExp ); + $phpcsFile->addError( $errorMessage, $classnameRegExp, 'ClassNameViolatesNamingConvention' ); + return; + } + } + } + + private function getFunctionNameErrorMessage( $functionName, $regularExpression) { + return sprintf( + 'The function name "%s()" violates the naming convention defined by the regular expression: "{regular_expression}".', + $functionName, + $regularExpression + ); + } + + private function getClassNameErrorMessage( $className, $regularExpression) { + return sprintf( + 'The class name "%s" violates the naming convention defined by the regular expression: "{regular_expression}".', + $className, + $regularExpression + ); + } + + /** + * The purpose of this method is to sanitize the input data + * after the properties have been set. + */ + private function onRegisterEvent() { + $this->whitelisted_functions = self::sanitize( $this->whitelisted_functions ); + $this->whitelisted_classes = self::sanitize( $this->whitelisted_classes ); + } + + /** + * Input data needs to be sanitized. + * + * @param array $values The values being sanitized. + * + * @return array + */ + private static function sanitize( $values ) { + $values = array_map( 'trim', $values ); + + return array_filter( $values ); + } +} From 881a5940c3ed67a0e81d13cc63ee81084091b93e Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 16:29:34 +0200 Subject: [PATCH 03/49] 1. Rename sniff. 2. Adjust the logic per https://github.com/WordPress/gutenberg/issues/52769#issuecomment-1669540435. --- .../PrefixAllGlobalsSniff.php | 217 ------------------ .../ValidBlockLibraryFunctionName.php | 128 +++++++++++ 2 files changed, 128 insertions(+), 217 deletions(-) delete mode 100644 test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php create mode 100644 test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionName.php diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php deleted file mode 100644 index 2d6132e49d21f1..00000000000000 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php +++ /dev/null @@ -1,217 +0,0 @@ -onRegisterEvent(); - - return array( T_FUNCTION, T_CLASS ); - } - - /** - * Processes function and class tokens. - * - * @param File $phpcsFile The file being scanned. - * @param int $stackPtr The position of the current token - * in the stack passed in $tokens. - * - * @return void - */ - public function process( File $phpcsFile, $stackPtr ) { - $tokens = $phpcsFile->getTokens(); - $token = $tokens[ $stackPtr ]; - - if ( 'T_FUNCTION' === $token['type'] ) { - $this->processFunctionToken( $phpcsFile, $stackPtr ); - return; - } - - if ( 'T_CLASS' === $token['type'] ) { - $this->processClassToken( $phpcsFile, $stackPtr ); - } - } - - /** - * Functions should be wrapped with !function_exists() to avoid fatal errors. - * E.g.: - * if ( ! function_exists( 'wp_get_navigation' ) ) { - * function wp_get_navigation( $slug ) { ... } - * } - * - * @param File $phpcsFile The file being scanned. - * @param int $stackPointer The position of the current token - * in the stack passed in $tokens. - * - * @return void - */ - private function processFunctionToken( File $phpcsFile, $stackPointer ) { - $tokens = $phpcsFile->getTokens(); - $functionToken = $phpcsFile->findNext( T_STRING, $stackPointer ); - - $wrappingTokensToCheck = array( - T_CLASS, - T_INTERFACE, - T_TRAIT, - ); - - foreach ( $wrappingTokensToCheck as $wrappingTokenToCheck ) { - if ( false !== $phpcsFile->getCondition( $functionToken, $wrappingTokenToCheck, false ) ) { - // This sniff only processes functions, not class methods. - return; - } - } - - $functionName = $tokens[ $functionToken ]['content']; - foreach ( $this->whitelisted_functions as $functionRegExp ) { - if ( preg_match( $functionRegExp, $functionName ) ) { - // Ignore whitelisted function names. - return; - } - } - - foreach ( $this->blacklisted_functions as $functionRegExp ) { - if ( preg_match( $functionRegExp, $functionName ) ) { - $errorMessage = $this->getFunctionNameErrorMessage( $functionName, $functionRegExp ); - $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameViolatesNamingConvention' ); - return; - } - } - } - - /** - * Classes should be wrapped with !function_exists() to avoid fatal errors. - * E.g.: - * if ( class_exists( 'WP_Navigation' ) ) { - * return; - * } - * - * Alternatively: - * - * if ( ! class_exists( 'WP_Navigation' ) ) { - * class WP_Navigation { ... } - * } - * - * @param File $phpcsFile The file being scanned. - * @param int $stackPointer The position of the current token - * in the stack passed in $tokens. - * - * @return void - */ - private function processClassToken( File $phpcsFile, $stackPointer ) { - $tokens = $phpcsFile->getTokens(); - $classToken = $phpcsFile->findNext( T_STRING, $stackPointer ); - $className = $tokens[ $classToken ]['content']; - - foreach ( $this->whitelisted_classes as $classnameRegExp ) { - if ( preg_match( $classnameRegExp, $className ) ) { - // Ignore whitelisted class names. - return; - } - } - - foreach ( $this->blacklisted_classes as $classnameRegExp ) { - if ( preg_match( $classnameRegExp, $className ) ) { - $errorMessage = $this->getClassNameErrorMessage( $className, $classnameRegExp ); - $phpcsFile->addError( $errorMessage, $classnameRegExp, 'ClassNameViolatesNamingConvention' ); - return; - } - } - } - - private function getFunctionNameErrorMessage( $functionName, $regularExpression) { - return sprintf( - 'The function name "%s()" violates the naming convention defined by the regular expression: "{regular_expression}".', - $functionName, - $regularExpression - ); - } - - private function getClassNameErrorMessage( $className, $regularExpression) { - return sprintf( - 'The class name "%s" violates the naming convention defined by the regular expression: "{regular_expression}".', - $className, - $regularExpression - ); - } - - /** - * The purpose of this method is to sanitize the input data - * after the properties have been set. - */ - private function onRegisterEvent() { - $this->whitelisted_functions = self::sanitize( $this->whitelisted_functions ); - $this->whitelisted_classes = self::sanitize( $this->whitelisted_classes ); - } - - /** - * Input data needs to be sanitized. - * - * @param array $values The values being sanitized. - * - * @return array - */ - private static function sanitize( $values ) { - $values = array_map( 'trim', $values ); - - return array_filter( $values ); - } -} diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionName.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionName.php new file mode 100644 index 00000000000000..789ca220d18200 --- /dev/null +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionName.php @@ -0,0 +1,128 @@ +onRegisterEvent(); + + return array( T_FUNCTION ); + } + + /** + * Processes function and class tokens. + * + * @param File $phpcsFile The file being scanned. + * @param int $stackPtr The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + public function process( File $phpcsFile, $stackPtr ) { + $tokens = $phpcsFile->getTokens(); + $token = $tokens[ $stackPtr ]; + + if ( 'T_FUNCTION' !== $token['type'] ) { + return; + } + + $this->processFunctionToken( $phpcsFile, $stackPtr ); + } + + /** + * Functions should be wrapped with !function_exists() to avoid fatal errors. + * E.g.: + * if ( ! function_exists( 'wp_get_navigation' ) ) { + * function wp_get_navigation( $slug ) { ... } + * } + * + * @param File $phpcsFile The file being scanned. + * @param int $stackPointer The position of the current token + * in the stack passed in $tokens. + * + * @return void + */ + private function processFunctionToken( File $phpcsFile, $stackPointer ) { + $tokens = $phpcsFile->getTokens(); + $functionToken = $phpcsFile->findNext( T_STRING, $stackPointer ); + + $wrappingTokensToCheck = array( + T_CLASS, + T_INTERFACE, + T_TRAIT, + ); + + foreach ( $wrappingTokensToCheck as $wrappingTokenToCheck ) { + if ( false !== $phpcsFile->getCondition( $functionToken, $wrappingTokenToCheck, false ) ) { + // This sniff only processes functions, not class methods. + return; + } + } + + $functionName = $tokens[ $functionToken ]['content']; + + foreach ( $this->whitelistedFunctions as $functionRegExp ) { + if ( preg_match( $functionRegExp, $functionName ) ) { + // Ignore whitelisted function names. + return; + } + } + } + + /** + * The purpose of this method is to sanitize the input data + * after the properties have been set. + */ + private function onRegisterEvent() { + $this->prefixes = self::sanitize( $this->prefixes ); + } + + /** + * Input data needs to be sanitized. + * + * @param array $values The values being sanitized. + * + * @return array + */ + private static function sanitize( $values ) { + $values = array_map( 'trim', $values ); + + return array_filter( $values ); + } +} From 695e2bfbcde341ba1076152f9582238e5c011ef9 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 17:10:35 +0200 Subject: [PATCH 04/49] Remove redundant file. --- .../GutenbergPrefixAllGlobals.php | 1071 ----------------- 1 file changed, 1071 deletions(-) delete mode 100644 test/php/gutenberg-coding-standards/Gutenberg/Sniffs/CodeAnalysis/GutenbergPrefixAllGlobals.php diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/CodeAnalysis/GutenbergPrefixAllGlobals.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/CodeAnalysis/GutenbergPrefixAllGlobals.php deleted file mode 100644 index 1351220a2a4c73..00000000000000 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/CodeAnalysis/GutenbergPrefixAllGlobals.php +++ /dev/null @@ -1,1071 +0,0 @@ - true, - 'wp' => true, - '_' => true, - 'php' => true, // See #1728, the 'php' prefix is reserved by PHP itself. - ); - - /** - * Target prefixes after validation. - * - * All prefixes are lowercased for case-insensitive compare. - * - * @since 0.12.0 - * - * @var string[] - */ - private $validated_prefixes = array(); - - /** - * Target namespace prefixes after validation with regex indicator. - * - * All prefixes are lowercased for case-insensitive compare. - * If the prefix doesn't already contain a namespace separator, but does contain - * non-word characters, these will have been replaced with regex syntax to allow - * for namespace separators and the `is_regex` indicator will have been set to `true`. - * - * @since 1.2.0 - * - * @var array - */ - private $validated_namespace_prefixes = array(); - - /** - * Cache of previously set prefixes. - * - * Prevents having to do the same prefix validation over and over again. - * - * @since 0.12.0 - * - * @var string[] - */ - private $previous_prefixes = array(); - - /** - * A list of core hooks that are allowed to be called by plugins and themes. - * - * @since 0.14.0 - * @since 3.0.0 Renamed from `$whitelisted_core_hooks` to `$allowed_core_hooks`. - * - * @var array - */ - protected $allowed_core_hooks = array( - 'widget_title' => true, - 'add_meta_boxes' => true, - ); - - /** - * A list of core constants that are allowed to be defined by plugins and themes. - * - * @since 1.0.0 - * @since 3.0.0 Renamed from `$whitelisted_core_constants` to `$allowed_core_constants`. - * - * Source: {@link https://core.trac.wordpress.org/browser/trunk/src/wp-includes/default-constants.php#L0} - * The constants are listed in the order they are found in the source file - * to make life easier for future updates. - * Only overrulable constants are listed, i.e. those defined within core within - * a `if ( ! defined() ) {}` wrapper. - * - * @var array - */ - protected $allowed_core_constants = array( - 'WP_MEMORY_LIMIT' => true, - 'WP_MAX_MEMORY_LIMIT' => true, - 'WP_CONTENT_DIR' => true, - 'WP_DEBUG' => true, - 'WP_DEBUG_DISPLAY' => true, - 'WP_DEBUG_LOG' => true, - 'WP_CACHE' => true, - 'SCRIPT_DEBUG' => true, - 'MEDIA_TRASH' => true, - 'SHORTINIT' => true, - 'WP_CONTENT_URL' => true, - 'WP_PLUGIN_DIR' => true, - 'WP_PLUGIN_URL' => true, - 'PLUGINDIR' => true, - 'WPMU_PLUGIN_DIR' => true, - 'WPMU_PLUGIN_URL' => true, - 'MUPLUGINDIR' => true, - 'COOKIEHASH' => true, - 'USER_COOKIE' => true, - 'PASS_COOKIE' => true, - 'AUTH_COOKIE' => true, - 'SECURE_AUTH_COOKIE' => true, - 'LOGGED_IN_COOKIE' => true, - 'TEST_COOKIE' => true, - 'COOKIEPATH' => true, - 'SITECOOKIEPATH' => true, - 'ADMIN_COOKIE_PATH' => true, - 'PLUGINS_COOKIE_PATH' => true, - 'COOKIE_DOMAIN' => true, - 'RECOVERY_MODE_COOKIE' => true, - 'FORCE_SSL_ADMIN' => true, - 'FORCE_SSL_LOGIN' => true, - 'AUTOSAVE_INTERVAL' => true, - 'EMPTY_TRASH_DAYS' => true, - 'WP_POST_REVISIONS' => true, - 'WP_CRON_LOCK_TIMEOUT' => true, - 'WP_DEFAULT_THEME' => true, - ); - - /** - * List of all PHP native functions. - * - * Using this list rather than a call to `function_exists()` prevents - * false negatives from user-defined functions when those would be - * autoloaded via a Composer autoload files directives. - * - * @var array - */ - private $built_in_functions; - - - /** - * Returns an array of tokens this test wants to listen for. - * - * @since 0.12.0 - * - * @return array - */ - public function register() { - // Get a list of all PHP native functions. - $all_functions = get_defined_functions(); - $this->built_in_functions = array_flip( $all_functions['internal'] ); - - // Set the sniff targets. - $targets = array( - \T_NAMESPACE => \T_NAMESPACE, - \T_FUNCTION => \T_FUNCTION, - \T_CONST => \T_CONST, - \T_VARIABLE => \T_VARIABLE, - \T_DOLLAR => \T_DOLLAR, // Variable variables. - \T_FN_ARROW => \T_FN_ARROW, // T_FN_ARROW is only used for skipping over (for now). - ); - $targets += Tokens::$ooScopeTokens; // T_ANON_CLASS is only used for skipping over test classes. - $targets += Collections::listOpenTokensBC(); - - // Add function call target for hook names and constants defined using define(). - $parent = parent::register(); - if ( ! empty( $parent ) ) { - $targets[] = \T_STRING; - } - - return $targets; - } - - /** - * Groups of functions to restrict. - * - * @since 0.12.0 - * - * @return array - */ - public function getGroups() { - // Only retrieve functions which are not used for deprecated hooks. - $this->target_functions = WPHookHelper::get_functions( false ); - $this->target_functions['define'] = true; - - return parent::getGroups(); - } - - /** - * Processes this test, when one of its tokens is encountered. - * - * @since 0.12.0 - * - * @param int $stackPtr The position of the current token in the stack. - * - * @return int|void Integer stack pointer to skip forward or void to continue - * normal file processing. - */ - public function process_token( $stackPtr ) { - - // Allow overruling the prefixes set in a ruleset via the command line. - $cl_prefixes = Helper::getConfigData( 'prefixes' ); - if ( ! empty( $cl_prefixes ) ) { - $cl_prefixes = trim( $cl_prefixes ); - if ( '' !== $cl_prefixes ) { - $this->prefixes = array_filter( array_map( 'trim', explode( ',', $cl_prefixes ) ) ); - } - } - - $this->prefixes = RulesetPropertyHelper::merge_custom_array( $this->prefixes, array(), false ); - if ( empty( $this->prefixes ) ) { - // No prefixes passed, nothing to do. - return; - } - - $this->validate_prefixes(); - if ( empty( $this->validated_prefixes ) ) { - // No _valid_ prefixes passed, nothing to do. - return; - } - - // Ignore test classes. - if ( isset( Tokens::$ooScopeTokens[ $this->tokens[ $stackPtr ]['code'] ] ) - && true === $this->is_test_class( $this->phpcsFile, $stackPtr ) - ) { - if ( $this->tokens[ $stackPtr ]['scope_condition'] === $stackPtr && isset( $this->tokens[ $stackPtr ]['scope_closer'] ) ) { - // Skip forward to end of test class. - return $this->tokens[ $stackPtr ]['scope_closer']; - } - return; - } - - if ( \T_ANON_CLASS === $this->tokens[ $stackPtr ]['code'] ) { - // Token was only registered to allow skipping over test classes. - return; - } - - /* - * Ignore the contents of arrow functions which do not declare closures. - * - * - Parameters declared by arrow functions do not need to be prefixed (handled elsewhere). - * - New variables declared within an arrow function are local to the arrow function, so can be ignored. - * - A `global` statement is not allowed within an arrow function. - * - * Note: this does mean some convoluted code may get ignored (false negatives), but this is currently - * not reliably solvable as PHPCS does not add arrow functions to the 'conditions' array. - */ - if ( \T_FN_ARROW === $this->tokens[ $stackPtr ]['code'] - && isset( $this->tokens[ $stackPtr ]['scope_closer'] ) - ) { - $has_closure = $this->phpcsFile->findNext( \T_CLOSURE, ( $stackPtr + 1 ), $this->tokens[ $stackPtr ]['scope_closer'] ); - if ( false !== $has_closure ) { - // Skip to the start of the closure. - return $has_closure; - } - - // Skip the arrow function completely. - return $this->tokens[ $stackPtr ]['scope_closer']; - } - - if ( \T_STRING === $this->tokens[ $stackPtr ]['code'] ) { - // Disallow excluding function groups for this sniff. - $this->exclude = array(); - - return parent::process_token( $stackPtr ); - - } elseif ( \T_DOLLAR === $this->tokens[ $stackPtr ]['code'] ) { - - return $this->process_variable_variable( $stackPtr ); - - } elseif ( \T_VARIABLE === $this->tokens[ $stackPtr ]['code'] ) { - - return $this->process_variable_assignment( $stackPtr ); - - } elseif ( isset( Collections::listOpenTokensBC()[ $this->tokens[ $stackPtr ]['code'] ] ) ) { - return $this->process_list_assignment( $stackPtr ); - - } elseif ( \T_NAMESPACE === $this->tokens[ $stackPtr ]['code'] ) { - $namespace_name = Namespaces::getDeclaredName( $this->phpcsFile, $stackPtr ); - - if ( false === $namespace_name || '' === $namespace_name || '\\' === $namespace_name ) { - return; - } - - foreach ( $this->validated_namespace_prefixes as $key => $prefix_info ) { - if ( false === $prefix_info['is_regex'] ) { - if ( stripos( $namespace_name, $prefix_info['prefix'] ) === 0 ) { - $this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: allowed prefixes', $key ); - return; - } - } else { - // Ok, so this prefix should be used as a regex. - $regex = '`^' . $prefix_info['prefix'] . '`i'; - if ( preg_match( $regex, $namespace_name ) > 0 ) { - $this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: allowed prefixes', $key ); - return; - } - } - } - - // Still here ? In that case, we have a non-prefixed namespace name. - $recorded = $this->phpcsFile->addError( - self::ERROR_MSG, - $stackPtr, - 'NonPrefixedNamespaceFound', - array( - 'Namespaces declared', - $namespace_name, - ) - ); - - if ( true === $recorded ) { - $this->record_potential_prefix_metric( $stackPtr, $namespace_name ); - } - - return; - - } else { - - // Namespaced methods, classes and constants do not need to be prefixed. - $namespace = Namespaces::determineNamespace( $this->phpcsFile, $stackPtr ); - if ( '' !== $namespace && '\\' !== $namespace ) { - return; - } - - $item_name = ''; - $error_text = 'Unknown syntax used'; - $error_code = 'NonPrefixedSyntaxFound'; - - switch ( $this->tokens[ $stackPtr ]['code'] ) { - case \T_FUNCTION: - // Methods in a class do not need to be prefixed. - if ( Scopes::isOOMethod( $this->phpcsFile, $stackPtr ) === true ) { - return; - } - - if ( DeprecationHelper::is_function_deprecated( $this->phpcsFile, $stackPtr ) === true ) { - /* - * Deprecated functions don't have to comply with the naming conventions, - * otherwise functions deprecated in favour of a function with a compliant - * name would still trigger an error. - */ - return; - } - - $item_name = FunctionDeclarations::getName( $this->phpcsFile, $stackPtr ); - if ( isset( $this->built_in_functions[ $item_name ] ) ) { - // Backfill for PHP native function. - return; - } - - $error_text = 'Functions declared in the global namespace'; - $error_code = 'NonPrefixedFunctionFound'; - break; - - case \T_CLASS: - case \T_INTERFACE: - case \T_TRAIT: - case \T_ENUM: - $item_name = ObjectDeclarations::getName( $this->phpcsFile, $stackPtr ); - $error_text = 'Classes declared'; - $error_code = 'NonPrefixedClassFound'; - - switch ( $this->tokens[ $stackPtr ]['code'] ) { - case \T_CLASS: - if ( class_exists( '\\' . $item_name, false ) ) { - // Backfill for PHP native class. - return; - } - break; - - case \T_INTERFACE: - if ( interface_exists( '\\' . $item_name, false ) ) { - // Backfill for PHP native interface. - return; - } - - $error_text = 'Interfaces declared'; - $error_code = 'NonPrefixedInterfaceFound'; - break; - - case \T_TRAIT: - // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.trait_existsFound - if ( function_exists( '\trait_exists' ) && trait_exists( '\\' . $item_name, false ) ) { - // Backfill for PHP native trait. - return; - } - - $error_text = 'Traits declared'; - $error_code = 'NonPrefixedTraitFound'; - break; - - case \T_ENUM: - // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.enum_existsFound - if ( function_exists( '\enum_exists' ) && enum_exists( '\\' . $item_name, false ) ) { - // Backfill for PHP native enum. - return; - } - - $error_text = 'Enums declared'; - $error_code = 'NonPrefixedEnumFound'; - break; - } - - break; - - case \T_CONST: - // Constants in an OO construct do not need to be prefixed. - if ( true === Scopes::isOOConstant( $this->phpcsFile, $stackPtr ) ) { - return; - } - - $constant_name_ptr = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true ); - if ( false === $constant_name_ptr ) { - // Live coding. - return; - } - - $item_name = $this->tokens[ $constant_name_ptr ]['content']; - if ( \defined( '\\' . $item_name ) ) { - // Backfill for PHP native constant. - return; - } - - if ( isset( $this->allowed_core_constants[ $item_name ] ) ) { - // Defining a WP Core constant intended for overruling. - return; - } - - $error_text = 'Global constants defined'; - $error_code = 'NonPrefixedConstantFound'; - break; - - default: - // Left empty on purpose. - break; - - } - - if ( empty( $item_name ) || $this->is_prefixed( $stackPtr, $item_name ) === true ) { - return; - } - - $recorded = $this->phpcsFile->addError( - self::ERROR_MSG, - $stackPtr, - $error_code, - array( - $error_text, - $item_name, - ) - ); - - if ( true === $recorded ) { - $this->record_potential_prefix_metric( $stackPtr, $item_name ); - } - } - } - - /** - * Handle variable variables defined in the global namespace. - * - * @since 0.12.0 - * - * @param int $stackPtr The position of the current token in the stack. - * - * @return int|void Integer stack pointer to skip forward or void to continue - * normal file processing. - */ - protected function process_variable_variable( $stackPtr ) { - static $indicators = array( - \T_OPEN_CURLY_BRACKET => true, - \T_VARIABLE => true, - ); - - // Is this a variable variable ? - // Not concerned with nested ones as those will be recognized on their own token. - $next_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true ); - if ( false === $next_non_empty || ! isset( $indicators[ $this->tokens[ $next_non_empty ]['code'] ] ) ) { - return; - } - - if ( \T_OPEN_CURLY_BRACKET === $this->tokens[ $next_non_empty ]['code'] - && isset( $this->tokens[ $next_non_empty ]['bracket_closer'] ) - ) { - // Skip over the variable part. - $next_non_empty = $this->tokens[ $next_non_empty ]['bracket_closer']; - } - - $maybe_assignment = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $next_non_empty + 1 ), null, true, null, true ); - - while ( false !== $maybe_assignment - && \T_OPEN_SQUARE_BRACKET === $this->tokens[ $maybe_assignment ]['code'] - && isset( $this->tokens[ $maybe_assignment ]['bracket_closer'] ) - ) { - $maybe_assignment = $this->phpcsFile->findNext( - Tokens::$emptyTokens, - ( $this->tokens[ $maybe_assignment ]['bracket_closer'] + 1 ), - null, - true, - null, - true - ); - } - - if ( false === $maybe_assignment ) { - return; - } - - if ( ! isset( Tokens::$assignmentTokens[ $this->tokens[ $maybe_assignment ]['code'] ] ) ) { - // Not an assignment. - return; - } - - $error = self::ERROR_MSG; - - /* - * Local variable variables in a function do not need to be prefixed. - * But a variable variable could evaluate to the name of an imported global - * variable. - * Not concerned with imported variable variables (global.. ) as that has been - * forbidden since PHP 7.0. Presuming cross-version code and if not, that - * is for the PHPCompatibility standard to detect. - */ - $functionPtr = Conditions::getLastCondition( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); - if ( false !== $functionPtr ) { - $has_global = $this->phpcsFile->findPrevious( \T_GLOBAL, ( $stackPtr - 1 ), $this->tokens[ $functionPtr ]['scope_opener'] ); - if ( false === $has_global ) { - // No variable import happening. - return; - } - - $error = 'Variable variable which could potentially override an imported global variable detected. ' . $error; - } - - $variable_name = $this->phpcsFile->getTokensAsString( $stackPtr, ( ( $next_non_empty - $stackPtr ) + 1 ) ); - - // Still here ? In that case, the variable name should be prefixed. - $recorded = $this->phpcsFile->addWarning( - $error, - $stackPtr, - 'NonPrefixedVariableFound', - array( - 'Global variables defined', - $variable_name, - ) - ); - - if ( true === $recorded ) { - $this->record_potential_prefix_metric( $stackPtr, $variable_name ); - } - - // Skip over the variable part of the variable. - return ( $next_non_empty + 1 ); - } - - /** - * Check that defined global variables are prefixed. - * - * @since 0.12.0 - * @since 2.2.0 Added $in_list parameter. - * - * @param int $stackPtr The position of the current token in the stack. - * @param bool $in_list Whether or not this is a variable in a list assignment. - * Defaults to false. - * - * @return int|void Integer stack pointer to skip forward or void to continue - * normal file processing. - */ - protected function process_variable_assignment( $stackPtr, $in_list = false ) { - /* - * We're only concerned with variables which are being defined. - * `is_assigment()` will not recognize property assignments, which is good in this case. - * However it will also not recognize $b in `foreach( $a as $b )` as an assignment, so - * we need a separate check for that. - */ - if ( false === $in_list - && false === VariableHelper::is_assignment( $this->phpcsFile, $stackPtr ) - && Context::inForeachCondition( $this->phpcsFile, $stackPtr ) !== 'afterAs' - ) { - return; - } - - $is_error = true; - $variable_name = substr( $this->tokens[ $stackPtr ]['content'], 1 ); // Strip the dollar sign. - - // Bow out early if we know for certain no prefix is needed. - if ( 'GLOBALS' !== $variable_name - && $this->variable_prefixed_or_allowed( $stackPtr, $variable_name ) === true - ) { - return; - } - - if ( 'GLOBALS' === $variable_name ) { - $array_open = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true ); - if ( false === $array_open || \T_OPEN_SQUARE_BRACKET !== $this->tokens[ $array_open ]['code'] ) { - // Live coding or something very silly. - return; - } - - $array_key = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $array_open + 1 ), null, true, null, true ); - if ( false === $array_key ) { - // No key found, nothing to do. - return; - } - - $stackPtr = $array_key; - $variable_name = TextStrings::stripQuotes( $this->tokens[ $array_key ]['content'] ); - - // Check whether a prefix is needed. - if ( isset( Tokens::$stringTokens[ $this->tokens[ $array_key ]['code'] ] ) - && $this->variable_prefixed_or_allowed( $stackPtr, $variable_name ) === true - ) { - return; - } - - if ( \T_DOUBLE_QUOTED_STRING === $this->tokens[ $array_key ]['code'] ) { - // If the array key is a double quoted string, try again with only - // the part before the first variable (if any). - $exploded = explode( '$', $variable_name ); - $first = rtrim( $exploded[0], '{' ); - if ( '' !== $first ) { - if ( $this->variable_prefixed_or_allowed( $array_key, $first ) === true ) { - return; - } - } else { - // If the first part was dynamic, throw a warning. - $is_error = false; - } - } elseif ( ! isset( Tokens::$stringTokens[ $this->tokens[ $array_key ]['code'] ] ) ) { - // Dynamic array key, throw a warning. - $is_error = false; - } - } else { - // Function parameters do not need to be prefixed. - if ( false === $in_list ) { - $functionPtr = Parentheses::getLastOwner( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); - if ( false !== $functionPtr ) { - return; - } - unset( $functionPtr ); - } - - // Properties in a class do not need to be prefixed. - if ( false === $in_list && true === Scopes::isOOProperty( $this->phpcsFile, $stackPtr ) ) { - return; - } - - // Local variables in a function do not need to be prefixed unless they are being imported. - $functionPtr = Conditions::getLastCondition( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); - if ( false !== $functionPtr ) { - $has_global = $this->phpcsFile->findPrevious( \T_GLOBAL, ( $stackPtr - 1 ), $this->tokens[ $functionPtr ]['scope_opener'] ); - if ( false === $has_global - || Conditions::getLastCondition( $this->phpcsFile, $has_global, Collections::functionDeclarationTokens() ) !== $functionPtr - ) { - // No variable import happening in the current scope. - return; - } - - // Ok, this may be an imported global variable. - $end_of_statement = $this->phpcsFile->findNext( array( \T_SEMICOLON, \T_CLOSE_TAG ), ( $has_global + 1 ) ); - if ( false === $end_of_statement ) { - // No semi-colon - live coding. - return; - } - - for ( $ptr = ( $has_global + 1 ); $ptr <= $end_of_statement; $ptr++ ) { - // Move the stack pointer to the next variable. - $ptr = $this->phpcsFile->findNext( \T_VARIABLE, $ptr, $end_of_statement, false, null, true ); - - if ( false === $ptr ) { - // Reached the end of the global statement without finding the variable, - // so this must be a local variable. - return; - } - - if ( substr( $this->tokens[ $ptr ]['content'], 1 ) === $variable_name ) { - break; - } - } - - unset( $has_global, $end_of_statement, $ptr, $imported ); - } - } - - // Still here ? In that case, the variable name should be prefixed. - $recorded = MessageHelper::addMessage( - $this->phpcsFile, - self::ERROR_MSG, - $stackPtr, - $is_error, - 'NonPrefixedVariableFound', - array( - 'Global variables defined', - '$' . $variable_name, - ) - ); - - if ( true === $recorded ) { - $this->record_potential_prefix_metric( $stackPtr, $variable_name ); - } - } - - /** - * Check that global variables declared via a list construct are prefixed. - * - * @internal No need to take special measures for nested lists. Nested or not, - * each list part can only contain one variable being written to. - * - * @since 2.2.0 - * - * @param int $stackPtr The position of the current token in the stack. - * - * @return int|void Integer stack pointer to skip forward or void to continue - * normal file processing. - */ - protected function process_list_assignment( $stackPtr ) { - $list_open_close = Lists::getOpenClose( $this->phpcsFile, $stackPtr ); - if ( false === $list_open_close ) { - // Short array, not short list. - return; - } - - $var_pointers = $this->get_list_variables( $stackPtr, $list_open_close ); - foreach ( $var_pointers as $ptr ) { - $this->process_variable_assignment( $ptr, true ); - } - - // No need to re-examine these variables. - return $list_open_close['closer']; - } - - /** - * Process the parameters of a matched function. - * - * @since 0.12.0 - * - * @param int $stackPtr The position of the current token in the stack. - * @param string $group_name The name of the group which was matched. - * @param string $matched_content The token content (function name) which was matched. - * @param array $parameters Array with information about the parameters. - * - * @return void - */ - public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { - if ( 'define' === $matched_content ) { - $target_param = PassedParameters::getParameterFromStack( $parameters, 1, 'constant_name' ); - - } else { - $target_param = WPHookHelper::get_hook_name_param( $matched_content, $parameters ); - } - - if ( false === $target_param ) { - return; - } - - $is_error = true; - $clean_content = TextStrings::stripQuotes( $target_param['clean'] ); - - if ( ( 'define' !== $matched_content - && isset( $this->allowed_core_hooks[ $clean_content ] ) ) - || ( 'define' === $matched_content - && isset( $this->allowed_core_constants[ $clean_content ] ) ) - ) { - return; - } - - if ( $this->is_prefixed( $target_param['start'], $clean_content ) === true ) { - return; - } else { - // This may be a dynamic hook/constant name. - $first_non_empty = $this->phpcsFile->findNext( - Tokens::$emptyTokens, - $target_param['start'], - ( $target_param['end'] + 1 ), - true - ); - - if ( false === $first_non_empty ) { - return; - } - - $first_non_empty_content = TextStrings::stripQuotes( $this->tokens[ $first_non_empty ]['content'] ); - - // Try again with just the first token if it's a text string. - if ( isset( Tokens::$stringTokens[ $this->tokens[ $first_non_empty ]['code'] ] ) - && $this->is_prefixed( $target_param['start'], $first_non_empty_content ) === true - ) { - return; - } - - if ( \T_DOUBLE_QUOTED_STRING === $this->tokens[ $first_non_empty ]['code'] ) { - // If the first part of the parameter is a double quoted string, try again with only - // the part before the first variable (if any). - $exploded = explode( '$', $first_non_empty_content ); - $first = rtrim( $exploded[0], '{' ); - if ( '' !== $first ) { - if ( $this->is_prefixed( $target_param['start'], $first ) === true ) { - return; - } - } else { - // Start of hook/constant name is dynamic, throw a warning. - $is_error = false; - } - } elseif ( ! isset( Tokens::$stringTokens[ $this->tokens[ $first_non_empty ]['code'] ] ) ) { - // Dynamic hook/constant name, throw a warning. - $is_error = false; - } - } - - if ( 'define' === $matched_content ) { - if ( \defined( '\\' . $clean_content ) ) { - // Backfill for PHP native constant. - return; - } - - if ( strpos( $clean_content, '\\' ) !== false ) { - // Namespaced or unreachable constant. - return; - } - - $data = array( 'Global constants defined' ); - $error_code = 'NonPrefixedConstantFound'; - if ( false === $is_error ) { - $error_code = 'VariableConstantNameFound'; - } - } else { - $data = array( 'Hook names invoked' ); - $error_code = 'NonPrefixedHooknameFound'; - if ( false === $is_error ) { - $error_code = 'DynamicHooknameFound'; - } - } - - $data[] = $clean_content; - - $recorded = MessageHelper::addMessage( $this->phpcsFile, self::ERROR_MSG, $first_non_empty, $is_error, $error_code, $data ); - - if ( true === $recorded ) { - $this->record_potential_prefix_metric( $stackPtr, $clean_content ); - } - } - - /** - * Check if a function/class/constant/variable name is prefixed with one of the expected prefixes. - * - * @since 0.12.0 - * @since 0.14.0 Allows for other non-word characters as well as underscores to better support hook names. - * @since 1.0.0 Does not require a word seperator anymore after a prefix. - * This allows for improved code style independent checking, - * i.e. allows for camelCase naming and the likes. - * @since 1.0.1 - Added $stackPtr parameter. - * - The function now also records metrics about the prefixes encountered. - * - * @param int $stackPtr The position of the token to record the metric against. - * @param string $name Name to check for a prefix. - * - * @return bool True when the name is one of the prefixes or starts with an allowed prefix. - * False otherwise. - */ - private function is_prefixed( $stackPtr, $name ) { - foreach ( $this->validated_prefixes as $prefix ) { - if ( stripos( $name, $prefix ) === 0 ) { - $this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: allowed prefixes', $prefix ); - return true; - } - } - - return false; - } - - /** - * Check if a variable name might need a prefix. - * - * Prefix is not needed for: - * - superglobals, - * - WP native globals, - * - variables which are already prefixed. - * - * @since 0.12.0 - * @since 1.0.1 Added $stackPtr parameter. - * @since 3.0.0 Renamed from `variable_prefixed_or_whitelisted()` to `variable_prefixed_or_allowed()`. - * - * @param int $stackPtr The position of the token to record the metric against. - * @param string $name Variable name without the dollar sign. - * - * @return bool True if the variable name is allowed or already prefixed. - * False otherwise. - */ - private function variable_prefixed_or_allowed( $stackPtr, $name ) { - // Ignore superglobals and WP global variables. - if ( Variables::isSuperglobalName( $name ) || WPGlobalVariablesHelper::is_wp_global( $name ) ) { - return true; - } - - return $this->is_prefixed( $stackPtr, $name ); - } - - /** - * Validate an array of prefixes as passed through a custom property or via the command line. - * - * Checks that the prefix: - * - is not one of the blocked ones. - * - complies with the PHP rules for valid function, class, variable, constant names. - * - * @since 0.12.0 - */ - private function validate_prefixes() { - if ( $this->previous_prefixes === $this->prefixes ) { - return; - } - - // Set the cache *before* validation so as to not break the above compare. - $this->previous_prefixes = $this->prefixes; - - // Validate the passed prefix(es). - $prefixes = array(); - $ns_prefixes = array(); - foreach ( $this->prefixes as $key => $prefix ) { - $prefixLC = strtolower( $prefix ); - - if ( isset( $this->prefix_blocklist[ $prefixLC ] ) ) { - $this->phpcsFile->addError( - 'The "%s" prefix is not allowed.', - 0, - 'ForbiddenPrefixPassed', - array( $prefix ) - ); - continue; - } - - $prefix_length = strlen( $prefix ); - if ( function_exists( 'iconv_strlen' ) ) { - $prefix_length = iconv_strlen( $prefix, Helper::getEncoding( $this->phpcsFile ) ); - } - - if ( $prefix_length < self::MIN_PREFIX_LENGTH ) { - $this->phpcsFile->addError( - 'The "%s" prefix is too short. Short prefixes are not unique enough and may cause name collisions with other code.', - 0, - 'ShortPrefixPassed', - array( $prefix ) - ); - continue; - } - - /* - * Validate the prefix against characters allowed for function, class, constant names etc. - * Note: this does not use the PHPCSUtils `NamingConventions::isValidIdentifierName()` method - * as we want to allow namespace separators in the prefixes. - */ - if ( preg_match( '`^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff\\\\]*$`', $prefix ) !== 1 ) { - - $this->phpcsFile->addWarning( - 'The "%s" prefix is not a valid namespace/function/class/variable/constant prefix in PHP.', - 0, - 'InvalidPrefixPassed', - array( $prefix ) - ); - } - - // Lowercase the prefix to allow for direct compare. - $prefixes[ $key ] = $prefixLC; - - /* - * Replace non-word characters in the prefix with a regex snippet, but only if the - * string doesn't already contain namespace separators. - */ - $is_regex = false; - if ( strpos( $prefix, '\\' ) === false && preg_match( '`[_\W]`', $prefix ) > 0 ) { - $prefix = preg_replace( '`([_\W])`', '[\\\\\\\\$1]', $prefixLC ); - $is_regex = true; - } - - $ns_prefixes[ $prefixLC ] = array( - 'prefix' => $prefix, - 'is_regex' => $is_regex, - ); - } - - // Set the validated prefixes caches. - $this->validated_prefixes = $prefixes; - $this->validated_namespace_prefixes = $ns_prefixes; - } - - /** - * Record the "potential prefix" metric. - * - * @since 1.0.1 - * - * @param int $stackPtr The position of the token to record the metric against. - * @param string $construct_name Name of the global construct to try and distill a potential prefix from. - * - * @return void - */ - private function record_potential_prefix_metric( $stackPtr, $construct_name ) { - if ( preg_match( '`^([A-Z]*[a-z0-9]*+)`', ltrim( $construct_name, '\$_' ), $matches ) > 0 - && isset( $matches[1] ) && '' !== $matches[1] - ) { - $this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: potential prefixes - start of non-prefixed construct', strtolower( $matches[1] ) ); - } - } -} From 3b650ad9b24aedc7205011a7430d7a9278c0e128 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 17:11:13 +0200 Subject: [PATCH 05/49] Fix sniff's name. --- ...unctionName.php => ValidBlockLibraryFunctionNameSniff.php} | 4 ++-- test/php/gutenberg-coding-standards/Gutenberg/ruleset.xml | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) rename test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/{ValidBlockLibraryFunctionName.php => ValidBlockLibraryFunctionNameSniff.php} (96%) diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionName.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php similarity index 96% rename from test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionName.php rename to test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php index 789ca220d18200..c15f74dc23fee3 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionName.php +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php @@ -97,8 +97,8 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { $functionName = $tokens[ $functionToken ]['content']; - foreach ( $this->whitelistedFunctions as $functionRegExp ) { - if ( preg_match( $functionRegExp, $functionName ) ) { + foreach ( $this->prefixes as $prefix ) { + if ( 0 === stripos( $functionName, $prefix ) ) { // Ignore whitelisted function names. return; } diff --git a/test/php/gutenberg-coding-standards/Gutenberg/ruleset.xml b/test/php/gutenberg-coding-standards/Gutenberg/ruleset.xml index e899c9bed05286..784dfd9a1b2be3 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/ruleset.xml +++ b/test/php/gutenberg-coding-standards/Gutenberg/ruleset.xml @@ -4,5 +4,6 @@ Gutenberg Coding Standards + From ce561b104d0c117e64e722c8b97b0bcea0bf047d Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 18:40:36 +0200 Subject: [PATCH 06/49] List allowed function names in the error message. --- .../ValidBlockLibraryFunctionNameSniff.php | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php index c15f74dc23fee3..bd61e94844e3b0 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php @@ -95,14 +95,26 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { } } - $functionName = $tokens[ $functionToken ]['content']; + $functionName = $tokens[ $functionToken ]['content']; + $parent_directory_name = basename( dirname( $phpcsFile->getFilename() ) ); + $allowed_function_names = array(); foreach ( $this->prefixes as $prefix ) { - if ( 0 === stripos( $functionName, $prefix ) ) { - // Ignore whitelisted function names. - return; - } + $prefix = rtrim( $prefix, '_' ); + $allowed_function_names[] = $prefix . '_' . str_replace( '-', '_', $parent_directory_name ); + } + + $is_function_name_valid = false; + foreach ( $allowed_function_names as $allowed_function_name ) { + $is_function_name_valid |= 0 === strpos( $functionName, $allowed_function_name ); } + + if ( $is_function_name_valid ) { + return; + } + + $errorMessage = 'Only the following PHP function names are allowed in this index.php file: "' . implode( '", "', $allowed_function_names ) . '"'; + $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameInvalid' ); } /** From 10eae71789217714797dea55de8eea0e688db429 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 19:21:51 +0200 Subject: [PATCH 07/49] 1. Fix doc blocks. 2. Return early if there are no prefixes. --- .../ValidBlockLibraryFunctionNameSniff.php | 27 ++++++++----------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php index bd61e94844e3b0..e02346ea5d3818 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php @@ -13,12 +13,6 @@ use PHP_CodeSniffer\Sniffs\Sniff; /** - * The sniff implements the Gutenberg coding standard to verify whether functions and classes - * are enclosed with function_exists() and !class_exists(). This check ensures that the functions - * and classes are not already defined, and recommends the use of function_exists() and class_exists() - * to prevent fatal errors during the integration of the feature to the Core. - * - * @link https://github.com/WordPress/gutenberg/blob/trunk/lib/README.md#wrap-functions-and-classes-with--function_exists-and--class_exists * * @package gutenberg/gutenberg-coding-standards * @@ -66,11 +60,6 @@ public function process( File $phpcsFile, $stackPtr ) { } /** - * Functions should be wrapped with !function_exists() to avoid fatal errors. - * E.g.: - * if ( ! function_exists( 'wp_get_navigation' ) ) { - * function wp_get_navigation( $slug ) { ... } - * } * * @param File $phpcsFile The file being scanned. * @param int $stackPointer The position of the current token @@ -79,6 +68,12 @@ public function process( File $phpcsFile, $stackPtr ) { * @return void */ private function processFunctionToken( File $phpcsFile, $stackPointer ) { + + if ( empty( $this->prefixes ) ) { + // Nothing to process. + return; + } + $tokens = $phpcsFile->getTokens(); $functionToken = $phpcsFile->findNext( T_STRING, $stackPointer ); @@ -98,14 +93,14 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { $functionName = $tokens[ $functionToken ]['content']; $parent_directory_name = basename( dirname( $phpcsFile->getFilename() ) ); - $allowed_function_names = array(); + $allowed_function_prefixes = array(); foreach ( $this->prefixes as $prefix ) { - $prefix = rtrim( $prefix, '_' ); - $allowed_function_names[] = $prefix . '_' . str_replace( '-', '_', $parent_directory_name ); + $prefix = rtrim( $prefix, '_' ); + $allowed_function_prefixes[] = $prefix . '_' . str_replace( '-', '_', $parent_directory_name ); } $is_function_name_valid = false; - foreach ( $allowed_function_names as $allowed_function_name ) { + foreach ( $allowed_function_prefixes as $allowed_function_name ) { $is_function_name_valid |= 0 === strpos( $functionName, $allowed_function_name ); } @@ -113,7 +108,7 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { return; } - $errorMessage = 'Only the following PHP function names are allowed in this index.php file: "' . implode( '", "', $allowed_function_names ) . '"'; + $errorMessage = 'In this index.php file, only the following prefixes for PHP function names are allowed: "1", "2", and "3".: "' . implode( '", "', $allowed_function_prefixes ) . '"'; $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameInvalid' ); } From 332f00321214e2167515d0b688836fcc9a589975 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 19:23:47 +0200 Subject: [PATCH 08/49] Fix error message. --- .../NamingConventions/ValidBlockLibraryFunctionNameSniff.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php index e02346ea5d3818..47e1b1384d7da2 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php @@ -108,7 +108,7 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { return; } - $errorMessage = 'In this index.php file, only the following prefixes for PHP function names are allowed: "1", "2", and "3".: "' . implode( '", "', $allowed_function_prefixes ) . '"'; + $errorMessage = 'In this file, only the following prefixes for PHP function names are allowed: "' . implode( '", "', $allowed_function_prefixes ) . '"'; $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameInvalid' ); } From 8f74d2adea8ad342bf67f57bbcce74e44096b6a4 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 19:32:18 +0200 Subject: [PATCH 09/49] Improve error message. --- .../NamingConventions/ValidBlockLibraryFunctionNameSniff.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php index 47e1b1384d7da2..ab64f5dfa956c0 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php @@ -108,7 +108,7 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { return; } - $errorMessage = 'In this file, only the following prefixes for PHP function names are allowed: "' . implode( '", "', $allowed_function_prefixes ) . '"'; + $errorMessage = 'Only the following prefixes for PHP function names are allowed in this file: "' . implode( '", "', $allowed_function_prefixes ) . '"'; $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameInvalid' ); } From 081259d4f496526e2b9c3f840139639026964c4a Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 19:33:10 +0200 Subject: [PATCH 10/49] Add the new rule to the phpcs.xml.dist file. --- phpcs.xml.dist | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index deefb843dd4e66..49cc4cecda04b3 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -128,4 +128,15 @@ + + + ./packages/block-library/src/*/index.php + + + + + + + + From 5bdb79e839140708d3fc537b958890be53696418 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 19:46:54 +0200 Subject: [PATCH 11/49] Add doing it wrong as dynamic properties are not supported in PHP 8.2 and above. --- .../NamingConventions/ValidBlockLibraryFunctionNameSniff.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php index ab64f5dfa956c0..79b7b2c9f7c68c 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php @@ -108,7 +108,8 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { return; } - $errorMessage = 'Only the following prefixes for PHP function names are allowed in this file: "' . implode( '", "', $allowed_function_prefixes ) . '"'; + $errorMessage = "The function name \"{$functionName}\" is invalid because function names in this file should start with one of the following prefixes: \"" + . implode( '", "', $allowed_function_prefixes ) . '"'; $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameInvalid' ); } From 975187f7e9c7c51bf31715c27dd8ba4267e52edf Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 19:50:18 +0200 Subject: [PATCH 12/49] Improve error message. --- .../NamingConventions/ValidBlockLibraryFunctionNameSniff.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php index 79b7b2c9f7c68c..82a4fe98d319e1 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php @@ -108,7 +108,7 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { return; } - $errorMessage = "The function name \"{$functionName}\" is invalid because function names in this file should start with one of the following prefixes: \"" + $errorMessage = "The function name \"{$functionName}()\" is invalid because function names in this file should start with one of the following prefixes: \"" . implode( '", "', $allowed_function_prefixes ) . '"'; $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameInvalid' ); } From 156311648132f88856c6326786026ac23ce8e9cf Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 19:59:04 +0200 Subject: [PATCH 13/49] Improve error message. --- .../NamingConventions/ValidBlockLibraryFunctionNameSniff.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php index 82a4fe98d319e1..f21797df607e29 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php @@ -108,7 +108,7 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { return; } - $errorMessage = "The function name \"{$functionName}()\" is invalid because function names in this file should start with one of the following prefixes: \"" + $errorMessage = "The function name \"{$functionName}()\" is invalid because PHP function names in this file should start with one of the following prefixes: \"" . implode( '", "', $allowed_function_prefixes ) . '"'; $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameInvalid' ); } From c3a6cdc250709a6b05ea9137b9b22dd843900742 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Tue, 8 Aug 2023 20:12:08 +0200 Subject: [PATCH 14/49] Improve error message. --- .../NamingConventions/ValidBlockLibraryFunctionNameSniff.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php index f21797df607e29..5ea8e082d3035d 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php @@ -109,7 +109,7 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { } $errorMessage = "The function name \"{$functionName}()\" is invalid because PHP function names in this file should start with one of the following prefixes: \"" - . implode( '", "', $allowed_function_prefixes ) . '"'; + . implode( '", "', $allowed_function_prefixes ) . '".'; $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameInvalid' ); } From addaea8c0bfacf71cd4daae6e316d98370123882 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko <43744263+anton-vlasenko@users.noreply.github.com> Date: Wed, 9 Aug 2023 14:36:10 +0200 Subject: [PATCH 15/49] Ensure that the rule checks all PHP files, not just the index.php files. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Greg Ziółkowski --- phpcs.xml.dist | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 49cc4cecda04b3..80727fd888299e 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -130,7 +130,7 @@ - ./packages/block-library/src/*/index.php + ./packages/block-library/src/*/*.php From 8bf5c729dabab08d34f433e6a8c5bb15258d9e3d Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 15:03:41 +0200 Subject: [PATCH 16/49] Refactor variable names to use lowercase. --- .../ValidBlockLibraryFunctionNameSniff.php | 28 +++++++++---------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php index 5ea8e082d3035d..6a8180b47175b6 100644 --- a/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php +++ b/test/php/gutenberg-coding-standards/Gutenberg/Sniffs/NamingConventions/ValidBlockLibraryFunctionNameSniff.php @@ -75,47 +75,45 @@ private function processFunctionToken( File $phpcsFile, $stackPointer ) { } $tokens = $phpcsFile->getTokens(); - $functionToken = $phpcsFile->findNext( T_STRING, $stackPointer ); + $function_token = $phpcsFile->findNext( T_STRING, $stackPointer ); - $wrappingTokensToCheck = array( + $wrapping_tokens_to_check = array( T_CLASS, T_INTERFACE, T_TRAIT, ); - foreach ( $wrappingTokensToCheck as $wrappingTokenToCheck ) { - if ( false !== $phpcsFile->getCondition( $functionToken, $wrappingTokenToCheck, false ) ) { + foreach ( $wrapping_tokens_to_check as $wrapping_token_to_check ) { + if ( false !== $phpcsFile->getCondition( $function_token, $wrapping_token_to_check, false ) ) { // This sniff only processes functions, not class methods. return; } } - $functionName = $tokens[ $functionToken ]['content']; + $function_name = $tokens[ $function_token ]['content']; $parent_directory_name = basename( dirname( $phpcsFile->getFilename() ) ); $allowed_function_prefixes = array(); + $is_function_name_valid = false; foreach ( $this->prefixes as $prefix ) { $prefix = rtrim( $prefix, '_' ); - $allowed_function_prefixes[] = $prefix . '_' . str_replace( '-', '_', $parent_directory_name ); - } - - $is_function_name_valid = false; - foreach ( $allowed_function_prefixes as $allowed_function_name ) { - $is_function_name_valid |= 0 === strpos( $functionName, $allowed_function_name ); + $allowed_function_prefix = $prefix . '_' . str_replace( '-', '_', $parent_directory_name ); + $allowed_function_prefixes[] = $allowed_function_prefix; + $is_function_name_valid |= 0 === strpos( $function_name, $allowed_function_prefix ); } if ( $is_function_name_valid ) { return; } - $errorMessage = "The function name \"{$functionName}()\" is invalid because PHP function names in this file should start with one of the following prefixes: \"" + $error_message = "The function name \"{$function_name}()\" is invalid because PHP function names in this file should start with one of the following prefixes: \"" . implode( '", "', $allowed_function_prefixes ) . '".'; - $phpcsFile->addError( $errorMessage, $functionToken, 'FunctionNameInvalid' ); + $phpcsFile->addError( $error_message, $function_token, 'FunctionNameInvalid' ); } /** - * The purpose of this method is to sanitize the input data - * after the properties have been set. + * The purpose of this method is to run callbacks + * after the class properties have been set. */ private function onRegisterEvent() { $this->prefixes = self::sanitize( $this->prefixes ); From ecc45fda775ca4d90c13f28ecfa8603352828c60 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 16:44:26 +0200 Subject: [PATCH 17/49] Add exceptions to ValidBlockLibraryFunctionName rule. --- packages/block-library/src/comments/index.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/block-library/src/comments/index.php b/packages/block-library/src/comments/index.php index 48aac15af6fbb6..52decf686c99a7 100644 --- a/packages/block-library/src/comments/index.php +++ b/packages/block-library/src/comments/index.php @@ -97,12 +97,14 @@ function register_block_core_comments() { /** * Use the button block classes for the form-submit button. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $fields The default comment form arguments. * * @return array Returns the modified fields. */ function comments_block_form_defaults( $fields ) { + //phpcs:enable if ( wp_is_block_theme() ) { $fields['submit_button'] = ''; $fields['submit_field'] = '

%1$s %2$s

'; @@ -115,10 +117,12 @@ function comments_block_form_defaults( $fields ) { /** * Enqueues styles from the legacy `core/post-comments` block. These styles are * required only by the block's fallback. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param string $block_name Name of the new block type. */ function enqueue_legacy_post_comments_block_styles( $block_name ) { + //phpcs:enable static $are_styles_enqueued = false; if ( ! $are_styles_enqueued ) { @@ -140,11 +144,13 @@ function enqueue_legacy_post_comments_block_styles( $block_name ) { * * The same approach was followed when core/query-loop was renamed to * core/post-template. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @see https://github.com/WordPress/gutenberg/pull/41807 * @see https://github.com/WordPress/gutenberg/pull/32514 */ function register_legacy_post_comments_block() { + //phpcs:enable $registry = WP_Block_Type_Registry::get_instance(); /* From a3ef82a614bf3072321bf94ed4276e078a4a6d44 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 16:52:06 +0200 Subject: [PATCH 18/49] Add exceptions to ValidBlockLibraryFunctionName rule. --- packages/block-library/src/site-logo/index.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/block-library/src/site-logo/index.php b/packages/block-library/src/site-logo/index.php index f1819fcaac8d03..069dbbbdeb383e 100644 --- a/packages/block-library/src/site-logo/index.php +++ b/packages/block-library/src/site-logo/index.php @@ -79,8 +79,10 @@ function register_block_core_site_logo_setting() { /** * Register a core site setting for a site icon + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName */ function register_block_core_site_icon_setting() { + //phpcs:enable register_setting( 'general', 'site_icon', @@ -110,12 +112,14 @@ function register_block_core_site_logo() { /** * Overrides the custom logo with a site logo, if the option is set. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param string $custom_logo The custom logo set by a theme. * * @return string The site logo if set. */ function _override_custom_logo_theme_mod( $custom_logo ) { + //phpcs:enable $site_logo = get_option( 'site_logo' ); return false === $site_logo ? $custom_logo : $site_logo; } @@ -124,11 +128,13 @@ function _override_custom_logo_theme_mod( $custom_logo ) { /** * Updates the site_logo option when the custom_logo theme-mod gets updated. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param mixed $value Attachment ID of the custom logo or an empty value. * @return mixed */ function _sync_custom_logo_to_site_logo( $value ) { + //phpcs:enable if ( empty( $value ) ) { delete_option( 'site_logo' ); } else { @@ -142,11 +148,13 @@ function _sync_custom_logo_to_site_logo( $value ) { /** * Deletes the site_logo when the custom_logo theme mod is removed. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $old_value Previous theme mod settings. * @param array $value Updated theme mod settings. */ function _delete_site_logo_on_remove_custom_logo( $old_value, $value ) { + //phpcs:enable global $_ignore_site_logo_changes; if ( $_ignore_site_logo_changes ) { @@ -161,8 +169,10 @@ function _delete_site_logo_on_remove_custom_logo( $old_value, $value ) { /** * Deletes the site logo when all theme mods are being removed. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName */ function _delete_site_logo_on_remove_theme_mods() { + //phpcs:enable global $_ignore_site_logo_changes; if ( $_ignore_site_logo_changes ) { @@ -179,8 +189,10 @@ function _delete_site_logo_on_remove_theme_mods() { * Hooks `_delete_site_logo_on_remove_theme_mods` in `delete_option_theme_mods_$theme`. * * Runs on `setup_theme` to account for dynamically-switched themes in the Customizer. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName */ function _delete_site_logo_on_remove_custom_logo_on_setup_theme() { + //phpcs:enable $theme = get_option( 'stylesheet' ); add_action( "update_option_theme_mods_$theme", '_delete_site_logo_on_remove_custom_logo', 10, 2 ); add_action( "delete_option_theme_mods_$theme", '_delete_site_logo_on_remove_theme_mods' ); @@ -189,8 +201,10 @@ function _delete_site_logo_on_remove_custom_logo_on_setup_theme() { /** * Removes the custom_logo theme-mod when the site_logo option gets deleted. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName */ function _delete_custom_logo_on_remove_site_logo() { + //phpcs:enable global $_ignore_site_logo_changes; // Prevent _delete_site_logo_on_remove_custom_logo and From c6029de9d0d529853a68a6e97821a088204bba2a Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 16:54:06 +0200 Subject: [PATCH 19/49] Add exceptions to ValidBlockLibraryFunctionName rule. --- packages/block-library/src/navigation-link/index.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/block-library/src/navigation-link/index.php b/packages/block-library/src/navigation-link/index.php index 5333ab6ea3dc9e..916976ad0f8c39 100644 --- a/packages/block-library/src/navigation-link/index.php +++ b/packages/block-library/src/navigation-link/index.php @@ -264,6 +264,7 @@ function render_block_core_navigation_link( $attributes, $content, $block ) { /** * Returns a navigation link variation + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param WP_Taxonomy|WP_Post_Type $entity post type or taxonomy entity. * @param string $kind string of value 'taxonomy' or 'post-type'. @@ -271,6 +272,7 @@ function render_block_core_navigation_link( $attributes, $content, $block ) { * @return array */ function build_variation_for_navigation_link( $entity, $kind ) { + //phpcs:enable $title = ''; $description = ''; From 1e54af8b9870762f2ee8aeb6fa5c3dfde6417bad Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 16:55:30 +0200 Subject: [PATCH 20/49] Add exceptions to ValidBlockLibraryFunctionName rule. --- packages/block-library/src/file/index.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/block-library/src/file/index.php b/packages/block-library/src/file/index.php index 7dd77b20f466c0..b3752b19083dec 100644 --- a/packages/block-library/src/file/index.php +++ b/packages/block-library/src/file/index.php @@ -8,12 +8,14 @@ if ( gutenberg_should_block_use_interactivity_api( 'core/file' ) ) { /** * Replaces view script for the File block with version using Interactivity API. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $metadata Block metadata as read in via block.json. * * @return array Filtered block type metadata. */ function gutenberg_block_core_file_update_interactive_view_script( $metadata ) { + //phpcs:enable if ( 'core/file' === $metadata['name'] ) { $metadata['viewScript'] = array( 'file:./view-interactivity.min.js' ); $metadata['supports']['interactivity'] = true; From a51c0ba0063a5e2cf6c64739f15d919a26dbdbbb Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 16:56:50 +0200 Subject: [PATCH 21/49] Add exceptions to ValidBlockLibraryFunctionName rule. --- packages/block-library/src/navigation/index.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/block-library/src/navigation/index.php b/packages/block-library/src/navigation/index.php index 52376aba0d44e1..b46b23bccaebf3 100644 --- a/packages/block-library/src/navigation/index.php +++ b/packages/block-library/src/navigation/index.php @@ -144,12 +144,14 @@ function block_core_navigation_add_directives_to_submenu( $w, $block_attributes /** * Replaces view script for the Navigation block with version using Interactivity API. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $metadata Block metadata as read in via block.json. * * @return array Filtered block type metadata. */ function gutenberg_block_core_navigation_update_interactive_view_script( $metadata ) { + //phpcs:enable if ( 'core/navigation' === $metadata['name'] ) { $metadata['viewScript'] = array( 'file:./view-interactivity.min.js' ); $metadata['supports']['interactivity'] = true; From 32c3a27f1748824eac5614b4e6723647d8f4502f Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 16:59:25 +0200 Subject: [PATCH 22/49] Add exceptions to ValidBlockLibraryFunctionName rule. --- packages/block-library/src/template-part/index.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/block-library/src/template-part/index.php b/packages/block-library/src/template-part/index.php index a7bd4033affc34..e35727263427de 100644 --- a/packages/block-library/src/template-part/index.php +++ b/packages/block-library/src/template-part/index.php @@ -170,12 +170,14 @@ function render_block_core_template_part( $attributes ) { /** * Returns an array of area variation objects for the template part block. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $instance_variations The variations for instances. * * @return array Array containing the block variation objects. */ function build_template_part_block_area_variations( $instance_variations ) { + //phpcs:enable $variations = array(); $defined_areas = get_allowed_block_template_part_areas(); @@ -208,10 +210,12 @@ function build_template_part_block_area_variations( $instance_variations ) { /** * Returns an array of instance variation objects for the template part block + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @return array Array containing the block variation objects. */ function build_template_part_block_instance_variations() { + //phpcs:enable // Block themes are unavailable during installation. if ( wp_installing() ) { return array(); @@ -262,10 +266,12 @@ function build_template_part_block_instance_variations() { /** * Returns an array of all template part block variations. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @return array Array containing the block variation objects. */ function build_template_part_block_variations() { + //phpcs:enable $instance_variations = build_template_part_block_instance_variations(); $area_variations = build_template_part_block_area_variations( $instance_variations ); return array_merge( $area_variations, $instance_variations ); From 0ee1871b0b60ab59cd2d3ebecec131eb46e29636 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 17:05:46 +0200 Subject: [PATCH 23/49] Add exceptions to the ValidBlockLibraryFunctionName rule. --- packages/block-library/src/search/index.php | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/block-library/src/search/index.php b/packages/block-library/src/search/index.php index 670ceb0eb66c54..2d0f7987d05133 100644 --- a/packages/block-library/src/search/index.php +++ b/packages/block-library/src/search/index.php @@ -184,12 +184,14 @@ function register_block_core_search() { /** * Builds the correct top level classnames for the 'core/search' block. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes The block attributes. * * @return string The classnames used in the block. */ function classnames_for_block_core_search( $attributes ) { + //phpcs:enable $classnames = array(); if ( ! empty( $attributes['buttonPosition'] ) ) { @@ -231,6 +233,7 @@ function classnames_for_block_core_search( $attributes ) { * Based on whether the Search block is configured to display the button inside * or not, the generated rule is injected into the appropriate collection of * styles for later application in the block's markup. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes The block attributes. * @param string $property Border property to generate rule for e.g. width or color. @@ -242,6 +245,7 @@ function classnames_for_block_core_search( $attributes ) { * @return void */ function apply_block_core_search_border_style( $attributes, $property, $side, &$wrapper_styles, &$button_styles, &$input_styles ) { + //phpcs:enable $is_button_inside = 'button-inside' === _wp_array_get( $attributes, array( 'buttonPosition' ), false ); $path = array( 'style', 'border', $property ); @@ -278,6 +282,7 @@ function apply_block_core_search_border_style( $attributes, $property, $side, &$ * This adds CSS rules for a given border property e.g. width or color. It * injects rules into the provided wrapper, button and input style arrays for * uniform "flat" borders or those with individual sides configured. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes The block attributes. * @param string $property Border property to generate rule for e.g. width or color. @@ -288,6 +293,7 @@ function apply_block_core_search_border_style( $attributes, $property, $side, &$ * @return void */ function apply_block_core_search_border_styles( $attributes, $property, &$wrapper_styles, &$button_styles, &$input_styles ) { + //phpcs:enable apply_block_core_search_border_style( $attributes, $property, null, $wrapper_styles, $button_styles, $input_styles ); apply_block_core_search_border_style( $attributes, $property, 'top', $wrapper_styles, $button_styles, $input_styles ); apply_block_core_search_border_style( $attributes, $property, 'right', $wrapper_styles, $button_styles, $input_styles ); @@ -301,12 +307,14 @@ function apply_block_core_search_border_styles( $attributes, $property, &$wrappe * The result will contain one entry for shared styles such as those for the * inner input or button and a second for the inner wrapper should the block * be positioning the button "inside". + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes The block attributes. * * @return array Style HTML attribute. */ function styles_for_block_core_search( $attributes ) { + //phpcs:enable $wrapper_styles = array(); $button_styles = array(); $input_styles = array(); @@ -428,13 +436,15 @@ function styles_for_block_core_search( $attributes ) { } /** - * Returns typography classnames depending on whether there are named font sizes/families . + * Returns typography classnames depending on whether there are named font sizes/families. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes The block attributes. * * @return string The typography color classnames to be applied to the block elements. */ function get_typography_classes_for_block_core_search( $attributes ) { + //phpcs:enable $typography_classes = array(); $has_named_font_family = ! empty( $attributes['fontFamily'] ); $has_named_font_size = ! empty( $attributes['fontSize'] ); @@ -453,12 +463,14 @@ function get_typography_classes_for_block_core_search( $attributes ) { /** * Returns typography styles to be included in an HTML style tag. * This excludes text-decoration, which is applied only to the label and button elements of the search block. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes The block attributes. * * @return string A string of typography CSS declarations. */ function get_typography_styles_for_block_core_search( $attributes ) { + //phpcs:enable $typography_styles = array(); // Add typography styles. @@ -503,12 +515,14 @@ function get_typography_styles_for_block_core_search( $attributes ) { /** * Returns border color classnames depending on whether there are named or custom border colors. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes The block attributes. * * @return string The border color classnames to be applied to the block elements. */ function get_border_color_classes_for_block_core_search( $attributes ) { + //phpcs:enable $border_color_classes = array(); $has_custom_border_color = ! empty( $attributes['style']['border']['color'] ); $has_named_border_color = ! empty( $attributes['borderColor'] ); @@ -526,12 +540,14 @@ function get_border_color_classes_for_block_core_search( $attributes ) { /** * Returns color classnames depending on whether there are named or custom text and background colors. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes The block attributes. * * @return string The color classnames to be applied to the block elements. */ function get_color_classes_for_block_core_search( $attributes ) { + //phpcs:enable $classnames = array(); // Text color. From 50dfbcc4f5e84cd3ba32efedb7f1a5e6e4e3a924 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 17:07:18 +0200 Subject: [PATCH 24/49] Add exceptions to the ValidBlockLibraryFunctionName rule. --- packages/block-library/src/post-comments-form/index.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/block-library/src/post-comments-form/index.php b/packages/block-library/src/post-comments-form/index.php index 644b02ae0f1498..e7338720c95c55 100644 --- a/packages/block-library/src/post-comments-form/index.php +++ b/packages/block-library/src/post-comments-form/index.php @@ -67,12 +67,14 @@ function register_block_core_post_comments_form() { /** * Use the button block classes for the form-submit button. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $fields The default comment form arguments. * * @return array Returns the modified fields. */ function post_comments_form_block_form_defaults( $fields ) { + //phpcs:enable if ( wp_is_block_theme() ) { $fields['submit_button'] = ''; $fields['submit_field'] = '

%1$s %2$s

'; From 07a9a155b5cd0b6f885a53d5034af071c96736e2 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 17:10:43 +0200 Subject: [PATCH 25/49] Add exceptions to the ValidBlockLibraryFunctionName rule. --- packages/block-library/src/avatar/index.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/packages/block-library/src/avatar/index.php b/packages/block-library/src/avatar/index.php index 1566fe6edfebc3..45af084d5b6c86 100644 --- a/packages/block-library/src/avatar/index.php +++ b/packages/block-library/src/avatar/index.php @@ -87,11 +87,13 @@ function render_block_core_avatar( $attributes, $content, $block ) { /** * Generates class names and styles to apply the border support styles for * the Avatar block. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes The block attributes. * @return array The border-related classnames and styles for the block. */ function get_block_core_avatar_border_attributes( $attributes ) { + //phpcs:enable $border_styles = array(); $sides = array( 'top', 'right', 'bottom', 'left' ); From e276723359915f61877287697fc8c4ccf4e3c197 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 17:13:58 +0200 Subject: [PATCH 26/49] Add exceptions to the ValidBlockLibraryFunctionName rule. --- packages/block-library/src/footnotes/index.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/block-library/src/footnotes/index.php b/packages/block-library/src/footnotes/index.php index 5924db3a190c20..3f8cdf731df0f4 100644 --- a/packages/block-library/src/footnotes/index.php +++ b/packages/block-library/src/footnotes/index.php @@ -85,12 +85,14 @@ function register_block_core_footnotes() { /** * Saves the footnotes meta value to the revision. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @since 6.3.0 * * @param int $revision_id The revision ID. */ function wp_save_footnotes_meta( $revision_id ) { + //phpcs:enable $post_id = wp_is_post_revision( $revision_id ); if ( $post_id ) { @@ -106,6 +108,7 @@ function wp_save_footnotes_meta( $revision_id ) { /** * Keeps track of the revision ID for "rest_after_insert_{$post_type}". + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @since 6.3.0 * @@ -114,6 +117,7 @@ function wp_save_footnotes_meta( $revision_id ) { * @param int $revision_id The revision ID. */ function wp_keep_footnotes_revision_id( $revision_id ) { + //phpcs:enable global $wp_temporary_footnote_revision_id; $wp_temporary_footnote_revision_id = $revision_id; } @@ -129,6 +133,7 @@ function wp_keep_footnotes_revision_id( $revision_id ) { * added to the `post_updated` action, which means the meta is not * available at the time, so we have to add it afterwards through the * `"rest_after_insert_{$post_type}"` action. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @since 6.3.0 * @@ -137,6 +142,7 @@ function wp_keep_footnotes_revision_id( $revision_id ) { * @param WP_Post $post The post object. */ function wp_add_footnotes_revisions_to_post_meta( $post ) { + //phpcs:enable global $wp_temporary_footnote_revision_id; if ( $wp_temporary_footnote_revision_id ) { @@ -165,6 +171,7 @@ function wp_add_footnotes_revisions_to_post_meta( $post ) { /** * Restores the footnotes meta value from the revision. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @since 6.3.0 * @@ -172,6 +179,7 @@ function wp_add_footnotes_revisions_to_post_meta( $post ) { * @param int $revision_id The revision ID. */ function wp_restore_footnotes_from_revision( $post_id, $revision_id ) { + //phpcs:enable $footnotes = get_post_meta( $revision_id, 'footnotes', true ); if ( $footnotes ) { @@ -184,6 +192,7 @@ function wp_restore_footnotes_from_revision( $post_id, $revision_id ) { /** * Adds the footnotes field to the revision. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @since 6.3.0 * @@ -191,6 +200,7 @@ function wp_restore_footnotes_from_revision( $post_id, $revision_id ) { * @return array The revision fields. */ function wp_add_footnotes_to_revision( $fields ) { + //phpcs:enable $fields['footnotes'] = __( 'Footnotes' ); return $fields; } @@ -198,6 +208,7 @@ function wp_add_footnotes_to_revision( $fields ) { /** * Gets the footnotes field from the revision. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @since 6.3.0 * @@ -208,6 +219,7 @@ function wp_add_footnotes_to_revision( $fields ) { * @return string The field value. */ function wp_get_footnotes_from_revision( $revision_field, $field, $revision ) { + //phpcs:enable return get_metadata( 'post', $revision->ID, $field, true ); } add_filter( '_wp_post_revision_field_footnotes', 'wp_get_footnotes_from_revision', 10, 3 ); @@ -216,12 +228,14 @@ function wp_get_footnotes_from_revision( $revision_field, $field, $revision ) { * The REST API autosave endpoint doesn't save meta, so we can use the * `wp_creating_autosave` when it updates an exiting autosave, and * `_wp_put_post_revision` when it creates a new autosave. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @since 6.3.0 * * @param int|array $autosave The autosave ID or array. */ function _wp_rest_api_autosave_meta( $autosave ) { + //phpcs:enable // Ensure it's a REST API request. if ( ! defined( 'REST_REQUEST' ) || ! REST_REQUEST ) { return; @@ -259,6 +273,7 @@ function _wp_rest_api_autosave_meta( $autosave ) { * cause the autosave endpoint to always update the latest revision. That should * be fine, it should be ok to update the revision even if nothing changed. Of * course, this is temporary fix. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @since 6.3.0 * @@ -269,6 +284,7 @@ function _wp_rest_api_autosave_meta( $autosave ) { * See https://github.com/WordPress/wordpress-develop/blob/2103cb9966e57d452c94218bbc3171579b536a40/src/wp-includes/rest-api/endpoints/class-wp-rest-autosaves-controller.php#L219. */ function _wp_rest_api_force_autosave_difference( $prepared_post, $request ) { + //phpcs:enable // We only want to be altering POST requests. if ( $request->get_method() !== 'POST' ) { return $prepared_post; From 4c12e14466ac90e04bd15a649a15fe7c9b549576 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 17:18:39 +0200 Subject: [PATCH 27/49] Add exceptions to the ValidBlockLibraryFunctionName rule. --- packages/block-library/src/post-featured-image/index.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/block-library/src/post-featured-image/index.php b/packages/block-library/src/post-featured-image/index.php index 6cb4110ee000e6..249a02bbcfb076 100644 --- a/packages/block-library/src/post-featured-image/index.php +++ b/packages/block-library/src/post-featured-image/index.php @@ -99,12 +99,14 @@ function render_block_core_post_featured_image( $attributes, $content, $block ) /** * Generate markup for the HTML element that will be used for the overlay. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes Block attributes. * * @return string HTML markup in string format. */ function get_block_core_post_featured_image_overlay_element_markup( $attributes ) { + //phpcs:enable $has_dim_background = isset( $attributes['dimRatio'] ) && $attributes['dimRatio']; $has_gradient = isset( $attributes['gradient'] ) && $attributes['gradient']; $has_custom_gradient = isset( $attributes['customGradient'] ) && $attributes['customGradient']; @@ -165,11 +167,13 @@ function get_block_core_post_featured_image_overlay_element_markup( $attributes /** * Generates class names and styles to apply the border support styles for * the Post Featured Image block. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param array $attributes The block attributes. * @return array The border-related classnames and styles for the block. */ function get_block_core_post_featured_image_border_attributes( $attributes ) { + //phpcs:enable $border_styles = array(); $sides = array( 'top', 'right', 'bottom', 'left' ); From aed8f1bff2b2cb7adda82af0213d63f7179fb2b2 Mon Sep 17 00:00:00 2001 From: Anton Vlasenko Date: Wed, 9 Aug 2023 17:22:53 +0200 Subject: [PATCH 28/49] Add exceptions to the ValidBlockLibraryFunctionName rule. --- packages/block-library/src/categories/index.php | 2 ++ packages/block-library/src/latest-comments/index.php | 2 ++ 2 files changed, 4 insertions(+) diff --git a/packages/block-library/src/categories/index.php b/packages/block-library/src/categories/index.php index 7e3979b7aefe2e..b4d55fce70ee33 100644 --- a/packages/block-library/src/categories/index.php +++ b/packages/block-library/src/categories/index.php @@ -62,12 +62,14 @@ function render_block_core_categories( $attributes ) { /** * Generates the inline script for a categories dropdown field. + * //phpcs:disable Gutenberg.NamingConventions.ValidBlockLibraryFunctionName * * @param string $dropdown_id ID of the dropdown field. * * @return string Returns the dropdown onChange redirection script. */ function build_dropdown_script_block_core_categories( $dropdown_id ) { + //phpcs:enable ob_start(); ?>