code
stringlengths
17
296k
docstring
stringlengths
30
30.3k
func_name
stringlengths
1
89
language
stringclasses
1 value
repo
stringlengths
7
63
path
stringlengths
7
153
url
stringlengths
51
209
license
stringclasses
4 values
public function register() { /* * Set the $ignore_tokens property. * * Existing heredoc, nowdoc and inline HTML indentation should be respected at all times. */ $this->ignore_tokens = Tokens::$heredocTokens; unset( $this->ignore_tokens[ \T_START_HEREDOC ], $this->ignore_tokens[ \T_START_NOWDOC ] ); $this->ignore_tokens[ \T_INLINE_HTML ] = \T_INLINE_HTML; return Collections::arrayOpenTokensBC(); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
MIT
protected function ignore_token( $ptr ) { $token_code = $this->tokens[ $ptr ]['code']; if ( isset( $this->ignore_tokens[ $token_code ] ) ) { return true; } /* * If it's a subsequent line of a multi-line sting, it will not start with a quote * character, nor just *be* a quote character. */ if ( isset( Tokens::$stringTokens[ $token_code ] ) === true ) { // Deal with closing quote of a multi-line string being on its own line. if ( "'" === $this->tokens[ $ptr ]['content'] || '"' === $this->tokens[ $ptr ]['content'] ) { return true; } // Deal with subsequent lines of a multi-line string where the token is broken up per line. if ( "'" !== $this->tokens[ $ptr ]['content'][0] && '"' !== $this->tokens[ $ptr ]['content'][0] ) { return true; } } return false; }
Should the token be ignored ? This method is only intended to be used with the first token on a line for subsequent lines in an multi-line array item. @param int $ptr Stack pointer to the first token on a line. @return bool
ignore_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
MIT
protected function get_indentation_size( $ptr ) { // Find the first token on the line. for ( ; $ptr >= 0; $ptr-- ) { if ( 1 === $this->tokens[ $ptr ]['column'] ) { break; } } $whitespace = ''; if ( \T_WHITESPACE === $this->tokens[ $ptr ]['code'] || \T_DOC_COMMENT_WHITESPACE === $this->tokens[ $ptr ]['code'] ) { return $this->tokens[ $ptr ]['length']; } /* * Special case for multi-line, non-docblock comments. * Only applicable for subsequent lines in an array item. * * First/Single line is tokenized as T_WHITESPACE + T_COMMENT * Subsequent lines are tokenized as T_COMMENT including the indentation whitespace. */ if ( \T_COMMENT === $this->tokens[ $ptr ]['code'] ) { $content = $this->tokens[ $ptr ]['content']; $actual_comment = ltrim( $content ); $whitespace = str_replace( $actual_comment, '', $content ); } return \strlen( $whitespace ); }
Determine the line indentation whitespace. @param int $ptr Stack pointer to an arbitrary token on a line. @return int Nr of spaces found. Where necessary, tabs are translated to spaces.
get_indentation_size
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
MIT
protected function add_array_alignment_error( $ptr, $error, $error_code, $expected, $found, $new_indent ) { $fix = $this->phpcsFile->addFixableError( $error, $ptr, $error_code, array( $expected, $found ) ); if ( true === $fix ) { $this->fix_alignment_error( $ptr, $new_indent ); } }
Throw an error and fix incorrect array alignment. @param int $ptr Stack pointer to the first content on the line. @param string $error Error message. @param string $error_code Error code. @param int $expected Expected nr of spaces (tabs translated to space value). @param int $found Found nr of spaces (tabs translated to space value). @param string $new_indent Whitespace indent replacement content. @return void
add_array_alignment_error
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
MIT
protected function fix_alignment_error( $ptr, $new_indent ) { if ( 1 === $this->tokens[ $ptr ]['column'] ) { $this->phpcsFile->fixer->addContentBefore( $ptr, $new_indent ); } else { $this->phpcsFile->fixer->replaceToken( ( $ptr - 1 ), $new_indent ); } }
Fix incorrect array alignment. @param int $ptr Stack pointer to the first content on the line. @param string $new_indent Whitespace indent replacement content. @return void
fix_alignment_error
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/ArrayIndentationSniff.php
MIT
public function register() { return Collections::arrayOpenTokensBC(); }
Returns an array of tokens this test wants to listen for. @since 0.14.0 @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
MIT
public function process_token( $stackPtr ) { if ( isset( Collections::shortArrayListOpenTokensBC()[ $this->tokens[ $stackPtr ]['code'] ] ) && Arrays::isShortArray( $this->phpcsFile, $stackPtr ) === false ) { // Short list, not short array. return; } /* * Determine the array opener & closer. */ $array_open_close = Arrays::getOpenClose( $this->phpcsFile, $stackPtr ); if ( false === $array_open_close ) { // Array open/close could not be determined. return; } $opener = $array_open_close['opener']; $closer = $array_open_close['closer']; $array_items = PassedParameters::getParameters( $this->phpcsFile, $stackPtr ); if ( empty( $array_items ) ) { return; } // Pass off to either the single line or multi-line array analysis. if ( $this->tokens[ $opener ]['line'] === $this->tokens[ $closer ]['line'] ) { return $this->process_single_line_array( $stackPtr, $array_items, $opener, $closer ); } else { return $this->process_multi_line_array( $stackPtr, $array_items, $opener, $closer ); } }
Processes this test, when one of its tokens is encountered. @since 0.14.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.
process_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
MIT
protected function process_single_line_array( $stackPtr, $items, $opener, $closer ) { /* * For single line arrays, we don't care about what level the arrow is from. * Just find and fix them all. */ $next_arrow = $this->phpcsFile->findNext( \T_DOUBLE_ARROW, ( $opener + 1 ), $closer ); while ( false !== $next_arrow ) { if ( \T_WHITESPACE === $this->tokens[ ( $next_arrow - 1 ) ]['code'] ) { $space_length = $this->tokens[ ( $next_arrow - 1 ) ]['length']; if ( 1 !== $space_length ) { $error = 'Expected 1 space between "%s" and double arrow; %s found'; $data = array( $this->tokens[ ( $next_arrow - 2 ) ]['content'], $space_length, ); $fix = $this->phpcsFile->addFixableWarning( $error, $next_arrow, 'SpaceBeforeDoubleArrow', $data ); if ( true === $fix ) { $this->phpcsFile->fixer->replaceToken( ( $next_arrow - 1 ), ' ' ); } } } // Find the position of the next double arrow. $next_arrow = $this->phpcsFile->findNext( \T_DOUBLE_ARROW, ( $next_arrow + 1 ), $closer ); } // Ignore any child-arrays as the double arrows in these will already have been handled. return ( $closer + 1 ); }
Process a single-line array. While the WP standard does not allow single line multi-item associative arrays, this sniff should function independently of that. The `WordPress.WhiteSpace.OperatorSpacing` sniff already covers checking that there is a space between the array key and the double arrow, but doesn't enforce it to be exactly one space for single line arrays. That is what this method covers. @since 0.14.0 @param int $stackPtr The position of the current token in the stack. @param array $items Info array containing information on each array item. @param int $opener The position of the array opener. @param int $closer The position of the array closer. @return int|void Integer stack pointer to skip forward or void to continue normal file processing.
process_single_line_array
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
MIT
protected function validate_align_multiline_items() { $alignMultilineItems = $this->alignMultilineItems; if ( 'always' === $alignMultilineItems || 'never' === $alignMultilineItems ) { return; } else { // Correct for a potentially added % sign. $alignMultilineItems = rtrim( $alignMultilineItems, '%' ); if ( preg_match( '`^([=<>!]{1,2})(100|[0-9]{1,2})$`', $alignMultilineItems, $matches ) > 0 ) { $operator = $matches[1]; $number = (int) $matches[2]; if ( \in_array( $operator, array( '<', '<=', '>', '>=', '==', '=', '!=', '<>' ), true ) === true && ( $number >= 0 && $number <= 100 ) ) { $this->alignMultilineItems = $alignMultilineItems; $this->number = (string) $number; $this->operator = $operator; return; } } } $this->phpcsFile->addError( 'Invalid property value passed: "%s". The value for the "alignMultilineItems" property for the "WordPress.Arrays.MultipleStatementAlignment" sniff should be either "always", "never" or an comparison operator + a number between 0 and 100.', 0, 'InvalidPropertyPassed', array( $this->alignMultilineItems ) ); // Reset to the default if an invalid value was received. $this->alignMultilineItems = 'always'; }
Validate that a valid value has been received for the alignMultilineItems property. This message may be thrown more than once if the property is being changed inline in a file. @since 0.14.0 @return void
validate_align_multiline_items
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/MultipleStatementAlignmentSniff.php
MIT
public function register() { return array( \T_OPEN_SQUARE_BRACKET, ); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/ArrayKeySpacingRestrictionsSniff.php
MIT
public function register() { return Collections::arrayOpenTokensBC(); }
Returns an array of tokens this test wants to listen for. @since 0.12.0 @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/ArrayDeclarationSpacingSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/ArrayDeclarationSpacingSniff.php
MIT
public function process_token( $stackPtr ) { if ( isset( Collections::shortArrayListOpenTokensBC()[ $this->tokens[ $stackPtr ]['code'] ] ) && Arrays::isShortArray( $this->phpcsFile, $stackPtr ) === false ) { // Short list, not short array. return; } /* * Determine the array opener & closer. */ $array_open_close = Arrays::getOpenClose( $this->phpcsFile, $stackPtr ); if ( false === $array_open_close ) { // Array open/close could not be determined. return; } $opener = $array_open_close['opener']; $closer = $array_open_close['closer']; unset( $array_open_close ); // Pass off to either the single line or multi-line array analysis. if ( $this->tokens[ $opener ]['line'] === $this->tokens[ $closer ]['line'] ) { $this->process_single_line_array( $stackPtr, $opener, $closer ); } else { $this->process_multi_line_array( $stackPtr, $opener ); } }
Processes this test, when one of its tokens is encountered. @since 0.12.0 The actual checks contained in this method used to be in the `processSingleLineArray()` method. @param int $stackPtr The position of the current token in the stack. @return void
process_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/ArrayDeclarationSpacingSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/ArrayDeclarationSpacingSniff.php
MIT
protected function process_single_line_array( $stackPtr, $opener, $closer ) { $array_items = PassedParameters::getParameters( $this->phpcsFile, $stackPtr ); if ( ( false === $this->allow_single_item_single_line_associative_arrays && empty( $array_items ) ) || ( true === $this->allow_single_item_single_line_associative_arrays && \count( $array_items ) === 1 ) ) { return; } /* * Make sure the double arrow is for *this* array, not for a nested one. */ $array_has_keys = false; foreach ( $array_items as $item ) { if ( Arrays::getDoubleArrowPtr( $this->phpcsFile, $item['start'], $item['end'] ) !== false ) { $array_has_keys = true; break; } } if ( false === $array_has_keys ) { return; } $error = 'When an array uses associative keys, each value should start on %s.'; if ( true === $this->allow_single_item_single_line_associative_arrays ) { $error = 'When a multi-item array uses associative keys, each value should start on %s.'; } /* * Just add a new line before the array closer. * The multi-line array fixer will then fix the individual array items in the next fixer loop. */ SpacesFixer::checkAndFix( $this->phpcsFile, $closer, $this->phpcsFile->findPrevious( \T_WHITESPACE, ( $closer - 1 ), null, true ), 'newline', $error, 'AssociativeArrayFound', 'error' ); }
Check that associative arrays are always multi-line. @since 0.13.0 The actual checks contained in this method used to be in the `process()` method. @param int $stackPtr The position of the current token in the stack. @param int $opener The position of the array opener. @param int $closer The position of the array closer. @return void
process_single_line_array
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Arrays/ArrayDeclarationSpacingSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Arrays/ArrayDeclarationSpacingSniff.php
MIT
public function register() { $this->assignment_tokens = Tokens::$assignmentTokens; unset( $this->assignment_tokens[ \T_DOUBLE_ARROW ] ); $starters = Tokens::$booleanOperators; $starters[ \T_SEMICOLON ] = \T_SEMICOLON; $starters[ \T_OPEN_PARENTHESIS ] = \T_OPEN_PARENTHESIS; $starters[ \T_INLINE_ELSE ] = \T_INLINE_ELSE; $this->condition_start_tokens = $starters; return array( \T_INLINE_THEN, ); }
Registers the tokens that this sniff wants to listen for. @since 0.14.0 @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/CodeAnalysis/AssignmentInTernaryConditionSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/CodeAnalysis/AssignmentInTernaryConditionSniff.php
MIT
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { if ( \count( $parameters ) === 1 ) { return; } /* * We already know that there will be a valid open+close parenthesis, otherwise the sniff * would have bowed out long before. */ $opener = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); $closer = $this->tokens[ $opener ]['parenthesis_closer']; $data = array( $matched_content, $this->target_functions[ $matched_content ], GetTokensAsString::compact( $this->phpcsFile, $stackPtr, $closer, true ), ); $this->phpcsFile->addWarning( '%s() expects only a $text parameter. Did you mean to use %s() ? Found: %s', $stackPtr, 'Found', $data ); }
Process the parameters of a matched function. @since 2.2.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 in lowercase. @param array $parameters Array with information about the parameters. @return void
process_parameters
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/CodeAnalysis/EscapedNotTranslatedSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/CodeAnalysis/EscapedNotTranslatedSniff.php
MIT
public function register() { $targets = Collections::textStringStartTokens(); $targets[] = \T_INLINE_HTML; return $targets; }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/EnqueuedResourcesSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php
MIT
private function find_token_in_multiline_string( $stackPtr, $content, $match_offset ) { $newline_count = 0; if ( $match_offset > 0 ) { $newline_count = substr_count( $content, "\n", 0, $match_offset ); } // Account for heredoc/nowdoc text starting at the token *after* the opener. if ( isset( Tokens::$heredocTokens[ $this->tokens[ $stackPtr ]['code'] ] ) === true ) { ++$newline_count; } return ( $stackPtr + $newline_count ); }
Find the exact token on which the error should be reported for multi-line strings. @param int $stackPtr The position of the current token in the stack. @param string $content The complete, potentially multi-line, text string. @param int $match_offset The offset within the content at which the match was found. @return int The stack pointer to the token containing the start of the match.
find_token_in_multiline_string
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/EnqueuedResourcesSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/EnqueuedResourcesSniff.php
MIT
public function register() { $this->false_tokens += Tokens::$emptyTokens; $this->safe_tokens += Tokens::$emptyTokens; $this->safe_tokens += Tokens::$assignmentTokens; $this->safe_tokens += Tokens::$comparisonTokens; $this->safe_tokens += Tokens::$operators; $this->safe_tokens += Tokens::$booleanOperators; $this->safe_tokens += Tokens::$castTokens; return parent::register(); }
Returns an array of tokens this test wants to listen for. Overloads and calls the parent method to allow for adding additional tokens to the $safe_tokens property. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/EnqueuedResourceParametersSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/EnqueuedResourceParametersSniff.php
MIT
protected function is_falsy( $start, $end ) { // Find anything excluding the false tokens. $has_non_false = $this->phpcsFile->findNext( $this->false_tokens, $start, ( $end + 1 ), true ); // If no non-false tokens are found, we are good. if ( false === $has_non_false ) { return true; } $code_string = ''; for ( $i = $start; $i <= $end; $i++ ) { if ( isset( $this->safe_tokens[ $this->tokens[ $i ]['code'] ] ) === false ) { // Function call/variable or other token which makes it neigh impossible // to determine whether the actual value would evaluate to false. return false; } if ( isset( Tokens::$emptyTokens[ $this->tokens[ $i ]['code'] ] ) === true ) { continue; } // Make sure that PHP 7.4 numeric literals and PHP 8.1 explicit octals don't cause problems. if ( \T_LNUMBER === $this->tokens[ $i ]['code'] || \T_DNUMBER === $this->tokens[ $i ]['code'] ) { $number_info = Numbers::getCompleteNumber( $this->phpcsFile, $i ); $code_string .= $number_info['decimal']; $i = $number_info['last_token']; continue; } $code_string .= $this->tokens[ $i ]['content']; } if ( '' === $code_string ) { return false; } // Evaluate the argument to figure out the outcome is false or not. // phpcs:ignore Squiz.PHP.Eval -- No harm here. return ( false === eval( "return (bool) $code_string;" ) ); }
Determine if a range has a falsy value. @param int $start The position to start looking from. @param int $end The position to stop looking (inclusive). @return bool True if the parameter is falsy. False if the parameter is not falsy or when it couldn't be reliably determined.
is_falsy
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/EnqueuedResourceParametersSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/EnqueuedResourceParametersSniff.php
MIT
public function getGroups() { return array( 'posts_per_page' => array( 'type' => 'warning', 'message' => 'Detected high pagination limit, `%s` is set to `%s`', 'keys' => array( 'posts_per_page', 'numberposts', ), ), ); }
Groups of variables to restrict. @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/PostsPerPageSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/PostsPerPageSniff.php
MIT
public function callback( $key, $val, $line, $group ) { $stripped_val = TextStrings::stripQuotes( $val ); if ( '' === $stripped_val ) { return false; } if ( $val !== $stripped_val ) { // The value was a text string. For text strings, we only accept purely numeric values. if ( preg_match( '`^[0-9]+$`', $stripped_val ) !== 1 ) { // Not a purely numeric value, so any comparison would be a false comparison. return false; } // Purely numeric string, treat it as an integer from here on out. $val = $stripped_val; } $first_char = $val[0]; if ( '-' === $first_char || '+' === $first_char ) { $val = ltrim( $val, '-+' ); } else { $first_char = ''; } $real_value = Numbers::getDecimalValue( $val ); if ( false === $real_value ) { // This wasn't a purely numeric value, so any comparison would be a false comparison. return false; } $val = $first_char . $real_value; return ( (int) $val > (int) $this->posts_per_page ); }
Callback to process each confirmed key, to check value. @param string $key Array index / key. @param mixed $val Assigned value. @param int $line Token line. @param array $group Group definition. @return bool FALSE if no match, TRUE if matches.
callback
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/PostsPerPageSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/PostsPerPageSniff.php
MIT
public function getGroups() { // Make sure all array keys are lowercase. $this->deprecated_classes = array_change_key_case( $this->deprecated_classes, \CASE_LOWER ); return array( 'deprecated_classes' => array( 'classes' => array_keys( $this->deprecated_classes ), ), ); }
Groups of classes to restrict. @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/DeprecatedClassesSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DeprecatedClassesSniff.php
MIT
public function process_matched_token( $stackPtr, $group_name, $matched_content ) { $this->set_minimum_wp_version(); $class_name = ltrim( strtolower( $matched_content ), '\\' ); $message = 'The %s class has been deprecated since WordPress version %s.'; $data = array( ltrim( $matched_content, '\\' ), $this->deprecated_classes[ $class_name ]['version'], ); if ( ! empty( $this->deprecated_classes[ $class_name ]['alt'] ) ) { $message .= ' Use %s instead.'; $data[] = $this->deprecated_classes[ $class_name ]['alt']; } MessageHelper::addMessage( $this->phpcsFile, $message, $stackPtr, ( $this->wp_version_compare( $this->deprecated_classes[ $class_name ]['version'], $this->minimum_wp_version, '<' ) ), MessageHelper::stringToErrorcode( $class_name . 'Found' ), $data ); }
Process a matched token. @param int $stackPtr The position of the current token in the stack. @param string $group_name The name of the group which was matched. Will always be 'deprecated_classes'. @param string $matched_content The token content (class name) which was matched in its original case. @return void
process_matched_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/DeprecatedClassesSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DeprecatedClassesSniff.php
MIT
public function getGroups() { return array( 'curl' => array( 'type' => 'warning', 'message' => 'Using cURL functions is highly discouraged. Use wp_remote_get() instead.', 'since' => '2.7.0', 'functions' => array( 'curl_*', ), 'allow' => array( 'curl_version' => true, ), ), 'parse_url' => array( 'type' => 'warning', 'message' => '%s() is discouraged because of inconsistency in the output across PHP versions; use wp_parse_url() instead.', 'since' => '4.4.0', 'functions' => array( 'parse_url', ), ), 'json_encode' => array( 'type' => 'warning', 'message' => '%s() is discouraged. Use wp_json_encode() instead.', 'since' => '4.1.0', 'functions' => array( 'json_encode', ), ), 'file_get_contents' => array( 'type' => 'warning', 'message' => '%s() is discouraged. Use wp_remote_get() for remote URLs instead.', 'since' => '2.7.0', 'functions' => array( 'file_get_contents', ), ), 'unlink' => array( 'type' => 'warning', 'message' => '%s() is discouraged. Use wp_delete_file() to delete a file.', 'since' => '4.2.0', 'functions' => array( 'unlink', ), ), 'rename' => array( 'type' => 'warning', 'message' => '%s() is discouraged. Use WP_Filesystem::move() to rename a file.', 'since' => '2.5.0', 'functions' => array( 'rename', ), ), 'file_system_operations' => array( 'type' => 'warning', 'message' => 'File operations should use WP_Filesystem methods instead of direct PHP filesystem calls. Found: %s().', 'since' => '2.5.0', 'functions' => array( 'chgrp', 'chmod', 'chown', 'fclose', 'file_put_contents', 'fopen', 'fputs', 'fread', 'fsockopen', 'fwrite', 'is_writable', 'is_writeable', 'mkdir', 'pfsockopen', 'readfile', 'rmdir', 'touch', ), ), 'strip_tags' => array( 'type' => 'warning', 'message' => '%s() is discouraged. Use the more comprehensive wp_strip_all_tags() instead.', 'since' => '2.9.0', 'functions' => array( 'strip_tags', ), ), 'rand_seeding' => array( 'type' => 'warning', 'message' => '%s() is discouraged. Rand seeding is not necessary when using the wp_rand() function (as you should).', 'since' => '2.6.2', 'functions' => array( 'mt_srand', 'srand', ), ), 'rand' => array( 'type' => 'warning', 'message' => '%s() is discouraged. Use the far less predictable wp_rand() instead.', 'since' => '2.6.2', 'functions' => array( 'mt_rand', 'rand', ), ), ); }
Groups of functions to restrict. Example: groups => array( 'lambda' => array( 'type' => 'error' | 'warning', 'message' => 'Use anonymous functions instead please!', 'since' => '4.9.0', //=> the WP version in which the alternative became available. 'functions' => array( 'file_get_contents', 'create_function' ), ) ) @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/AlternativeFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/AlternativeFunctionsSniff.php
MIT
public function process_matched_token( $stackPtr, $group_name, $matched_content ) { $this->set_minimum_wp_version(); /* * Deal with exceptions. */ switch ( $matched_content ) { case 'strip_tags': /* * The function `wp_strip_all_tags()` is only a valid alternative when * only the first parameter, `$string`, is passed to `strip_tags()`. */ $has_allowed_tags = PassedParameters::getParameter( $this->phpcsFile, $stackPtr, 2, 'allowed_tags' ); if ( false !== $has_allowed_tags ) { return; } unset( $has_allowed_tags ); break; case 'parse_url': /* * Before WP 4.7.0, the function `wp_parse_url()` was only a valid alternative * if the second param - `$component` - was not passed to `parse_url()`. * * @see https://developer.wordpress.org/reference/functions/wp_parse_url/#changelog */ $has_component = PassedParameters::getParameter( $this->phpcsFile, $stackPtr, 2, 'component' ); if ( false !== $has_component && $this->wp_version_compare( $this->minimum_wp_version, '4.7.0', '<' ) ) { return; } unset( $has_component ); break; case 'file_get_contents': /* * Using `wp_remote_get()` will only work for remote URLs. * See if we can determine is this function call is for a local file and if so, bow out. */ $params = PassedParameters::getParameters( $this->phpcsFile, $stackPtr ); $use_include_path_param = PassedParameters::getParameterFromStack( $params, 2, 'use_include_path' ); if ( false !== $use_include_path_param && 'true' === $use_include_path_param['clean'] ) { // Setting `$use_include_path` to `true` is only relevant for local files. return; } $filename_param = PassedParameters::getParameterFromStack( $params, 1, 'filename' ); if ( false === $filename_param ) { // If the file to get is not set, this is a non-issue anyway. return; } if ( strpos( $filename_param['clean'], 'http:' ) !== false || strpos( $filename_param['clean'], 'https:' ) !== false ) { // Definitely a URL, throw notice. break; } $contains_wp_path_constant = preg_match( '`\b(?:ABSPATH|WP_(?:CONTENT|PLUGIN)_DIR|WPMU_PLUGIN_DIR|TEMPLATEPATH|STYLESHEETPATH|(?:MU)?PLUGINDIR)\b`', $filename_param['clean'] ); if ( 1 === $contains_wp_path_constant ) { // Using any of the constants matched in this regex is an indicator of a local file. return; } $contains_wp_path_function_call = preg_match( '`(?:get_home_path|plugin_dir_path|get_(?:stylesheet|template)_directory|wp_upload_dir)\s*\(`i', $filename_param['clean'] ); if ( 1 === $contains_wp_path_function_call ) { // Using any of the functions matched in the regex is an indicator of a local file. return; } if ( $this->is_local_data_stream( $filename_param['clean'] ) === true ) { // Local data stream. return; } unset( $params, $use_include_path_param, $filename_param, $contains_wp_path_constant, $contains_wp_path_function_call ); break; case 'file_put_contents': case 'fopen': case 'readfile': /* * Allow for handling raw data streams from the request body. * * Note: at this time (December 2022) these three functions use the same parameter name for their * first parameter. If this would change at any point in the future, this code will need to * be made more modular and will need to pass the parameter name based on the function call detected. */ $filename_param = PassedParameters::getParameter( $this->phpcsFile, $stackPtr, 1, 'filename' ); if ( false === $filename_param ) { // If the file to work with is not set, local data streams don't come into play. break; } if ( $this->is_local_data_stream( $filename_param['clean'] ) === true ) { // Local data stream. return; } unset( $filename_param ); break; } if ( ! isset( $this->groups[ $group_name ]['since'] ) ) { return parent::process_matched_token( $stackPtr, $group_name, $matched_content ); } // Verify if the alternative is available in the minimum supported WP version. if ( $this->wp_version_compare( $this->groups[ $group_name ]['since'], $this->minimum_wp_version, '<=' ) ) { return parent::process_matched_token( $stackPtr, $group_name, $matched_content ); } }
Process a matched token. @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 in lowercase. @return int|void Integer stack pointer to skip forward or void to continue normal file processing.
process_matched_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/AlternativeFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/AlternativeFunctionsSniff.php
MIT
protected function is_local_data_stream( $clean_param_value ) { $stripped = TextStrings::stripQuotes( $clean_param_value ); if ( isset( $this->allowed_local_streams[ $stripped ] ) || isset( $this->allowed_local_stream_constants[ $clean_param_value ] ) ) { return true; } foreach ( $this->allowed_local_stream_partials as $partial ) { if ( strpos( $stripped, $partial ) === 0 ) { return true; } } return false; }
Determine based on the "clean" parameter value, whether a file parameter points to a local data stream. @param string $clean_param_value Parameter value without comments. @return bool True if this is a local data stream. False otherwise.
is_local_data_stream
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/AlternativeFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/AlternativeFunctionsSniff.php
MIT
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { $condition = $this->target_functions[ $matched_content ]['condition']; $recommended = $this->target_functions[ $matched_content ]['recommended']; $meta_key = PassedParameters::getParameterFromStack( $parameters, $condition['position'], $condition['param_name'] ); if ( ! is_array( $meta_key ) ) { return; } $single = PassedParameters::getParameterFromStack( $parameters, $recommended['position'], $recommended['param_name'] ); if ( is_array( $single ) ) { $this->phpcsFile->recordMetric( $stackPtr, self::METRIC_NAME, 'yes' ); return; } $this->phpcsFile->recordMetric( $stackPtr, self::METRIC_NAME, 'no' ); $tokens = $this->phpcsFile->getTokens(); $message_data = array( $condition['param_name'], $tokens[ $stackPtr ]['content'], $recommended['param_name'], ); $this->phpcsFile->addWarning( 'When passing the $%s parameter to %s(), it is recommended to also pass the $%s parameter to explicitly indicate whether a single value or multiple values are expected to be returned.', $stackPtr, 'Missing', $message_data ); }
Process the parameters of a matched function. @since 3.2.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 in lowercase. @param array $parameters Array with information about the parameters. @return void
process_parameters
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/GetMetaSingleSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/GetMetaSingleSniff.php
MIT
public function register() { // Union the arrays - keeps the array keys. $this->text_and_comment_tokens = ( Tokens::$textStringTokens + $this->comment_text_tokens ); $targets = $this->text_and_comment_tokens; $targets += Tokens::$ooScopeTokens; $targets[ \T_NAMESPACE ] = \T_NAMESPACE; // Also sniff for array tokens to make skipping anything within those more efficient. $targets += Collections::arrayOpenTokensBC(); $targets += Collections::listTokens(); $targets[ \T_OPEN_SQUARE_BRACKET ] = \T_OPEN_SQUARE_BRACKET; return $targets; }
Returns an array of tokens this test wants to listen for. @since 0.12.0 @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/CapitalPDangitSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/CapitalPDangitSniff.php
MIT
protected function retrieve_misspellings( $match_stack ) { $misspelled = array(); foreach ( $match_stack as $match ) { // Deal with multi-dimensional arrays when capturing offset. if ( \is_array( $match ) ) { $match = $match[0]; } if ( 'WordPress' !== $match ) { $misspelled[] = $match; } } return $misspelled; }
Retrieve a list of misspellings based on an array of matched variations on the target word. @param array $match_stack Array of matched variations of the target word. @return array Array containing only the misspelled variants.
retrieve_misspellings
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/CapitalPDangitSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/CapitalPDangitSniff.php
MIT
public function process_matched_token( $stackPtr, $group_name, $matched_content ) { $matched_unqualified = ltrim( $matched_content, '\\' ); $matched_lowercase = strtolower( $matched_unqualified ); $matched_proper_case = $this->get_proper_case( $matched_lowercase ); if ( $matched_unqualified === $matched_proper_case ) { // Already using proper case, nothing to do. return; } $warning = 'It is strongly recommended to refer to classes by their properly cased name. Expected: %s Found: %s'; $data = array( $matched_proper_case, $matched_unqualified, ); $this->phpcsFile->addWarning( $warning, $stackPtr, 'Incorrect', $data ); }
Process a matched token. @since 3.0.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. Will always be 'wp_classes'. @param string $matched_content The token content (class name) which was matched. in its original case. @return void
process_matched_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/ClassNameCaseSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/ClassNameCaseSniff.php
MIT
private function get_proper_case( $matched_lc ) { foreach ( $this->class_groups as $name ) { $current = $this->$name; // Needed to prevent issues with PHP < 7.0. if ( isset( $current[ $matched_lc ] ) ) { return $current[ $matched_lc ]; } } // Shouldn't be possible. return ''; // @codeCoverageIgnore }
Match a lowercase class name to its proper cased name. @since 3.0.0 @param string $matched_lc Lowercase class name. @return string
get_proper_case
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/ClassNameCaseSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/ClassNameCaseSniff.php
MIT
public function getGroups() { return array( 'i18n' => array( 'functions' => array_keys( $this->i18n_functions ), ), 'typos' => array( 'functions' => array( '_', ), ), ); }
Groups of functions to restrict. Example: groups => array( 'lambda' => array( 'type' => 'error' | 'warning', 'message' => 'Use anonymous functions instead please!', 'functions' => array( 'file_get_contents', 'create_function' ), ) ) @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
public function process_token( $stackPtr ) { // Reset defaults. $this->text_domain_contains_default = false; $this->text_domain_is_default = false; // Allow overruling the text_domain set in a ruleset via the command line. $cl_text_domain = Helper::getConfigData( 'text_domain' ); if ( ! empty( $cl_text_domain ) ) { $cl_text_domain = trim( $cl_text_domain ); if ( '' !== $cl_text_domain ) { $this->text_domain = array_filter( array_map( 'trim', explode( ',', $cl_text_domain ) ) ); } } $this->text_domain = RulesetPropertyHelper::merge_custom_array( $this->text_domain, array(), false ); if ( ! empty( $this->text_domain ) ) { if ( \in_array( 'default', $this->text_domain, true ) ) { $this->text_domain_contains_default = true; if ( \count( $this->text_domain ) === 1 ) { $this->text_domain_is_default = true; } } } // Prevent exclusion of the i18n group. $this->exclude = array(); parent::process_token( $stackPtr ); }
Processes this test, when one of its tokens is encountered. @since 1.0.0 Defers to the abstractFunctionRestriction sniff for determining whether something is a function call. The logic after that has been split off to the `process_matched_token()` method. @param int $stackPtr The position of the current token in the stack. @return void
process_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
public function process_matched_token( $stackPtr, $group_name, $matched_content ) { $func_open_paren_token = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); if ( ! isset( $this->tokens[ $func_open_paren_token ]['parenthesis_closer'] ) ) { // Live coding, parse error or not a function call. return; } if ( 'typos' === $group_name && '_' === $matched_content ) { $this->phpcsFile->addError( 'Found single-underscore "_()" function when double-underscore expected.', $stackPtr, 'SingleUnderscoreGetTextFunction' ); return; } if ( 'translate' === $matched_content || 'translate_with_gettext_context' === $matched_content ) { $this->phpcsFile->addWarning( 'Use of the "%s()" function is reserved for low-level API usage.', $stackPtr, 'LowLevelTranslationFunction', array( $matched_content ) ); } parent::process_matched_token( $stackPtr, $group_name, $matched_content ); }
Process a matched token. @since 1.0.0 Logic split off from the `process_token()` method. @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 in lowercase. @return void
process_matched_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
private function check_argument_count( $stackPtr, $matched_content, $parameters, $expected_count ) { $actual_count = count( $parameters ); if ( $actual_count > $expected_count ) { $this->phpcsFile->addError( 'Too many parameters passed to function "%s()". Expected: %s parameters, received: %s', $stackPtr, 'TooManyFunctionArgs', array( $matched_content, $expected_count, $actual_count ) ); } }
Verify that there are no superfluous function arguments. @since 3.0.0 Check moved from the `process_matched_token()` method to this method. @param int $stackPtr The position of the current token in the stack. @param string $matched_content The token content (function name) which was matched in lowercase. @param array $parameters The parameters array. @param int $expected_count The expected number of passed arguments. @return void
check_argument_count
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
private function check_textdomain_matches( $matched_content, $param_name, $param_info ) { $stripped_content = TextStrings::stripQuotes( $param_info['clean'] ); if ( empty( $this->text_domain ) && '' === $stripped_content ) { $first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true ); $this->phpcsFile->addError( 'The passed $domain should never be an empty string. Either pass a text domain or remove the parameter.', $first_non_empty, 'EmptyTextDomain' ); } if ( empty( $this->text_domain ) ) { // Nothing more to do, the other checks all depend on a text domain being known. return; } if ( ! \in_array( $stripped_content, $this->text_domain, true ) ) { $first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true ); $this->phpcsFile->addError( 'Mismatched text domain. Expected \'%s\' but got %s.', $first_non_empty, 'TextDomainMismatch', array( implode( "' or '", $this->text_domain ), $param_info['clean'] ) ); return; } if ( true === $this->text_domain_is_default && 'default' === $stripped_content ) { $fixable = false; $error = 'No need to supply the text domain in function call to %s() when the only accepted text domain is "default".'; $error_code = 'SuperfluousDefaultTextDomain'; $data = array( $matched_content ); $first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true ); // Prevent removing comments when auto-fixing. $remove_from = ( $param_info['start'] - 1 ); $remove_to = $first_non_empty; if ( isset( $param_info['name_token'] ) ) { $remove_from = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $param_info['name_token'] - 1 ), null, true ); if ( \T_OPEN_PARENTHESIS === $this->tokens[ $remove_from ]['code'] ) { ++$remove_from; // Don't remove the open parenthesis. /* * Named param as first param in the function call, if we fix this, we need to * remove the comma _after_ the parameter as well to prevent creating a parse error. */ $remove_to = $param_info['end']; if ( \T_COMMA === $this->tokens[ ( $param_info['end'] + 1 ) ]['code'] ) { ++$remove_to; // Include the comma. } } } // Now, make sure there are no comments in the tokens we want to remove. if ( $this->phpcsFile->findNext( Tokens::$commentTokens, $remove_from, ( $remove_to + 1 ) ) === false ) { $fixable = true; } if ( false === $fixable ) { $this->phpcsFile->addWarning( $error, $first_non_empty, $error_code, $data ); return; } $fix = $this->phpcsFile->addFixableWarning( $error, $first_non_empty, $error_code, $data ); if ( true === $fix ) { $this->phpcsFile->fixer->beginChangeset(); for ( $i = $remove_from; $i <= $remove_to; $i++ ) { $this->phpcsFile->fixer->replaceToken( $i, '' ); } $this->phpcsFile->fixer->endChangeset(); } } }
Check the correct text domain is being used. @since 3.0.0 The logic in this method used to be contained in the, now removed, `check_argument_tokens()` method. @param string $matched_content The token content (function name) which was matched in lowercase. @param string $param_name The name of the parameter being examined. @param array|false $param_info Parameter info array for an individual parameter, as received from the PassedParameters class. @return void
check_textdomain_matches
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
private function check_placeholders_in_string( $matched_content, $param_name, $param_info ) { $content = $param_info['clean']; // UnorderedPlaceholders: Check for multiple unordered placeholders. $unordered_matches_count = preg_match_all( self::UNORDERED_SPRINTF_PLACEHOLDER_REGEX, $content, $unordered_matches ); $unordered_matches = $unordered_matches[0]; $all_matches_count = preg_match_all( self::SPRINTF_PLACEHOLDER_REGEX, $content, $all_matches ); if ( $unordered_matches_count > 0 && $unordered_matches_count !== $all_matches_count && $all_matches_count > 1 ) { $first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true ); $error_code = MessageHelper::stringToErrorcode( 'MixedOrderedPlaceholders' . ucfirst( $param_name ) ); $this->phpcsFile->addError( 'Multiple placeholders in translatable strings should be ordered. Mix of ordered and non-ordered placeholders found. Found: "%s" in %s.', $first_non_empty, $error_code, array( implode( ', ', $all_matches[0] ), $param_info['clean'] ) ); return; } if ( $unordered_matches_count >= 2 ) { $first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true ); $error_code = MessageHelper::stringToErrorcode( 'UnorderedPlaceholders' . ucfirst( $param_name ) ); $suggestions = array(); $replace_regexes = array(); $replacements = array(); for ( $i = 0; $i < $unordered_matches_count; $i++ ) { $to_insert = ( $i + 1 ); $to_insert .= ( '"' !== $content[0] ) ? '$' : '\$'; $suggestions[ $i ] = substr_replace( $unordered_matches[ $i ], $to_insert, 1, 0 ); // Prepare the strings for use in a regex. $replace_regexes[ $i ] = '`\Q' . $unordered_matches[ $i ] . '\E`'; // Note: the initial \\ is a literal \, the four \ in the replacement translate also to a literal \. $replacements[ $i ] = str_replace( '\\', '\\\\', $suggestions[ $i ] ); // Note: the $ needs escaping to prevent numeric sequences after the $ being interpreted as match replacements. $replacements[ $i ] = str_replace( '$', '\\$', $replacements[ $i ] ); } $fix = $this->phpcsFile->addFixableError( 'Multiple placeholders in translatable strings should be ordered. Expected "%s", but got "%s" in %s.', $first_non_empty, $error_code, array( implode( ', ', $suggestions ), implode( ', ', $unordered_matches ), $param_info['clean'] ) ); if ( true === $fix ) { $this->phpcsFile->fixer->beginChangeset(); $fixed_str = preg_replace( $replace_regexes, $replacements, $content, 1 ); $this->phpcsFile->fixer->replaceToken( $first_non_empty, $fixed_str ); $i = ( $first_non_empty + 1 ); while ( $i <= $param_info['end'] && isset( Tokens::$stringTokens[ $this->tokens[ $i ]['code'] ] ) ) { $this->phpcsFile->fixer->replaceToken( $i, '' ); ++$i; } $this->phpcsFile->fixer->endChangeset(); } } }
Check the placeholders used in translatable text for common problems. @since 3.0.0 The logic in this method used to be contained in the, now removed, `check_text()` method. @param string $matched_content The token content (function name) which was matched in lowercase. @param string $param_name The name of the parameter being examined. @param array|false $param_info Parameter info array for an individual parameter, as received from the PassedParameters class. @return void
check_placeholders_in_string
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
private function check_string_has_translatable_content( $matched_content, $param_name, $param_info ) { // Strip placeholders and surrounding quotes. $content_without_quotes = trim( TextStrings::stripQuotes( $param_info['clean'] ) ); $non_placeholder_content = preg_replace( self::SPRINTF_PLACEHOLDER_REGEX, '', $content_without_quotes ); if ( '' === $non_placeholder_content ) { $first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true ); $this->phpcsFile->addError( 'The $%s text string should have translatable content. Found: %s', $first_non_empty, 'NoEmptyStrings', array( $param_name, $param_info['clean'] ) ); return false; } return true; }
Check if a parameter which is supposed to hold translatable text actually has translatable text. @since 3.0.0 The logic in this method used to be contained in the, now removed, `check_text()` method. @param string $matched_content The token content (function name) which was matched in lowercase. @param string $param_name The name of the parameter being examined. @param array|false $param_info Parameter info array for an individual parameter, as received from the PassedParameters class. @return bool Whether or not the text string has translatable content.
check_string_has_translatable_content
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
private function check_string_has_no_html_wrapper( $matched_content, $param_name, $param_info ) { // Strip surrounding quotes. $content_without_quotes = trim( TextStrings::stripQuotes( $param_info['clean'] ) ); $reader = new XMLReader(); $reader->XML( $content_without_quotes, 'UTF-8', \LIBXML_NOERROR | \LIBXML_ERR_NONE | \LIBXML_NOWARNING ); // Is the first node an HTML element? if ( ! $reader->read() || XMLReader::ELEMENT !== $reader->nodeType ) { return; } // If the opening HTML element includes placeholders in its attributes, we don't warn. // E.g. '<option id="%1$s" value="%2$s">Translatable option name</option>'. $i = 0; while ( $attr = $reader->getAttributeNo( $i ) ) { if ( preg_match( self::SPRINTF_PLACEHOLDER_REGEX, $attr ) === 1 ) { return; } ++$i; } // We don't flag strings wrapped in `<a href="...">...</a>`, as the link target might actually need localization. if ( 'a' === $reader->name && $reader->getAttribute( 'href' ) ) { return; } // Does the entire string only consist of this HTML node? if ( $reader->readOuterXml() === $content_without_quotes ) { $first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info['start'], ( $param_info['end'] + 1 ), true ); $this->phpcsFile->addWarning( 'Translatable string should not be wrapped in HTML. Found: %s', $first_non_empty, 'NoHtmlWrappedStrings', array( $param_info['clean'] ) ); } }
Ensure that a translatable text string is not wrapped in HTML code. If the text is wrapped in HTML, the HTML should be moved out of the translatable text string. @since 3.0.0 The logic in this method used to be contained in the, now removed, `check_text()` method. @param string $matched_content The token content (function name) which was matched in lowercase. @param string $param_name The name of the parameter being examined. @param array|false $param_info Parameter info array for an individual parameter, as received from the PassedParameters class. @return void
check_string_has_no_html_wrapper
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
private function compare_single_and_plural_arguments( $stackPtr, $param_info_single, $param_info_plural ) { $single_content = $param_info_single['clean']; $plural_content = $param_info_plural['clean']; preg_match_all( self::SPRINTF_PLACEHOLDER_REGEX, $single_content, $single_placeholders ); $single_placeholders = $single_placeholders[0]; preg_match_all( self::SPRINTF_PLACEHOLDER_REGEX, $plural_content, $plural_placeholders ); $plural_placeholders = $plural_placeholders[0]; // English conflates "singular" with "only one", described in the codex: // https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals . if ( \count( $single_placeholders ) < \count( $plural_placeholders ) ) { $error_string = 'Missing singular placeholder, needed for some languages. See https://codex.wordpress.org/I18n_for_WordPress_Developers#Plurals'; $first_non_empty_single = $this->phpcsFile->findNext( Tokens::$emptyTokens, $param_info_single['start'], ( $param_info_single['end'] + 1 ), true ); $this->phpcsFile->addError( $error_string, $first_non_empty_single, 'MissingSingularPlaceholder' ); return; } // Reordering is fine, but mismatched placeholders is probably wrong. sort( $single_placeholders, \SORT_NATURAL ); sort( $plural_placeholders, \SORT_NATURAL ); if ( $single_placeholders !== $plural_placeholders ) { $this->phpcsFile->addWarning( 'Mismatched placeholders is probably an error', $stackPtr, 'MismatchedPlaceholders' ); } }
Check for inconsistencies in the placeholders between single and plural form of the translatable text string. @since 3.0.0 - The parameter names and expected format for the $param_info_single and the $param_info_plural parameters has changed. - The method visibility has been changed from `protected` to `private`. @param int $stackPtr The position of the function call token in the stack. @param array $param_info_single Parameter info array for the `$single` parameter, as received from the PassedParameters class. @param array $param_info_plural Parameter info array for the `$plural` parameter, as received from the PassedParameters class. @return void
compare_single_and_plural_arguments
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
private function check_for_translator_comment( $stackPtr, $matched_content, $parameters ) { $needs_translators_comment = false; foreach ( $parameters as $param_name => $param_info ) { if ( false === \in_array( $param_name, array( 'text', 'single', 'singular', 'plural' ), true ) ) { continue; } if ( false === $param_info || false === $param_info['is_string_literal'] ) { continue; } if ( preg_match( self::SPRINTF_PLACEHOLDER_REGEX, $param_info['clean'] ) === 1 ) { $needs_translators_comment = true; break; } } if ( false === $needs_translators_comment ) { // No text string with placeholders found, no translation comment needed. return; } $previous_comment = $this->phpcsFile->findPrevious( Tokens::$commentTokens, ( $stackPtr - 1 ) ); if ( false !== $previous_comment ) { /* * Check that the comment is either on the line before the gettext call or * if it's not, that there is only whitespace between. */ $correctly_placed = false; if ( ( $this->tokens[ $previous_comment ]['line'] + 1 ) === $this->tokens[ $stackPtr ]['line'] ) { $correctly_placed = true; } else { $next_non_whitespace = $this->phpcsFile->findNext( \T_WHITESPACE, ( $previous_comment + 1 ), $stackPtr, true ); if ( false === $next_non_whitespace || $this->tokens[ $next_non_whitespace ]['line'] === $this->tokens[ $stackPtr ]['line'] ) { // No non-whitespace found or next non-whitespace is on same line as gettext call. $correctly_placed = true; } unset( $next_non_whitespace ); } /* * Check that the comment starts with 'translators:'. */ if ( true === $correctly_placed ) { if ( \T_COMMENT === $this->tokens[ $previous_comment ]['code'] ) { $comment_text = trim( $this->tokens[ $previous_comment ]['content'] ); // If it's multi-line /* */ comment, collect all the parts. if ( '*/' === substr( $comment_text, -2 ) && '/*' !== substr( $comment_text, 0, 2 ) ) { for ( $i = ( $previous_comment - 1 ); 0 <= $i; $i-- ) { if ( \T_COMMENT !== $this->tokens[ $i ]['code'] ) { break; } $comment_text = trim( $this->tokens[ $i ]['content'] ) . $comment_text; } } if ( true === $this->is_translators_comment( $comment_text ) ) { // Comment is ok. return; } } if ( \T_DOC_COMMENT_CLOSE_TAG === $this->tokens[ $previous_comment ]['code'] ) { // If it's docblock comment (wrong style) make sure that it's a translators comment. if ( isset( $this->tokens[ $previous_comment ]['comment_opener'] ) ) { $db_start = $this->tokens[ $previous_comment ]['comment_opener']; } else { $db_start = $this->phpcsFile->findPrevious( \T_DOC_COMMENT_OPEN_TAG, ( $previous_comment - 1 ) ); } $db_first_text = $this->phpcsFile->findNext( \T_DOC_COMMENT_STRING, ( $db_start + 1 ), $previous_comment ); if ( true === $this->is_translators_comment( $this->tokens[ $db_first_text ]['content'] ) ) { $this->phpcsFile->addWarning( 'A "translators:" comment must be a "/* */" style comment. Docblock comments will not be picked up by the tools to generate a ".pot" file.', $stackPtr, 'TranslatorsCommentWrongStyle' ); return; } } } } // Found placeholders but no translators comment. $this->phpcsFile->addWarning( 'A function call to %s() with texts containing placeholders was found, but was not accompanied by a "translators:" comment on the line above to clarify the meaning of the placeholders.', $stackPtr, 'MissingTranslatorsComment', array( $matched_content ) ); }
Check for the presence of a translators comment if one of the text strings contains a placeholder. @since 3.0.0 - The parameter names and expected format for the $parameters parameter has changed. - The method visibility has been changed from `protected` to `private`. @param int $stackPtr The position of the gettext call token in the stack. @param string $matched_content The token content (function name) which was matched in lowercase. @param array $parameters Array with information about the parameters. @return void
check_for_translator_comment
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
private function is_translators_comment( $content ) { if ( preg_match( '`^(?:(?://|/\*{1,2}) )?translators:`i', $content ) === 1 ) { return true; } return false; }
Check if a (collated) comment string starts with 'translators:'. @since 0.11.0 @param string $content Comment string content. @return bool
is_translators_comment
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/I18nSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/I18nSniff.php
MIT
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { $function_details = $this->target_functions[ $matched_content ]; $parameter = PassedParameters::getParameterFromStack( $parameters, $function_details['position'], $function_details['name'] ); if ( false === $parameter ) { return; } // If the parameter is anything other than T_CONSTANT_ENCAPSED_STRING throw a warning and bow out. $first_non_empty = null; for ( $i = $parameter['start']; $i <= $parameter['end']; $i++ ) { if ( isset( Tokens::$emptyTokens[ $this->tokens[ $i ]['code'] ] ) ) { continue; } if ( \T_CONSTANT_ENCAPSED_STRING !== $this->tokens[ $i ]['code'] || null !== $first_non_empty ) { // Throw warning at low severity. $this->phpcsFile->addWarning( 'Couldn\'t determine the value passed to the $%s parameter in function call to %s(). Please check if it matches a valid capability. Found: %s', $i, 'Undetermined', array( $function_details['name'], $matched_content, $parameter['clean'], ), 3 // Message severity set to below default. ); return; } $first_non_empty = $i; } if ( null === $first_non_empty ) { // Parse error. Bow out. return; } /* * As of this point we know that the `$capabilities` parameter only contains the one token * and that that token is a `T_CONSTANT_ENCAPSED_STRING`. */ $matched_parameter = TextStrings::stripQuotes( $this->tokens[ $first_non_empty ]['content'] ); if ( isset( $this->core_capabilities[ $matched_parameter ] ) ) { return; } if ( empty( $matched_parameter ) ) { $this->phpcsFile->addError( 'An empty string is not a valid capability. Empty string found as the $%s parameter in a function call to %s()"', $first_non_empty, 'Invalid', array( $function_details['name'], $matched_content, ) ); return; } // Check if additional capabilities were registered via the ruleset and if the found capability matches any of those. $custom_capabilities = RulesetPropertyHelper::merge_custom_array( $this->custom_capabilities, array() ); if ( isset( $custom_capabilities[ $matched_parameter ] ) ) { return; } if ( isset( $this->deprecated_capabilities[ $matched_parameter ] ) ) { $this->set_minimum_wp_version(); $is_error = $this->wp_version_compare( $this->deprecated_capabilities[ $matched_parameter ], $this->minimum_wp_version, '<' ); $data = array( $matched_parameter, $matched_content, $this->deprecated_capabilities[ $matched_parameter ], ); MessageHelper::addMessage( $this->phpcsFile, 'The capability "%s", found in the function call to %s(), has been deprecated since WordPress version %s.', $first_non_empty, $is_error, 'Deprecated', $data ); return; } if ( isset( $this->core_roles[ $matched_parameter ] ) ) { $this->phpcsFile->addError( 'Capabilities should be used instead of roles. Found "%s" in function call to %s()', $first_non_empty, 'RoleFound', array( $matched_parameter, $matched_content, ) ); return; } $this->phpcsFile->addWarning( 'Found unknown capability "%s" in function call to %s(). Please check the spelling of the capability. If this is a custom capability, please verify the capability is registered with WordPress via a call to WP_Role(s)->add_cap().' . \PHP_EOL . 'Custom capabilities can be made known to this sniff by setting the "custom_capabilities" property in the PHPCS ruleset.', $first_non_empty, 'Unknown', array( $matched_parameter, $matched_content, ) ); }
Process the parameters of a matched function. @since 3.0.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 in lowercase. @param array $parameters Array with information about the parameters. @return void
process_parameters
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/CapabilitiesSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/CapabilitiesSniff.php
MIT
public function register() { return Tokens::$stringTokens; }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/CronIntervalSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/CronIntervalSniff.php
MIT
private function find_function_by_name( $functionName ) { $functionPtr = false; for ( $ptr = 0; $ptr < $this->phpcsFile->numTokens; $ptr++ ) { if ( \T_FUNCTION === $this->tokens[ $ptr ]['code'] ) { $foundName = FunctionDeclarations::getName( $this->phpcsFile, $ptr ); if ( $foundName === $functionName ) { $functionPtr = $ptr; break; } elseif ( isset( $this->tokens[ $ptr ]['scope_closer'] ) ) { // Skip to the end of the function definition. $ptr = $this->tokens[ $ptr ]['scope_closer']; } } } return $functionPtr; }
Find a declared function in a file based on the function name. @param string $functionName The name of the function to find. @return int|false Integer stack pointer to the function keyword token or false if not found.
find_function_by_name
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/CronIntervalSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/CronIntervalSniff.php
MIT
public function confused( $stackPtr ) { $this->phpcsFile->addWarning( 'Detected changing of cron_schedules, but could not detect the interval value.', $stackPtr, 'ChangeDetected' ); }
Add warning about unclear cron schedule change. @param int $stackPtr The position of the current token in the stack. @return void
confused
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/CronIntervalSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/CronIntervalSniff.php
MIT
public function getGroups() { // Make sure all array keys are lowercase. $this->deprecated_functions = array_change_key_case( $this->deprecated_functions, \CASE_LOWER ); return array( 'deprecated_functions' => array( 'functions' => array_keys( $this->deprecated_functions ), ), ); }
Groups of functions to restrict. @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/DeprecatedFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DeprecatedFunctionsSniff.php
MIT
public function process_matched_token( $stackPtr, $group_name, $matched_content ) { $this->set_minimum_wp_version(); $message = '%s() has been deprecated since WordPress version %s.'; $data = array( $this->tokens[ $stackPtr ]['content'], $this->deprecated_functions[ $matched_content ]['version'], ); if ( ! empty( $this->deprecated_functions[ $matched_content ]['alt'] ) ) { $message .= ' Use %s instead.'; $data[] = $this->deprecated_functions[ $matched_content ]['alt']; } MessageHelper::addMessage( $this->phpcsFile, $message, $stackPtr, ( $this->wp_version_compare( $this->deprecated_functions[ $matched_content ]['version'], $this->minimum_wp_version, '<' ) ), MessageHelper::stringToErrorcode( $matched_content . 'Found' ), $data ); }
Process a matched token. @param int $stackPtr The position of the current token in the stack. @param string $group_name The name of the group which was matched. Will always be 'deprecated_functions'. @param string $matched_content The token content (function name) which was matched in lowercase. @return void
process_matched_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/DeprecatedFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DeprecatedFunctionsSniff.php
MIT
public function getGroups() { return array( 'query_posts' => array( 'type' => 'warning', 'message' => '%s() is discouraged. Use WP_Query instead.', 'functions' => array( 'query_posts', ), ), 'wp_reset_query' => array( 'type' => 'warning', 'message' => '%s() is discouraged. Use wp_reset_postdata() instead.', 'functions' => array( 'wp_reset_query', ), ), ); }
Groups of functions to restrict. Example: groups => array( 'lambda' => array( 'type' => 'error' | 'warning', 'message' => 'Use anonymous functions instead please!', 'functions' => array( 'file_get_contents', 'create_function' ), ) ) @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/DiscouragedFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DiscouragedFunctionsSniff.php
MIT
protected function process_parameter( $matched_content, $parameter, $parameter_args ) { $parameter_position = $this->phpcsFile->findNext( Tokens::$emptyTokens, $parameter['start'], $parameter['end'] + 1, true ); if ( false === $parameter_position ) { return; } $matched_parameter = TextStrings::stripQuotes( $this->tokens[ $parameter_position ]['content'] ); if ( ! isset( $parameter_args[ $matched_parameter ] ) ) { return; } $message = 'The parameter value "%s" has been deprecated since WordPress version %s.'; $data = array( $matched_parameter, $parameter_args[ $matched_parameter ]['version'], ); if ( ! empty( $parameter_args[ $matched_parameter ]['alt'] ) ) { $message .= ' Use %s instead.'; $data[] = $parameter_args[ $matched_parameter ]['alt']; } $is_error = $this->wp_version_compare( $parameter_args[ $matched_parameter ]['version'], $this->minimum_wp_version, '<' ); MessageHelper::addMessage( $this->phpcsFile, $message, $parameter_position, $is_error, 'Found', $data ); }
Process the parameter of a matched function. @since 1.0.0 @param string $matched_content The token content (function name) which was matched in lowercase. @param array $parameter Array with start and end token position of the parameter. @param array $parameter_args Array with alternative and WordPress deprecation version of the parameter. @return void
process_parameter
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/DeprecatedParameterValuesSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DeprecatedParameterValuesSniff.php
MIT
public function process_token( $stackPtr ) { if ( isset( $this->target_functions[ strtolower( $this->tokens[ $stackPtr ]['content'] ) ] ) ) { // Disallow excluding function groups for this sniff. $this->exclude = array(); return parent::process_token( $stackPtr ); } else { return $this->process_arbitrary_tstring( $stackPtr ); } }
Processes this test, when one of its tokens is encountered. @since 0.14.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.
process_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/DiscouragedConstantsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DiscouragedConstantsSniff.php
MIT
public function process_arbitrary_tstring( $stackPtr ) { $content = $this->tokens[ $stackPtr ]['content']; if ( ! isset( $this->discouraged_constants[ $content ] ) ) { return; } if ( ConstantsHelper::is_use_of_global_constant( $this->phpcsFile, $stackPtr ) === false ) { return; } $this->phpcsFile->addWarning( 'Found usage of constant "%s". Use %s instead.', $stackPtr, MessageHelper::stringToErrorcode( $content . 'UsageFound' ), array( $content, $this->discouraged_constants[ $content ], ) ); }
Process an arbitrary T_STRING token to determine whether it is one of the target constants. @since 0.14.0 @param int $stackPtr The position of the current token in the stack. @return void
process_arbitrary_tstring
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/DiscouragedConstantsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DiscouragedConstantsSniff.php
MIT
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { $target_param = $this->target_functions[ $matched_content ]; // Was the target parameter passed ? $found_param = PassedParameters::getParameterFromStack( $parameters, $target_param['position'], $target_param['name'] ); if ( false === $found_param ) { return; } $clean_content = TextStrings::stripQuotes( $found_param['clean'] ); if ( isset( $this->discouraged_constants[ $clean_content ] ) ) { $first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $found_param['start'], ( $found_param['end'] + 1 ), true ); $this->phpcsFile->addWarning( 'Found declaration of constant "%s". Use %s instead.', $first_non_empty, MessageHelper::stringToErrorcode( $clean_content . 'DeclarationFound' ), array( $clean_content, $this->discouraged_constants[ $clean_content ], ) ); } }
Process the parameters of a matched `define` function call. @since 0.14.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 in lowercase. @param array $parameters Array with information about the parameters. @return void
process_parameters
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/DiscouragedConstantsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/DiscouragedConstantsSniff.php
MIT
public function register() { $targets = array( \T_GLOBAL, \T_VARIABLE, ); $targets += Collections::listOpenTokensBC(); // Only used to skip over test classes. $targets += Tokens::$ooScopeTokens; return $targets; }
Returns an array of tokens this test wants to listen for. @since 0.3.0 @since 1.1.0 Added class tokens for improved test classes skipping. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php
MIT
protected function process_variable_assignment( $stackPtr, $in_list = false ) { $token = $this->tokens[ $stackPtr ]; $var_name = substr( $token['content'], 1 ); // Strip the dollar sign. $data = array(); // Determine the variable name for `$GLOBALS['array_key']`. if ( 'GLOBALS' === $var_name ) { $bracketPtr = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); if ( false === $bracketPtr || \T_OPEN_SQUARE_BRACKET !== $this->tokens[ $bracketPtr ]['code'] || ! isset( $this->tokens[ $bracketPtr ]['bracket_closer'] ) ) { return; } // Retrieve the array key and avoid getting tripped up by some simple obfuscation. $var_name = ''; $start = ( $bracketPtr + 1 ); for ( $ptr = $start; $ptr < $this->tokens[ $bracketPtr ]['bracket_closer']; $ptr++ ) { /* * If the globals array key contains a variable, constant, function call * or interpolated variable, bow out. */ if ( \T_VARIABLE === $this->tokens[ $ptr ]['code'] || \T_STRING === $this->tokens[ $ptr ]['code'] || \T_DOUBLE_QUOTED_STRING === $this->tokens[ $ptr ]['code'] ) { return; } if ( \T_CONSTANT_ENCAPSED_STRING === $this->tokens[ $ptr ]['code'] ) { $var_name .= TextStrings::stripQuotes( $this->tokens[ $ptr ]['content'] ); } } if ( '' === $var_name ) { // Shouldn't happen, but just in case. return; } // Set up the data for the error message. $data[] = '$GLOBALS[\'' . $var_name . '\']'; } /* * Is this one of the WP global variables ? */ if ( WPGlobalVariablesHelper::is_wp_global( $var_name ) === false ) { return; } /* * Is this one of the WP global variables which are allowed to be overwritten ? */ if ( isset( $this->override_allowed[ $var_name ] ) === true ) { return; } /* * Check if the variable value is being changed. */ if ( false === $in_list && false === VariableHelper::is_assignment( $this->phpcsFile, $stackPtr ) && Context::inForeachCondition( $this->phpcsFile, $stackPtr ) !== 'afterAs' ) { return; } /* * Function parameters with the same name as a WP global variable are fine, * including when they are being assigned a default value. */ if ( false === $in_list ) { $functionPtr = Parentheses::getLastOwner( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); if ( false !== $functionPtr ) { return; } unset( $functionPtr ); } /* * Class property declarations with the same name as WP global variables are fine. */ if ( false === $in_list && true === Scopes::isOOProperty( $this->phpcsFile, $stackPtr ) ) { return; } // Still here ? In that case, the WP global variable is being tampered with. $this->add_error( $stackPtr, $data ); }
Check that defined global variables are prefixed. @since 1.1.0 Logic was previously contained in the process_token() method. @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 void
process_variable_assignment
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php
MIT
protected function process_global_statement( $stackPtr, $in_function_scope ) { /* * Collect the variables to watch for. */ $search = array(); $ptr = ( $stackPtr + 1 ); $end_of_statement = $this->phpcsFile->findNext( array( \T_SEMICOLON, \T_CLOSE_TAG ), $ptr ); while ( isset( $this->tokens[ $ptr ] ) && $ptr < $end_of_statement ) { if ( \T_VARIABLE === $this->tokens[ $ptr ]['code'] ) { $var_name = substr( $this->tokens[ $ptr ]['content'], 1 ); if ( WPGlobalVariablesHelper::is_wp_global( $var_name ) && isset( $this->override_allowed[ $var_name ] ) === false ) { $search[ $this->tokens[ $ptr ]['content'] ] = true; } } ++$ptr; } if ( empty( $search ) ) { return; } /* * Search for assignments to the imported global variables within the relevant scope. */ $start = $ptr; if ( true === $in_function_scope ) { $functionPtr = Conditions::getLastCondition( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); if ( isset( $this->tokens[ $functionPtr ]['scope_closer'] ) === false ) { // Live coding or parse error. return; } $end = $this->tokens[ $functionPtr ]['scope_closer']; } else { // Global statement in the global namespace in a file which is being treated as scoped. $end = $this->phpcsFile->numTokens; } for ( $ptr = $start; $ptr < $end; $ptr++ ) { // Skip over nested functions, classes and the likes. if ( isset( Collections::closedScopes()[ $this->tokens[ $ptr ]['code'] ] ) ) { if ( ! isset( $this->tokens[ $ptr ]['scope_closer'] ) ) { // Live coding or parse error. break; } $ptr = $this->tokens[ $ptr ]['scope_closer']; continue; } // Make sure to recognize assignments to variables in a list construct. if ( isset( Collections::listOpenTokensBC()[ $this->tokens[ $ptr ]['code'] ] ) ) { $list_open_close = Lists::getOpenClose( $this->phpcsFile, $ptr ); if ( false === $list_open_close ) { // Short array, not short list. continue; } $var_pointers = ListHelper::get_list_variables( $this->phpcsFile, $ptr ); foreach ( $var_pointers as $ptr ) { $var_name = $this->tokens[ $ptr ]['content']; if ( '$GLOBALS' === $var_name ) { $var_name = '$' . TextStrings::stripQuotes( VariableHelper::get_array_access_key( $this->phpcsFile, $ptr ) ); } if ( isset( $search[ $var_name ] ) ) { $this->process_variable_assignment( $ptr, true ); } } // No need to re-examine these variables. $ptr = $list_open_close['closer']; continue; } if ( \T_VARIABLE !== $this->tokens[ $ptr ]['code'] ) { continue; } if ( isset( $search[ $this->tokens[ $ptr ]['content'] ] ) === false ) { // Not one of the variables we're interested in. continue; } // Don't throw false positives for static class properties. if ( ContextHelper::has_object_operator_before( $this->phpcsFile, $ptr ) === true ) { continue; } if ( true === VariableHelper::is_assignment( $this->phpcsFile, $ptr ) ) { $this->add_error( $ptr ); continue; } // Check if this is a variable assignment within a `foreach()` declaration. if ( Context::inForeachCondition( $this->phpcsFile, $ptr ) === 'afterAs' ) { $this->add_error( $ptr ); } } }
Check that global variables imported into a function scope using a global statement are not being overruled. @since 1.1.0 Logic was previously contained in the process_token() method. @param int $stackPtr The position of the current token in the stack. @param bool $in_function_scope Whether the global statement is within a scoped function/closure. @return void
process_global_statement
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WP/GlobalVariablesOverrideSniff.php
MIT
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { /* * We already know there will be valid open & close parentheses as otherwise the parameter * retrieval function call would have returned an empty array, so no additional checks needed. */ $open_parens = $this->phpcsFile->findNext( \T_OPEN_PARENTHESIS, $stackPtr ); $close_parens = $this->tokens[ $open_parens ]['parenthesis_closer']; /* * Check whether the first parameter is a timestamp format. */ $type_param = PassedParameters::getParameterFromStack( $parameters, 1, 'type' ); if ( false === $type_param ) { // Type parameter not found. Bow out. return; } $content_type = ''; for ( $i = $type_param['start']; $i <= $type_param['end']; $i++ ) { if ( isset( Tokens::$emptyTokens[ $this->tokens[ $i ]['code'] ] ) ) { continue; } if ( isset( Tokens::$textStringTokens[ $this->tokens[ $i ]['code'] ] ) ) { $content_type = trim( TextStrings::stripQuotes( $this->tokens[ $i ]['content'] ) ); if ( 'U' !== $content_type && 'timestamp' !== $content_type ) { // Most likely valid use of current_time(). return; } continue; } if ( isset( Tokens::$heredocTokens[ $this->tokens[ $i ]['code'] ] ) ) { continue; } /* * If we're still here, we've encountered an unexpected token, like a variable or * function call. Bow out as we can't determine the runtime value. */ return; } $gmt_true = false; /* * Check whether the second parameter, $gmt, is a set to `true` or `1`. */ $gmt_param = PassedParameters::getParameterFromStack( $parameters, 2, 'gmt' ); if ( is_array( $gmt_param ) ) { $content_gmt = ''; if ( 'true' === $gmt_param['clean'] || '1' === $gmt_param['clean'] ) { $content_gmt = $gmt_param['clean']; $gmt_true = true; } } /* * Non-UTC timestamp requested. */ if ( false === $gmt_true ) { $this->phpcsFile->addWarning( 'Calling current_time() with a $type of "timestamp" or "U" is strongly discouraged as it will not return a Unix (UTC) timestamp. Please consider using a non-timestamp format or otherwise refactoring this code.', $stackPtr, 'Requested' ); return; } /* * UTC timestamp requested. Should use time() instead. */ $has_comment = $this->phpcsFile->findNext( Tokens::$commentTokens, ( $stackPtr + 1 ), ( $close_parens + 1 ) ); $error = 'Don\'t use current_time() for retrieving a Unix (UTC) timestamp. Use time() instead. Found: %s'; $error_code = 'RequestedUTC'; $code_snippet = "current_time( '" . $content_type . "'"; if ( isset( $content_gmt ) ) { $code_snippet .= ', ' . $content_gmt; } $code_snippet .= ' )'; if ( false !== $has_comment ) { // If there are comments, we don't auto-fix as it would remove those comments. $this->phpcsFile->addError( $error, $stackPtr, $error_code, array( $code_snippet ) ); return; } $fix = $this->phpcsFile->addFixableError( $error, $stackPtr, $error_code, array( $code_snippet ) ); if ( true === $fix ) { $this->phpcsFile->fixer->beginChangeset(); for ( $i = ( $stackPtr + 1 ); $i < $close_parens; $i++ ) { $this->phpcsFile->fixer->replaceToken( $i, '' ); } $this->phpcsFile->fixer->replaceToken( $stackPtr, 'time(' ); $this->phpcsFile->fixer->endChangeset(); } }
Process the parameters of a matched function. @since 2.2.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 in lowercase. @param array $parameters Array with information about the parameters. @return void
process_parameters
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/DateTime/CurrentTimeTimestampSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DateTime/CurrentTimeTimestampSniff.php
MIT
public function getGroups() { return array( /* * Disallow the changing the timezone. * * @link https://vip.wordpress.com/documentation/vip-go/code-review-blockers-warnings-notices/#manipulating-the-timezone-server-side */ 'timezone_change' => array( 'type' => 'error', 'message' => 'Using %s() and similar isn\'t allowed, instead use WP internal timezone support.', 'functions' => array( 'date_default_timezone_set', ), ), /* * Use gmdate(), not date(). * Don't rely on the current PHP time zone as it might have been changed by third party code. * * @link https://make.wordpress.org/core/2019/09/23/date-time-improvements-wp-5-3/ * @link https://core.trac.wordpress.org/ticket/46438 * @link https://github.com/WordPress/WordPress-Coding-Standards/issues/1713 */ 'date' => array( 'type' => 'error', 'message' => '%s() is affected by runtime timezone changes which can cause date/time to be incorrectly displayed. Use gmdate() instead.', 'functions' => array( 'date', ), ), ); }
Groups of functions to restrict. @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/DateTime/RestrictedFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DateTime/RestrictedFunctionsSniff.php
MIT
public function register() { return array( \T_VARIABLE, \T_DOUBLE_QUOTED_STRING, \T_HEREDOC, ); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/ValidatedSanitizedInputSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/ValidatedSanitizedInputSniff.php
MIT
public function add_unslash_error( File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); $var_name = $tokens[ $stackPtr ]['content']; if ( isset( $this->slashed_superglobals[ $var_name ] ) === false ) { // WP doesn't slash these, so they don't need unslashing. return; } // We know there will be array keys as that's checked in the process_token() method. $array_keys = VariableHelper::get_array_access_keys( $phpcsFile, $stackPtr ); $error_data = array( $var_name . '[' . implode( '][', $array_keys ) . ']' ); $phpcsFile->addError( '%s not unslashed before sanitization. Use wp_unslash() or similar', $stackPtr, 'MissingUnslash', $error_data ); }
Add an error for missing use of unslashing. @since 0.5.0 @since 3.0.0 - Moved from the `Sniff` class to this class. - The `$phpcsFile` parameter was added. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The index of the token in the stack which is missing unslashing. @return void
add_unslash_error
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/ValidatedSanitizedInputSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/ValidatedSanitizedInputSniff.php
MIT
public function register() { $targets = array( \T_VARIABLE => \T_VARIABLE ); $targets += Collections::listOpenTokensBC(); // We need to skip over lists. return $targets; }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/NonceVerificationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php
MIT
public function process_token( $stackPtr ) { // Skip over lists as whatever is in those will always be assignments. if ( isset( Collections::listOpenTokensBC()[ $this->tokens[ $stackPtr ]['code'] ] ) ) { $open_close = Lists::getOpenClose( $this->phpcsFile, $stackPtr ); $skip_to = $stackPtr; if ( false !== $open_close ) { $skip_to = $open_close['closer']; } return $skip_to; } if ( ! isset( $this->superglobals[ $this->tokens[ $stackPtr ]['content'] ] ) ) { return; } if ( Scopes::isOOProperty( $this->phpcsFile, $stackPtr ) ) { // Property with the same name as a superglobal. Not our target. return; } // Determine the cache keys for this item. $cache_keys = array( 'file' => $this->phpcsFile->getFilename(), 'start' => 0, 'end' => $stackPtr, ); // If we're in a function, only look inside of it. // This doesn't take arrow functions into account as those are "open". $functionPtr = Conditions::getLastCondition( $this->phpcsFile, $stackPtr, array( \T_FUNCTION, \T_CLOSURE ) ); if ( false !== $functionPtr ) { $cache_keys['start'] = $this->tokens[ $functionPtr ]['scope_opener']; } $this->mergeFunctionLists(); $needs_nonce = $this->needs_nonce_check( $stackPtr, $cache_keys ); if ( false === $needs_nonce ) { return; } if ( $this->has_nonce_check( $stackPtr, $cache_keys, ( 'after' === $needs_nonce ) ) ) { return; } // If we're still here, no nonce-verification function was found. $error_code = 'Missing'; if ( false === $this->superglobals[ $this->tokens[ $stackPtr ]['content'] ] ) { $error_code = 'Recommended'; } MessageHelper::addMessage( $this->phpcsFile, 'Processing form data without nonce verification.', $stackPtr, $this->superglobals[ $this->tokens[ $stackPtr ]['content'] ], $error_code ); }
Processes this test, when one of its tokens is encountered. @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.
process_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/NonceVerificationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php
MIT
protected function needs_nonce_check( $stackPtr, array $cache_keys ) { $in_nonce_check = ContextHelper::is_in_function_call( $this->phpcsFile, $stackPtr, $this->nonceVerificationFunctions ); if ( false !== $in_nonce_check ) { // This *is* the nonce check, so bow out, but do store to cache. // @todo Change to use arg unpacking once PHP < 5.6 has been dropped. $this->set_cache( $cache_keys['file'], $cache_keys['start'], $cache_keys['end'], $in_nonce_check ); return false; } if ( Context::inUnset( $this->phpcsFile, $stackPtr ) ) { // Variable is only being unset, no nonce check needed. return false; } if ( VariableHelper::is_assignment( $this->phpcsFile, $stackPtr, false ) ) { // Overwriting the value of a superglobal. return false; } $needs_nonce = 'before'; if ( ContextHelper::is_in_isset_or_empty( $this->phpcsFile, $stackPtr ) || ContextHelper::is_in_type_test( $this->phpcsFile, $stackPtr ) || VariableHelper::is_comparison( $this->phpcsFile, $stackPtr ) || VariableHelper::is_assignment( $this->phpcsFile, $stackPtr, true ) || ContextHelper::is_in_array_comparison( $this->phpcsFile, $stackPtr ) || ContextHelper::is_in_function_call( $this->phpcsFile, $stackPtr, UnslashingFunctionsHelper::get_functions() ) !== false || $this->is_only_sanitized( $this->phpcsFile, $stackPtr ) ) { $needs_nonce = 'after'; } return $needs_nonce; }
Determine whether or not a nonce check is needed for the current superglobal. @since 3.0.0 @param int $stackPtr The position of the current token in the stack of tokens. @param array $cache_keys The keys for the applicable cache (to potentially set). @return string|false String "before" or "after" if a nonce check is needed. FALSE when no nonce check is needed.
needs_nonce_check
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/NonceVerificationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php
MIT
private function has_nonce_check( $stackPtr, array $cache_keys, $allow_nonce_after = false ) { $start = $cache_keys['start']; $end = $cache_keys['end']; // We allow for certain actions, such as an isset() check to come before the nonce check. // If this superglobal is inside such a check, look for the nonce after it as well, // all the way to the end of the scope. if ( true === $allow_nonce_after ) { $end = ( 0 === $start ) ? $this->phpcsFile->numTokens : $this->tokens[ $start ]['scope_closer']; } // Check against the cache. $current_cache = $this->get_cache( $cache_keys['file'], $start ); if ( false !== $current_cache['nonce'] ) { // If we have already found a nonce check in this scope, we just // need to check whether it comes before this token. It is OK if the // check is after the token though, if this was only an isset() check. return ( true === $allow_nonce_after || $current_cache['nonce'] < $stackPtr ); } elseif ( $end <= $current_cache['end'] ) { // If not, we can still go ahead and return false if we've already // checked to the end of the search area. return false; } $search_start = $start; if ( $current_cache['end'] > $start ) { // We haven't checked this far yet, but we can still save work by // skipping over the part we've already checked. $search_start = $this->cached_results['cache'][ $start ]['end']; } // Loop through the tokens looking for nonce verification functions. for ( $i = $search_start; $i < $end; $i++ ) { // Skip over nested closed scope constructs. if ( isset( Collections::closedScopes()[ $this->tokens[ $i ]['code'] ] ) || \T_FN === $this->tokens[ $i ]['code'] ) { if ( isset( $this->tokens[ $i ]['scope_closer'] ) ) { $i = $this->tokens[ $i ]['scope_closer']; } continue; } // If this isn't a function name, skip it. if ( \T_STRING !== $this->tokens[ $i ]['code'] ) { continue; } // If this is one of the nonce verification functions, we can bail out. if ( isset( $this->nonceVerificationFunctions[ $this->tokens[ $i ]['content'] ] ) ) { /* * Now, make sure it is a call to a global function. */ if ( ContextHelper::has_object_operator_before( $this->phpcsFile, $i ) === true ) { continue; } if ( ContextHelper::is_token_namespaced( $this->phpcsFile, $i ) === true ) { continue; } $this->set_cache( $cache_keys['file'], $start, $end, $i ); return true; } } // We're still here, so no luck. $this->set_cache( $cache_keys['file'], $start, $end, false ); return false; }
Check if this token has an associated nonce check. @since 0.5.0 @since 3.0.0 - Moved from the generic `Sniff` class to this class. - Visibility changed from `protected` to `private. - New `$cache_keys` parameter. - New `$allow_nonce_after` parameter. @param int $stackPtr The position of the current token in the stack of tokens. @param array $cache_keys The keys for the applicable cache. @param bool $allow_nonce_after Whether the nonce check _must_ be before the $stackPtr or is allowed _after_ the $stackPtr. @return bool
has_nonce_check
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/NonceVerificationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php
MIT
private function get_cache( $filename, $start ) { if ( is_array( $this->cached_results ) && $filename === $this->cached_results['file'] && isset( $this->cached_results['cache'][ $start ] ) ) { return $this->cached_results['cache'][ $start ]; } return array( 'end' => 0, 'nonce' => false, ); }
Helper function to retrieve results from the cache. @since 3.0.0 @param string $filename The name of the current file. @param int $start The stack pointer searches started from. @return array<string, mixed>
get_cache
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/NonceVerificationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php
MIT
private function set_cache( $filename, $start, $end, $nonce ) { if ( is_array( $this->cached_results ) === false || $filename !== $this->cached_results['file'] ) { $this->cached_results = array( 'file' => $filename, 'cache' => array( $start => array( 'end' => $end, 'nonce' => $nonce, ), ), ); return; } // Okay, so we know the current cache is for the current file. Check if we've seen this start pointer before. if ( isset( $this->cached_results['cache'][ $start ] ) === false ) { $this->cached_results['cache'][ $start ] = array( 'end' => $end, 'nonce' => $nonce, ); return; } // Update existing entry. if ( $end > $this->cached_results['cache'][ $start ]['end'] ) { $this->cached_results['cache'][ $start ]['end'] = $end; } $this->cached_results['cache'][ $start ]['nonce'] = $nonce; }
Helper function to store results to the cache. @since 3.0.0 @param string $filename The name of the current file. @param int $start The stack pointer searches started from. @param int $end The stack pointer searched stopped at. @param int|bool $nonce Stack pointer to the nonce verification function call or false if none was found. @return void
set_cache
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/NonceVerificationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php
MIT
protected function mergeFunctionLists() { if ( $this->customNonceVerificationFunctions !== $this->addedCustomNonceFunctions ) { $this->nonceVerificationFunctions = RulesetPropertyHelper::merge_custom_array( $this->customNonceVerificationFunctions, $this->nonceVerificationFunctions ); $this->addedCustomNonceFunctions = $this->customNonceVerificationFunctions; } }
Merge custom functions provided via a custom ruleset with the defaults, if we haven't already. @since 0.11.0 Split out from the `process()` method. @return void
mergeFunctionLists
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/NonceVerificationSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/NonceVerificationSniff.php
MIT
public function register() { // Enrich the list of "safe components" tokens. $this->safe_components += Tokens::$comparisonTokens; $this->safe_components += Tokens::$operators; $this->safe_components += Tokens::$booleanOperators; $this->safe_components += Collections::incrementDecrementOperators(); // Set up the tokens the sniff should listen to. $targets = array_merge( parent::register(), $this->target_keywords ); $targets[] = \T_ECHO; $targets[] = \T_OPEN_TAG_WITH_ECHO; return $targets; }
Returns an array of tokens this test wants to listen for. @return string|int[]
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/EscapeOutputSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/EscapeOutputSniff.php
MIT
public function getGroups() { // Make sure all array keys are lowercase (could contain user-provided function names). $printing_functions = array_change_key_case( $this->get_printing_functions(), \CASE_LOWER ); // Remove the unsafe printing functions to prevent duplicate notices. $printing_functions = array_diff_key( $printing_functions, $this->unsafePrintingFunctions ); return array( 'unsafe_printing_functions' => array( 'functions' => array_keys( $this->unsafePrintingFunctions ), ), 'printing_functions' => array( 'functions' => array_keys( $printing_functions ), ), ); }
Groups of functions this sniff is looking for. @since 3.0.0 @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/EscapeOutputSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/EscapeOutputSniff.php
MIT
private function find_long_ternary( $start, $end ) { for ( $i = $start; $i < $end; $i++ ) { // Ignore anything within square brackets. if ( isset( $this->tokens[ $i ]['bracket_opener'], $this->tokens[ $i ]['bracket_closer'] ) && $i === $this->tokens[ $i ]['bracket_opener'] ) { $i = $this->tokens[ $i ]['bracket_closer']; continue; } // Skip past nested arrays, function calls and arbitrary groupings. if ( \T_OPEN_PARENTHESIS === $this->tokens[ $i ]['code'] && isset( $this->tokens[ $i ]['parenthesis_closer'] ) ) { $i = $this->tokens[ $i ]['parenthesis_closer']; continue; } // Skip past closures, anonymous classes and anything else scope related. if ( isset( $this->tokens[ $i ]['scope_condition'], $this->tokens[ $i ]['scope_closer'] ) && $this->tokens[ $i ]['scope_condition'] === $i ) { $i = $this->tokens[ $i ]['scope_closer']; continue; } if ( \T_INLINE_THEN !== $this->tokens[ $i ]['code'] ) { continue; } /* * Okay, we found a ternary and it should be at the correct nesting level. * If this is a short ternary, it shouldn't be ignored though. */ if ( Operators::isShortTernary( $this->phpcsFile, $i ) === true ) { return false; } return $i; } return false; }
Check whether there is a ternary token at the right nesting level in an arbitrary set of tokens. @since 3.0.0 Split off from the process_token() method. @param int $start The position to start checking from. @param int $end The position to stop the check at. @return int|false Stack pointer to the ternary or FALSE if no ternary was found or if this is a short ternary.
find_long_ternary
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/EscapeOutputSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/EscapeOutputSniff.php
MIT
public function getGroups() { return array( 'wp_redirect' => array( 'type' => 'warning', 'message' => '%s() found. Using wp_safe_redirect(), along with the "allowed_redirect_hosts" filter if needed, can help avoid any chances of malicious redirects within code. It is also important to remember to call exit() after a redirect so that no other unwanted code is executed.', 'functions' => array( 'wp_redirect', ), ), ); }
Groups of functions to restrict. Example: groups => array( 'lambda' => array( 'type' => 'error' | 'warning', 'message' => 'Use anonymous functions instead please!', 'functions' => array( 'file_get_contents', 'create_function' ), ) ) @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Security/SafeRedirectSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Security/SafeRedirectSniff.php
MIT
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { $param_info = $this->target_functions[ $matched_content ]; /* * Check if the strict check is actually needed. * * Important! This check only applies to array_keys() in the current form of the sniff * and has been written to be specific to that function. * If more functions would be added with 'always_needed' set to `false`, * this code will need to be adjusted to handle those. */ if ( false === $param_info['always_needed'] ) { $has_filter_value = PassedParameters::getParameterFromStack( $parameters, 2, 'filter_value' ); if ( false === $has_filter_value ) { return; } } $found_parameter = PassedParameters::getParameterFromStack( $parameters, $param_info['param_position'], $param_info['param_name'] ); if ( false === $found_parameter || 'true' !== strtolower( $found_parameter['clean'] ) ) { $errorcode = 'MissingTrueStrict'; /* * Use a different error code when `false` is found to allow for excluding * the warning as this will be a conscious choice made by the dev. */ if ( is_array( $found_parameter ) && 'false' === strtolower( $found_parameter['clean'] ) ) { $errorcode = 'FoundNonStrictFalse'; } $this->phpcsFile->addWarning( 'Not using strict comparison for %s; supply true for $%s argument.', ( isset( $found_parameter['start'] ) ? $found_parameter['start'] : $stackPtr ), $errorcode, array( $matched_content, $param_info['param_name'] ) ); } }
Process the parameters of a matched function. @since 0.11.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 in lowercase. @param array $parameters Array with information about the parameters. @return void
process_parameters
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/StrictInArraySniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/StrictInArraySniff.php
MIT
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { $delimiter = PassedParameters::getParameterFromStack( $parameters, 2, 'delimiter' ); if ( false !== $delimiter ) { return; } $this->phpcsFile->addWarning( 'Passing the $delimiter parameter to preg_quote() is strongly recommended.', $stackPtr, 'Missing' ); }
Process the parameters of a matched function. @since 1.0.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 in lowercase. @param array $parameters Array with information about the parameters. @return void
process_parameters
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/PregQuoteDelimiterSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/PregQuoteDelimiterSniff.php
MIT
public function getGroups() { return array( 'create_function' => array( 'type' => 'error', 'message' => '%s() is deprecated as of PHP 7.2 and removed in PHP 8.0. Please use declared named or anonymous functions instead.', 'functions' => array( 'create_function', ), ), ); }
Groups of functions to forbid. Example: groups => array( 'lambda' => array( 'type' => 'error' | 'warning', 'message' => 'Use anonymous functions instead please!', 'functions' => array( 'file_get_contents', 'create_function' ), ) ) @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/RestrictedPHPFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/RestrictedPHPFunctionsSniff.php
MIT
public function getGroups() { return array( 'extract' => array( 'type' => 'error', 'message' => '%s() usage is highly discouraged, due to the complexity and unintended issues it might cause.', 'functions' => array( 'extract', ), ), ); }
Groups of functions to restrict. Example: groups => array( 'lambda' => array( 'type' => 'error' | 'warning', 'message' => 'Use anonymous functions instead please!', 'functions' => array( 'file_get_contents', 'create_function' ), ) ) @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/DontExtractSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/DontExtractSniff.php
MIT
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { $option_param = PassedParameters::getParameterFromStack( $parameters, 1, 'option' ); $value_param = PassedParameters::getParameterFromStack( $parameters, 2, 'value' ); if ( false === $option_param || false === $value_param ) { // Missing required param. Not the concern of this sniff. Bow out. return; } $option_name = TextStrings::stripQuotes( $option_param['clean'] ); $option_value = TextStrings::stripQuotes( $value_param['clean'] ); if ( isset( $this->safe_options[ $option_name ] ) ) { $safe_option = $this->safe_options[ $option_name ]; if ( empty( $safe_option['valid_values'] ) || in_array( strtolower( $option_value ), $safe_option['valid_values'], true ) ) { return; } } if ( isset( $this->disallowed_options[ $option_name ] ) ) { $disallowed_option = $this->disallowed_options[ $option_name ]; if ( empty( $disallowed_option['invalid_values'] ) || in_array( strtolower( $option_value ), $disallowed_option['invalid_values'], true ) ) { $this->phpcsFile->addError( 'Found: %s(%s, %s). %s', $stackPtr, MessageHelper::stringToErrorcode( $option_name . '_Disallowed' ), array( $matched_content, $option_param['clean'], $value_param['clean'], $disallowed_option['message'], ) ); return; } } $this->phpcsFile->addWarning( 'Changing configuration values at runtime is strongly discouraged. Found: %s(%s, %s)', $stackPtr, 'Risky', array( $matched_content, $option_param['clean'], $value_param['clean'], ) ); }
Process the parameter of a matched function. Errors if an option is found in the disallow-list. Warns as 'risky' when the option is not found in the safe-list. @since 2.1.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 in lowercase. @param array $parameters Array with information about the parameters. @return void
process_parameters
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/IniSetSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/IniSetSniff.php
MIT
public function register() { return array( \T_DOUBLE_CAST, \T_UNSET_CAST, \T_BINARY_CAST, ); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/TypeCastsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/TypeCastsSniff.php
MIT
public function process_token( $stackPtr ) { $token_code = $this->tokens[ $stackPtr ]['code']; $typecast = str_replace( ' ', '', $this->tokens[ $stackPtr ]['content'] ); $typecast_lc = strtolower( $typecast ); switch ( $token_code ) { case \T_DOUBLE_CAST: if ( '(float)' !== $typecast_lc ) { $fix = $this->phpcsFile->addFixableError( 'Normalized type keywords must be used; expected "(float)" but found "%s"', $stackPtr, 'DoubleRealFound', array( $typecast ) ); if ( true === $fix ) { $this->phpcsFile->fixer->replaceToken( $stackPtr, '(float)' ); } } break; case \T_UNSET_CAST: $this->phpcsFile->addError( 'Using the "(unset)" cast is forbidden as the type cast is removed in PHP 8.0. Use the "unset()" language construct instead.', $stackPtr, 'UnsetFound' ); break; case \T_BINARY_CAST: $this->phpcsFile->addWarning( 'Using binary casting is strongly discouraged. Found: "%s"', $stackPtr, 'BinaryFound', array( $typecast ) ); break; } }
Processes this test, when one of its tokens is encountered. @param int $stackPtr The position of the current token in the stack. @return void
process_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/TypeCastsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/TypeCastsSniff.php
MIT
public function getGroups() { return array( 'serialize' => array( 'type' => 'warning', 'message' => '%s() found. Serialized data has known vulnerability problems with Object Injection. JSON is generally a better approach for serializing data. See https://www.owasp.org/index.php/PHP_Object_Injection', 'functions' => array( 'serialize', 'unserialize', ), ), 'urlencode' => array( 'type' => 'warning', 'message' => '%s() should only be used when dealing with legacy applications rawurlencode() should now be used instead. See https://www.php.net/function.rawurlencode and http://www.faqs.org/rfcs/rfc3986.html', 'functions' => array( 'urlencode', ), ), 'runtime_configuration' => array( 'type' => 'warning', 'message' => '%s() found. Changing configuration values at runtime is strongly discouraged.', 'functions' => array( 'error_reporting', 'ini_restore', 'apache_setenv', 'putenv', 'set_include_path', 'restore_include_path', // This alias was DEPRECATED in PHP 5.3.0, and REMOVED as of PHP 7.0.0. 'magic_quotes_runtime', // Warning This function was DEPRECATED in PHP 5.3.0, and REMOVED as of PHP 7.0.0. 'set_magic_quotes_runtime', // Warning This function was removed from most SAPIs in PHP 5.3.0, and was removed from PHP-FPM in PHP 7.0.0. 'dl', ), ), 'system_calls' => array( 'type' => 'warning', 'message' => '%s() found. PHP system calls are often disabled by server admins.', 'functions' => array( 'exec', 'passthru', 'proc_open', 'shell_exec', 'system', 'popen', ), ), 'obfuscation' => array( 'type' => 'warning', 'message' => '%s() can be used to obfuscate code which is strongly discouraged. Please verify that the function is used for benign reasons.', 'functions' => array( 'base64_decode', 'base64_encode', 'convert_uudecode', 'convert_uuencode', 'str_rot13', ), ), ); }
Groups of functions to discourage. Example: groups => array( 'lambda' => array( 'type' => 'error' | 'warning', 'message' => 'Use anonymous functions instead please!', 'functions' => array( 'file_get_contents', 'create_function' ), ) ) @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/DiscouragedPHPFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/DiscouragedPHPFunctionsSniff.php
MIT
public function getGroups() { return array( 'error_log' => array( 'type' => 'warning', 'message' => '%s() found. Debug code should not normally be used in production.', 'functions' => array( 'error_log', 'var_dump', 'var_export', 'print_r', 'trigger_error', 'set_error_handler', 'debug_backtrace', 'debug_print_backtrace', 'wp_debug_backtrace_summary', ), ), 'prevent_path_disclosure' => array( 'type' => 'warning', 'message' => '%s() can lead to full path disclosure.', 'functions' => array( 'error_reporting', 'phpinfo', ), ), ); }
Groups of functions to restrict. Example: groups => array( 'lambda' => array( 'type' => 'error' | 'warning', 'message' => 'Use anonymous functions instead please!', 'functions' => array( 'file_get_contents', 'create_function' ), ) ) @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/DevelopmentFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/DevelopmentFunctionsSniff.php
MIT
public function getGroups() { return array( 'ereg' => array( 'type' => 'error', 'message' => '%s() has been deprecated since PHP 5.3 and removed in PHP 7.0, please use preg_match() instead.', 'functions' => array( 'ereg', 'eregi', 'sql_regcase', ), ), 'ereg_replace' => array( 'type' => 'error', 'message' => '%s() has been deprecated since PHP 5.3 and removed in PHP 7.0, please use preg_replace() instead.', 'functions' => array( 'ereg_replace', 'eregi_replace', ), ), 'split' => array( 'type' => 'error', 'message' => '%s() has been deprecated since PHP 5.3 and removed in PHP 7.0, please use explode(), str_split() or preg_split() instead.', 'functions' => array( 'split', 'spliti', ), ), ); }
Groups of functions to restrict. Example: groups => array( 'lambda' => array( 'type' => 'error' | 'warning', 'message' => 'Use anonymous functions instead please!', 'functions' => array( 'file_get_contents', 'create_function' ), ) ) @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/POSIXFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/POSIXFunctionsSniff.php
MIT
public function register() { $starters = Tokens::$booleanOperators; $starters += Tokens::$assignmentTokens; $starters[ \T_CASE ] = \T_CASE; $starters[ \T_RETURN ] = \T_RETURN; $starters[ \T_INLINE_THEN ] = \T_INLINE_THEN; $starters[ \T_INLINE_ELSE ] = \T_INLINE_ELSE; $starters[ \T_SEMICOLON ] = \T_SEMICOLON; $starters[ \T_OPEN_PARENTHESIS ] = \T_OPEN_PARENTHESIS; $this->condition_start_tokens = $starters; return array( \T_IS_EQUAL, \T_IS_NOT_EQUAL, \T_IS_IDENTICAL, \T_IS_NOT_IDENTICAL, ); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/YodaConditionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/YodaConditionsSniff.php
MIT
public function process_token( $stackPtr ) { $start = $this->phpcsFile->findPrevious( $this->condition_start_tokens, $stackPtr, null, false, null, true ); $needs_yoda = false; // Note: going backwards! for ( $i = $stackPtr; $i > $start; $i-- ) { // Ignore whitespace. if ( isset( Tokens::$emptyTokens[ $this->tokens[ $i ]['code'] ] ) ) { continue; } // If this is a variable or array assignment, we've seen all we need to see. if ( \T_VARIABLE === $this->tokens[ $i ]['code'] || \T_CLOSE_SQUARE_BRACKET === $this->tokens[ $i ]['code'] ) { $needs_yoda = true; break; } // If this is a function call or something, we are OK. if ( \T_CLOSE_PARENTHESIS === $this->tokens[ $i ]['code'] ) { return; } } if ( ! $needs_yoda ) { return; } // Check if this is a var to var comparison, e.g.: if ( $var1 == $var2 ). $next_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); if ( isset( Tokens::$castTokens[ $this->tokens[ $next_non_empty ]['code'] ] ) ) { $next_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $next_non_empty + 1 ), null, true ); } if ( isset( Collections::ooHierarchyKeywords()[ $this->tokens[ $next_non_empty ]['code'] ] ) === true ) { $next_non_empty = $this->phpcsFile->findNext( ( Tokens::$emptyTokens + array( \T_DOUBLE_COLON => \T_DOUBLE_COLON ) ), ( $next_non_empty + 1 ), null, true ); } if ( \T_VARIABLE === $this->tokens[ $next_non_empty ]['code'] ) { return; } $this->phpcsFile->addError( 'Use Yoda Condition checks, you must.', $stackPtr, 'NotYoda' ); }
Processes this test, when one of its tokens is encountered. @param int $stackPtr The position of the current token in the stack. @return void
process_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/YodaConditionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/YodaConditionsSniff.php
MIT
public function register() { $this->empty_tokens = Tokens::$emptyTokens; $this->empty_tokens[ \T_NS_SEPARATOR ] = \T_NS_SEPARATOR; $this->empty_tokens[ \T_BITWISE_AND ] = \T_BITWISE_AND; return array( \T_ASPERAND, ); }
Returns an array of tokens this test wants to listen for. @since 1.1.0 @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/NoSilencedErrorsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/NoSilencedErrorsSniff.php
MIT
public function process_token( $stackPtr ) { // Handle the user-defined custom function list. $this->customAllowedFunctionsList = RulesetPropertyHelper::merge_custom_array( $this->customAllowedFunctionsList, array(), false ); $this->customAllowedFunctionsList = array_map( 'strtolower', $this->customAllowedFunctionsList ); /* * Check if the error silencing is done for one of the allowed functions. * * @internal The function call name determination is done even when there is no allow list active * to allow the metrics to be more informative. */ $next_non_empty = $this->phpcsFile->findNext( $this->empty_tokens, ( $stackPtr + 1 ), null, true, null, true ); if ( false !== $next_non_empty && \T_STRING === $this->tokens[ $next_non_empty ]['code'] ) { $has_parenthesis = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $next_non_empty + 1 ), null, true, null, true ); if ( false !== $has_parenthesis && \T_OPEN_PARENTHESIS === $this->tokens[ $has_parenthesis ]['code'] ) { $function_name = strtolower( $this->tokens[ $next_non_empty ]['content'] ); if ( ( true === $this->usePHPFunctionsList && isset( $this->allowedFunctionsList[ $function_name ] ) === true ) || ( ! empty( $this->customAllowedFunctionsList ) && in_array( $function_name, $this->customAllowedFunctionsList, true ) === true ) ) { $this->phpcsFile->recordMetric( $stackPtr, 'Error silencing', 'silencing allowed function call: ' . $function_name ); return; } } } $this->context_length = (int) $this->context_length; $context_length = $this->context_length; if ( $this->context_length <= 0 ) { $context_length = 2; } // Prepare the "Found" string to display. $end_of_statement = BCFile::findEndOfStatement( $this->phpcsFile, $stackPtr, \T_COMMA ); if ( ( $end_of_statement - $stackPtr ) < $context_length ) { $context_length = ( $end_of_statement - $stackPtr ); } $found = GetTokensAsString::compact( $this->phpcsFile, $stackPtr, ( $stackPtr + $context_length - 1 ), true ) . '...'; $error_msg = 'Silencing errors is strongly discouraged. Use proper error checking instead.'; $data = array(); if ( $this->context_length > 0 ) { $error_msg .= ' Found: %s'; $data[] = $found; } $this->phpcsFile->addWarning( $error_msg, $stackPtr, 'Discouraged', $data ); if ( isset( $function_name ) ) { $this->phpcsFile->recordMetric( $stackPtr, 'Error silencing', '@' . $function_name ); } else { $this->phpcsFile->recordMetric( $stackPtr, 'Error silencing', $found ); } }
Processes this test, when one of its tokens is encountered. @since 1.1.0 @param int $stackPtr The position of the current token in the stack.
process_token
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/PHP/NoSilencedErrorsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/PHP/NoSilencedErrorsSniff.php
MIT
public function __construct(private string $resourceDir) { }
Create a new Coverage Processor for the specified directory @throws void
__construct
php
browscap/browscap
src/Browscap/Coverage/Processor.php
https://github.com/browscap/browscap/blob/master/src/Browscap/Coverage/Processor.php
MIT
public function delete($name) { unset($this->_data[$name]); $this->_needSave = true; }
Delete an item from the session @param $name
delete
php
gotzmann/comet
src/Session.php
https://github.com/gotzmann/comet/blob/master/src/Session.php
MIT
public function pull($name, $default = null) { $value = $this->get($name, $default); $this->delete($name); return $value; }
Retrieve and delete an item from the session @param $name @param null $default @return mixed|null
pull
php
gotzmann/comet
src/Session.php
https://github.com/gotzmann/comet/blob/master/src/Session.php
MIT
public function all() { return $this->_data; }
Retrieve all the data in the session @return array
all
php
gotzmann/comet
src/Session.php
https://github.com/gotzmann/comet/blob/master/src/Session.php
MIT
public function flush() { $this->_needSave = true; $this->_data = array(); }
Remove all data from the session @return void
flush
php
gotzmann/comet
src/Session.php
https://github.com/gotzmann/comet/blob/master/src/Session.php
MIT
public function has($name) { return isset($this->_data[$name]); }
Determining If An Item Exists In The Session @param $name @return bool
has
php
gotzmann/comet
src/Session.php
https://github.com/gotzmann/comet/blob/master/src/Session.php
MIT
public function exists($name) { return \array_key_exists($name, $this->_data); }
To determine if an item is present in the session, even if its value is null @param $name @return bool
exists
php
gotzmann/comet
src/Session.php
https://github.com/gotzmann/comet/blob/master/src/Session.php
MIT
public function __construct($stream, array $options = []) { if (!is_resource($stream)) { throw new \InvalidArgumentException('Stream must be a resource'); } if (isset($options['size'])) { $this->size = $options['size']; } $this->customMetadata = $options['metadata'] ?? []; $this->stream = $stream; $meta = stream_get_meta_data($this->stream); $this->seekable = $meta['seekable']; $this->readable = (bool)preg_match(self::READABLE_MODES, $meta['mode']); $this->writable = (bool)preg_match(self::WRITABLE_MODES, $meta['mode']); $this->uri = $this->getMetadata('uri'); }
This constructor accepts an associative array of options. - size: (int) If a read stream would otherwise have an indeterminate size, but the size is known due to foreknowledge, then you can provide that size, in bytes. - metadata: (array) Any additional metadata to return when the metadata of the stream is accessed. @param resource $stream Stream resource to wrap. @param array{size?: int, metadata?: array} $options Associative array of options. @throws \InvalidArgumentException if the stream is not a stream resource
__construct
php
gotzmann/comet
src/Stream.php
https://github.com/gotzmann/comet/blob/master/src/Stream.php
MIT
public function __destruct() { $this->close(); }
Closes the stream when the destructed
__destruct
php
gotzmann/comet
src/Stream.php
https://github.com/gotzmann/comet/blob/master/src/Stream.php
MIT
private static function createUploadedFileFromSpec(array $value) { if (is_array($value['tmp_name'])) { return self::normalizeNestedFileSpec($value); } return new UploadedFile( $value['tmp_name'], (int) $value['size'], (int) $value['error'], $value['name'], $value['type'] ); }
Create and return an UploadedFile instance from a $_FILES specification. If the specification represents an array of values, this method will delegate to normalizeNestedFileSpec() and return that return value. @param array $value $_FILES struct @return array|UploadedFileInterface
createUploadedFileFromSpec
php
gotzmann/comet
src/Request.php
https://github.com/gotzmann/comet/blob/master/src/Request.php
MIT
public static function fromGlobals() { throw new InvalidArgumentException('Do not use fromGlobals() method for Comet\Request objects!'); }
We should not allow creating requests from GLOBALS with Workerman-based framework @throws InvalidArgumentException
fromGlobals
php
gotzmann/comet
src/Request.php
https://github.com/gotzmann/comet/blob/master/src/Request.php
MIT
public function getConfig(string $key = "") { if (!$key) { return self::$config; } else if (array_key_exists($key, self::$config)) { return self::$config[$key]; } else { return null; } }
Return config param value or the config at whole @param string $key
getConfig
php
gotzmann/comet
src/Comet.php
https://github.com/gotzmann/comet/blob/master/src/Comet.php
MIT
public function init (callable $init) { self::$init = $init; }
Set up worker initialization code if needed @param callable $init
init
php
gotzmann/comet
src/Comet.php
https://github.com/gotzmann/comet/blob/master/src/Comet.php
MIT
public function addJob(int $interval, callable $job, array $params = [], callable|null $init = null, string $name = '', int $workers = 1) { self::$jobs[] = [ 'interval' => $interval, 'job' => $job, 'params' => $params, 'init' => $init, 'name' => $name, 'workers' => $workers, ]; }
Add periodic $job executed every $interval of seconds @param int $interval @param callable $job @param array $params @param callable $init @param int $workers @param string $name
addJob
php
gotzmann/comet
src/Comet.php
https://github.com/gotzmann/comet/blob/master/src/Comet.php
MIT
public function serveStatic(string $dir, array $extensions = []) { self::$serveStatic = true; // If dir specified as UNIX absolute path, or contains Windows disk name, thats enough // In other case we should concatenate full path of two parts if ($dir[0] == '/' || strpos($dir, ':')) { self::$staticDir = $dir; } else { self::$staticDir = self::$rootDir . '/' . $dir; } self::$staticExtensions = $extensions; }
Set folder to serve as root for static files @param string $dir @param array|null $extensions
serveStatic
php
gotzmann/comet
src/Comet.php
https://github.com/gotzmann/comet/blob/master/src/Comet.php
MIT