_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q255000 | AbstractFunctionRestrictionsSniff.setup_groups | test | protected function setup_groups( $key ) {
// Prepare the function group regular expressions only once.
$this->groups = $this->getGroups();
if ( empty( $this->groups ) && empty( self::$unittest_groups ) ) {
return false;
}
// Allow for adding extra unit tests.
if ( ! empty( self::$unittest_groups ) ) {
$this->groups = array_merge( $this->groups, self::$unittest_groups );
}
$all_items = array();
foreach ( $this->groups as $groupName => $group ) {
if ( empty( $group[ $key ] ) ) {
unset( $this->groups[ $groupName ] );
} else {
$items = array_map( array( $this, 'prepare_name_for_regex' ), $group[ $key ] );
$all_items[] = $items;
$items = implode( '|', $items );
$this->groups[ $groupName ]['regex'] = sprintf( $this->regex_pattern, $items );
}
}
if ( empty( $this->groups ) ) {
return false;
}
// Create one "super-regex" to allow for initial filtering.
$all_items = \call_user_func_array( 'array_merge', $all_items );
$all_items = implode( '|', array_unique( $all_items ) );
$this->prelim_check_regex = sprintf( $this->regex_pattern, $all_items );
return true;
} | php | {
"resource": ""
} |
q255001 | AbstractFunctionRestrictionsSniff.is_targetted_token | test | public function is_targetted_token( $stackPtr ) {
// Exclude function definitions, class methods, and namespaced calls.
if ( \T_STRING === $this->tokens[ $stackPtr ]['code'] ) {
if ( $this->is_class_object_call( $stackPtr ) === true ) {
return false;
}
if ( $this->is_token_namespaced( $stackPtr ) === true ) {
return false;
}
$prev = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true );
if ( false !== $prev ) {
// Skip sniffing if calling a same-named method, or on function definitions.
$skipped = array(
\T_FUNCTION => \T_FUNCTION,
\T_CLASS => \T_CLASS,
\T_AS => \T_AS, // Use declaration alias.
);
if ( isset( $skipped[ $this->tokens[ $prev ]['code'] ] ) ) {
return false;
}
}
return true;
}
return false;
} | php | {
"resource": ""
} |
q255002 | AbstractFunctionRestrictionsSniff.check_for_matches | test | public function check_for_matches( $stackPtr ) {
$token_content = strtolower( $this->tokens[ $stackPtr ]['content'] );
$skip_to = array();
foreach ( $this->groups as $groupName => $group ) {
if ( isset( $this->excluded_groups[ $groupName ] ) ) {
continue;
}
if ( isset( $group['whitelist'][ $token_content ] ) ) {
continue;
}
if ( preg_match( $group['regex'], $token_content ) === 1 ) {
$skip_to[] = $this->process_matched_token( $stackPtr, $groupName, $token_content );
}
}
if ( empty( $skip_to ) || min( $skip_to ) === 0 ) {
return;
}
return min( $skip_to );
} | php | {
"resource": ""
} |
q255003 | PrefixAllGlobalsSniff.process_variable_variable | test | protected function process_variable_variable( $stackPtr ) {
static $indicators = array(
\T_OPEN_CURLY_BRACKET => true,
\T_VARIABLE => true,
);
// Is this a variable variable ?
// Not concerned with nested ones as those will be recognized on their own token.
$next_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true );
if ( false === $next_non_empty || ! isset( $indicators[ $this->tokens[ $next_non_empty ]['code'] ] ) ) {
return;
}
if ( \T_OPEN_CURLY_BRACKET === $this->tokens[ $next_non_empty ]['code']
&& isset( $this->tokens[ $next_non_empty ]['bracket_closer'] )
) {
// Skip over the variable part.
$next_non_empty = $this->tokens[ $next_non_empty ]['bracket_closer'];
}
$maybe_assignment = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $next_non_empty + 1 ), null, true, null, true );
while ( false !== $maybe_assignment
&& \T_OPEN_SQUARE_BRACKET === $this->tokens[ $maybe_assignment ]['code']
&& isset( $this->tokens[ $maybe_assignment ]['bracket_closer'] )
) {
$maybe_assignment = $this->phpcsFile->findNext(
Tokens::$emptyTokens,
( $this->tokens[ $maybe_assignment ]['bracket_closer'] + 1 ),
null,
true,
null,
true
);
}
if ( false === $maybe_assignment ) {
return;
}
if ( ! isset( Tokens::$assignmentTokens[ $this->tokens[ $maybe_assignment ]['code'] ] ) ) {
// Not an assignment.
return;
}
$error = self::ERROR_MSG;
/*
* Local variable variables in a function do not need to be prefixed.
* But a variable variable could evaluate to the name of an imported global
* variable.
* Not concerned with imported variable variables (global.. ) as that has been
* forbidden since PHP 7.0. Presuming cross-version code and if not, that
* is for the PHPCompatibility standard to detect.
*/
if ( $this->phpcsFile->hasCondition( $stackPtr, array( \T_FUNCTION, \T_CLOSURE ) ) === true ) {
$condition = $this->phpcsFile->getCondition( $stackPtr, \T_FUNCTION );
if ( false === $condition ) {
$condition = $this->phpcsFile->getCondition( $stackPtr, \T_CLOSURE );
}
$has_global = $this->phpcsFile->findPrevious( \T_GLOBAL, ( $stackPtr - 1 ), $this->tokens[ $condition ]['scope_opener'] );
if ( false === $has_global ) {
// No variable import happening.
return;
}
$error = 'Variable variable which could potentially override an imported global variable detected. ' . $error;
}
$variable_name = $this->phpcsFile->getTokensAsString( $stackPtr, ( ( $next_non_empty - $stackPtr ) + 1 ) );
// Still here ? In that case, the variable name should be prefixed.
$recorded = $this->phpcsFile->addWarning(
$error,
$stackPtr,
'NonPrefixedVariableFound',
array(
'Global variables defined',
$variable_name,
)
);
if ( true === $recorded ) {
$this->record_potential_prefix_metric( $stackPtr, $variable_name );
}
// Skip over the variable part of the variable.
return ( $next_non_empty + 1 );
} | php | {
"resource": ""
} |
q255004 | PrefixAllGlobalsSniff.variable_prefixed_or_whitelisted | test | private function variable_prefixed_or_whitelisted( $stackPtr, $name ) {
// Ignore superglobals and WP global variables.
if ( isset( $this->superglobals[ $name ] ) || isset( $this->wp_globals[ $name ] ) ) {
return true;
}
return $this->is_prefixed( $stackPtr, $name );
} | php | {
"resource": ""
} |
q255005 | PrefixAllGlobalsSniff.validate_prefixes | test | private function validate_prefixes() {
if ( $this->previous_prefixes === $this->prefixes ) {
return;
}
// Set the cache *before* validation so as to not break the above compare.
$this->previous_prefixes = $this->prefixes;
// Validate the passed prefix(es).
$prefixes = array();
$ns_prefixes = array();
foreach ( $this->prefixes as $key => $prefix ) {
$prefixLC = strtolower( $prefix );
if ( isset( $this->prefix_blacklist[ $prefixLC ] ) ) {
$this->phpcsFile->addError(
'The "%s" prefix is not allowed.',
0,
'ForbiddenPrefixPassed',
array( $prefix )
);
continue;
}
// Validate the prefix against characters allowed for function, class, constant names etc.
if ( preg_match( '`^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff\\\\]*$`', $prefix ) !== 1 ) {
$this->phpcsFile->addWarning(
'The "%s" prefix is not a valid namespace/function/class/variable/constant prefix in PHP.',
0,
'InvalidPrefixPassed',
array( $prefix )
);
}
// Lowercase the prefix to allow for direct compare.
$prefixes[ $key ] = $prefixLC;
/*
* Replace non-word characters in the prefix with a regex snippet, but only if the
* string doesn't already contain namespace separators.
*/
$is_regex = false;
if ( strpos( $prefix, '\\' ) === false && preg_match( '`[_\W]`', $prefix ) > 0 ) {
$prefix = preg_replace( '`([_\W])`', '[\\\\\\\\$1]', $prefixLC );
$is_regex = true;
}
$ns_prefixes[ $prefixLC ] = array(
'prefix' => $prefix,
'is_regex' => $is_regex,
);
}
// Set the validated prefixes caches.
$this->validated_prefixes = $prefixes;
$this->validated_namespace_prefixes = $ns_prefixes;
} | php | {
"resource": ""
} |
q255006 | PrefixAllGlobalsSniff.record_potential_prefix_metric | test | private function record_potential_prefix_metric( $stackPtr, $construct_name ) {
if ( preg_match( '`^([A-Z]*[a-z0-9]*+)`', ltrim( $construct_name, '\$_' ), $matches ) > 0
&& isset( $matches[1] ) && '' !== $matches[1]
) {
$this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: potential prefixes - start of non-prefixed construct', strtolower( $matches[1] ) );
}
} | php | {
"resource": ""
} |
q255007 | AbstractArrayAssignmentRestrictionsSniff.setup_groups | test | protected function setup_groups() {
$this->groups_cache = $this->getGroups();
if ( empty( $this->groups_cache ) && empty( self::$groups ) ) {
return false;
}
// Allow for adding extra unit tests.
if ( ! empty( self::$groups ) ) {
$this->groups_cache = array_merge( $this->groups_cache, self::$groups );
}
return true;
} | php | {
"resource": ""
} |
q255008 | MultipleStatementAlignmentSniff.validate_align_multiline_items | test | 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';
} | php | {
"resource": ""
} |
q255009 | AlternativeFunctionsSniff.is_local_data_stream | test | protected function is_local_data_stream( $raw_param_value ) {
$raw_stripped = $this->strip_quotes( $raw_param_value );
if ( isset( $this->allowed_local_streams[ $raw_stripped ] )
|| isset( $this->allowed_local_stream_constants[ $raw_param_value ] )
) {
return true;
}
foreach ( $this->allowed_local_stream_partials as $partial ) {
if ( strpos( $raw_stripped, $partial ) === 0 ) {
return true;
}
}
return false;
} | php | {
"resource": ""
} |
q255010 | ValidVariableNameSniff.processVariableInString | test | protected function processVariableInString( File $phpcs_file, $stack_ptr ) {
$tokens = $phpcs_file->getTokens();
if ( preg_match_all( '|[^\\\]\${?([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)|', $tokens[ $stack_ptr ]['content'], $matches ) > 0 ) {
// Merge any custom variables with the defaults.
$this->mergeWhiteList();
foreach ( $matches[1] as $var_name ) {
// If it's a php reserved var, then its ok.
if ( isset( $this->phpReservedVars[ $var_name ] ) ) {
continue;
}
// Likewise if it is a mixed-case var used by WordPress core.
if ( isset( $this->wordpress_mixed_case_vars[ $var_name ] ) ) {
return;
}
if ( false === self::isSnakeCase( $var_name ) ) {
$error = 'Variable "$%s" is not in valid snake_case format, try "$%s"';
$data = array(
$var_name,
Sniff::get_snake_case_name_suggestion( $var_name ),
);
$phpcs_file->addError( $error, $stack_ptr, 'InterpolatedVariableNotSnakeCase', $data );
}
}
}
} | php | {
"resource": ""
} |
q255011 | ValidVariableNameSniff.mergeWhiteList | test | protected function mergeWhiteList() {
if ( $this->customPropertiesWhitelist !== $this->addedCustomProperties['properties'] ) {
// Fix property potentially passed as comma-delimited string.
$customProperties = Sniff::merge_custom_array( $this->customPropertiesWhitelist, array(), false );
$this->whitelisted_mixed_case_member_var_names = Sniff::merge_custom_array(
$customProperties,
$this->whitelisted_mixed_case_member_var_names
);
$this->addedCustomProperties['properties'] = $this->customPropertiesWhitelist;
}
} | php | {
"resource": ""
} |
q255012 | ArrayIndentationSniff.ignore_token | test | 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 ( \T_CONSTANT_ENCAPSED_STRING === $token_code
|| \T_DOUBLE_QUOTED_STRING === $token_code
) {
// 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;
} | php | {
"resource": ""
} |
q255013 | ArrayIndentationSniff.get_indentation_size | test | 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 );
} | php | {
"resource": ""
} |
q255014 | ArrayIndentationSniff.get_indentation_string | test | protected function get_indentation_string( $nr ) {
if ( 0 >= $nr ) {
return '';
}
// Space-based indentation.
if ( false === $this->tabIndent ) {
return str_repeat( ' ', $nr );
}
// Tab-based indentation.
$num_tabs = (int) floor( $nr / $this->tab_width );
$remaining = ( $nr % $this->tab_width );
$tab_indent = str_repeat( "\t", $num_tabs );
$tab_indent .= str_repeat( ' ', $remaining );
return $tab_indent;
} | php | {
"resource": ""
} |
q255015 | ArrayIndentationSniff.add_array_alignment_error | test | 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 );
}
} | php | {
"resource": ""
} |
q255016 | ArrayIndentationSniff.fix_alignment_error | test | 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 );
}
} | php | {
"resource": ""
} |
q255017 | EnqueuedResourceParametersSniff.is_falsy | test | 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;
}
$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;" ) );
} | php | {
"resource": ""
} |
q255018 | I18nSniff.compare_single_and_plural_arguments | test | protected function compare_single_and_plural_arguments( $stack_ptr, $single_context, $plural_context ) {
$single_content = $single_context['tokens'][0]['content'];
$plural_content = $plural_context['tokens'][0]['content'];
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';
$single_index = $single_context['tokens'][0]['token_index'];
$this->phpcsFile->addError( $error_string, $single_index, 'MissingSingularPlaceholder' );
}
// Reordering is fine, but mismatched placeholders is probably wrong.
sort( $single_placeholders );
sort( $plural_placeholders );
if ( $single_placeholders !== $plural_placeholders ) {
$this->phpcsFile->addWarning( 'Mismatched placeholders is probably an error', $stack_ptr, 'MismatchedPlaceholders' );
}
} | php | {
"resource": ""
} |
q255019 | I18nSniff.check_text | test | protected function check_text( $context ) {
$stack_ptr = $context['stack_ptr'];
$arg_name = $context['arg_name'];
$content = $context['tokens'][0]['content'];
$is_error = empty( $context['warning'] );
// 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 ) {
$code = $this->string_to_errorcode( 'MixedOrderedPlaceholders' . ucfirst( $arg_name ) );
$this->phpcsFile->addError(
'Multiple placeholders should be ordered. Mix of ordered and non-ordered placeholders found. Found: %s.',
$stack_ptr,
$code,
array( implode( ', ', $all_matches[0] ) )
);
} elseif ( $unordered_matches_count >= 2 ) {
$code = $this->string_to_errorcode( 'UnorderedPlaceholders' . ucfirst( $arg_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 a regex.
$replace_regexes[ $i ] = '`\Q' . $unordered_matches[ $i ] . '\E`';
// Note: the initial \\ is a literal \, the four \ in the replacement translate to 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->addFixableMessage(
'Multiple placeholders should be ordered. Expected \'%s\', but got %s.',
$stack_ptr,
$is_error,
$code,
array( implode( ', ', $suggestions ), implode( ', ', $unordered_matches ) )
);
if ( true === $fix ) {
$fixed_str = preg_replace( $replace_regexes, $replacements, $content, 1 );
$this->phpcsFile->fixer->replaceToken( $stack_ptr, $fixed_str );
}
}
/*
* NoEmptyStrings.
*
* Strip placeholders and surrounding quotes.
*/
$non_placeholder_content = trim( $this->strip_quotes( $content ) );
$non_placeholder_content = preg_replace( self::SPRINTF_PLACEHOLDER_REGEX, '', $non_placeholder_content );
if ( '' === $non_placeholder_content ) {
$this->phpcsFile->addError( 'Strings should have translatable content', $stack_ptr, 'NoEmptyStrings' );
}
} | php | {
"resource": ""
} |
q255020 | AbstractClassRestrictionsSniff.is_targetted_token | test | public function is_targetted_token( $stackPtr ) {
$token = $this->tokens[ $stackPtr ];
$classname = '';
if ( \in_array( $token['code'], array( \T_NEW, \T_EXTENDS, \T_IMPLEMENTS ), true ) ) {
if ( \T_NEW === $token['code'] ) {
$nameEnd = ( $this->phpcsFile->findNext( array( \T_OPEN_PARENTHESIS, \T_WHITESPACE, \T_SEMICOLON, \T_OBJECT_OPERATOR ), ( $stackPtr + 2 ) ) - 1 );
} else {
$nameEnd = ( $this->phpcsFile->findNext( array( \T_CLOSE_CURLY_BRACKET, \T_WHITESPACE ), ( $stackPtr + 2 ) ) - 1 );
}
$length = ( $nameEnd - ( $stackPtr + 1 ) );
$classname = $this->phpcsFile->getTokensAsString( ( $stackPtr + 2 ), $length );
if ( \T_NS_SEPARATOR !== $this->tokens[ ( $stackPtr + 2 ) ]['code'] ) {
$classname = $this->get_namespaced_classname( $classname, ( $stackPtr - 1 ) );
}
}
if ( \T_DOUBLE_COLON === $token['code'] ) {
$nameEnd = $this->phpcsFile->findPrevious( \T_STRING, ( $stackPtr - 1 ) );
$nameStart = ( $this->phpcsFile->findPrevious( array( \T_STRING, \T_NS_SEPARATOR, \T_NAMESPACE ), ( $nameEnd - 1 ), null, true, null, true ) + 1 );
$length = ( $nameEnd - ( $nameStart - 1 ) );
$classname = $this->phpcsFile->getTokensAsString( $nameStart, $length );
if ( \T_NS_SEPARATOR !== $this->tokens[ $nameStart ]['code'] ) {
$classname = $this->get_namespaced_classname( $classname, ( $nameStart - 1 ) );
}
}
// Stop if we couldn't determine a classname.
if ( empty( $classname ) ) {
return false;
}
// Nothing to do if 'parent', 'self' or 'static'.
if ( \in_array( $classname, array( 'parent', 'self', 'static' ), true ) ) {
return false;
}
$this->classname = $classname;
return true;
} | php | {
"resource": ""
} |
q255021 | AbstractClassRestrictionsSniff.check_for_matches | test | public function check_for_matches( $stackPtr ) {
$skip_to = array();
foreach ( $this->groups as $groupName => $group ) {
if ( isset( $this->excluded_groups[ $groupName ] ) ) {
continue;
}
if ( preg_match( $group['regex'], $this->classname ) === 1 ) {
$skip_to[] = $this->process_matched_token( $stackPtr, $groupName, $this->classname );
}
}
if ( empty( $skip_to ) || min( $skip_to ) === 0 ) {
return;
}
return min( $skip_to );
} | php | {
"resource": ""
} |
q255022 | AbstractClassRestrictionsSniff.get_namespaced_classname | test | protected function get_namespaced_classname( $classname, $search_from ) {
// Don't do anything if this is already a fully qualified classname.
if ( empty( $classname ) || '\\' === $classname[0] ) {
return $classname;
}
// Remove the namespace keyword if used.
if ( 0 === strpos( $classname, 'namespace\\' ) ) {
$classname = substr( $classname, 10 );
}
$namespace_keyword = $this->phpcsFile->findPrevious( \T_NAMESPACE, $search_from );
if ( false === $namespace_keyword ) {
// No namespace keyword found at all, so global namespace.
$classname = '\\' . $classname;
} else {
$namespace = $this->determine_namespace( $search_from );
if ( ! empty( $namespace ) ) {
$classname = '\\' . $namespace . '\\' . $classname;
} else {
// No actual namespace found, so global namespace.
$classname = '\\' . $classname;
}
}
return $classname;
} | php | {
"resource": ""
} |
q255023 | AssignmentInConditionSniff.register | test | 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_IF,
\T_ELSEIF,
\T_FOR,
\T_SWITCH,
\T_CASE,
\T_WHILE,
\T_INLINE_THEN,
);
} | php | {
"resource": ""
} |
q255024 | Job.execute | test | public function execute($queue)
{
$serializer = new Serializer();
$closure = $serializer->unserialize($this->serialized);
return $closure();
} | php | {
"resource": ""
} |
q255025 | Queue.reserve | test | protected function reserve($timeout)
{
$response = $this->getClient()->receiveMessage([
'QueueUrl' => $this->url,
'AttributeNames' => ['ApproximateReceiveCount'],
'MessageAttributeNames' => ['TTR'],
'MaxNumberOfMessages' => 1,
'VisibilityTimeout' => $this->ttr,
'WaitTimeSeconds' => $timeout,
]);
if (!$response['Messages']) {
return null;
}
$payload = reset($response['Messages']);
$ttr = (int) $payload['MessageAttributes']['TTR']['StringValue'];
if ($ttr != $this->ttr) {
$this->getClient()->changeMessageVisibility([
'QueueUrl' => $this->url,
'ReceiptHandle' => $payload['ReceiptHandle'],
'VisibilityTimeout' => $ttr,
]);
}
return $payload;
} | php | {
"resource": ""
} |
q255026 | Queue.close | test | protected function close()
{
if (!$this->context) {
return;
}
$this->context->close();
$this->context = null;
$this->setupBrokerDone = false;
} | php | {
"resource": ""
} |
q255027 | Generator.validateNamespace | test | public function validateNamespace($attribute)
{
$value = $this->$attribute;
$value = ltrim($value, '\\');
$path = Yii::getAlias('@' . str_replace('\\', '/', $value), false);
if ($path === false) {
$this->addError($attribute, 'Namespace must be associated with an existing directory.');
}
} | php | {
"resource": ""
} |
q255028 | Queue.push | test | public function push($job)
{
$event = new PushEvent([
'job' => $job,
'ttr' => $this->pushTtr ?: (
$job instanceof RetryableJobInterface
? $job->getTtr()
: $this->ttr
),
'delay' => $this->pushDelay ?: 0,
'priority' => $this->pushPriority,
]);
$this->pushTtr = null;
$this->pushDelay = null;
$this->pushPriority = null;
$this->trigger(self::EVENT_BEFORE_PUSH, $event);
if ($event->handled) {
return null;
}
if ($this->strictJobType && !($event->job instanceof JobInterface)) {
throw new InvalidArgumentException('Job must be instance of JobInterface.');
}
if (!is_numeric($event->ttr)) {
throw new InvalidArgumentException('Job TTR must be integer.');
}
$event->ttr = (int) $event->ttr;
if ($event->ttr <= 0) {
throw new InvalidArgumentException('Job TTR must be greater that zero.');
}
if (!is_numeric($event->delay)) {
throw new InvalidArgumentException('Job delay must be integer.');
}
$event->delay = (int) $event->delay;
if ($event->delay < 0) {
throw new InvalidArgumentException('Job delay must be positive.');
}
$message = $this->serializer->serialize($event->job);
$event->id = $this->pushMessage($message, $event->ttr, $event->delay, $event->priority);
$this->trigger(self::EVENT_AFTER_PUSH, $event);
return $event->id;
} | php | {
"resource": ""
} |
q255029 | Command.actionListen | test | public function actionListen($timeout = 3)
{
if (!is_numeric($timeout)) {
throw new Exception('Timeout must be numeric.');
}
if ($timeout < 1) {
throw new Exception('Timeout must be greater than zero.');
}
return $this->queue->run(true, $timeout);
} | php | {
"resource": ""
} |
q255030 | Command.actionExec | test | public function actionExec($id, $ttr, $attempt, $pid)
{
if ($this->queue->execute($id, file_get_contents('php://stdin'), $ttr, $attempt, $pid ?: null)) {
return self::EXEC_DONE;
}
return self::EXEC_RETRY;
} | php | {
"resource": ""
} |
q255031 | Command.handleMessage | test | protected function handleMessage($id, $message, $ttr, $attempt)
{
// Child process command: php yii queue/exec "id" "ttr" "attempt" "pid"
$cmd = [
$this->phpBinary,
$_SERVER['SCRIPT_FILENAME'],
$this->uniqueId . '/exec',
$id,
$ttr,
$attempt,
$this->queue->getWorkerPid() ?: 0,
];
foreach ($this->getPassedOptions() as $name) {
if (in_array($name, $this->options('exec'), true)) {
$cmd[] = '--' . $name . '=' . $this->$name;
}
}
if (!in_array('color', $this->getPassedOptions(), true)) {
$cmd[] = '--color=' . $this->isColorEnabled();
}
$process = new Process($cmd, null, null, $message, $ttr);
try {
$result = $process->run(function ($type, $buffer) {
if ($type === Process::ERR) {
$this->stderr($buffer);
} else {
$this->stdout($buffer);
}
});
if (!in_array($result, [self::EXEC_DONE, self::EXEC_RETRY])) {
throw new ProcessFailedException($process);
}
return $result === self::EXEC_DONE;
} catch (ProcessRuntimeException $error) {
list($job) = $this->queue->unserializeMessage($message);
return $this->queue->handleError(new ExecEvent([
'id' => $id,
'job' => $job,
'ttr' => $ttr,
'attempt' => $attempt,
'error' => $error,
]));
}
} | php | {
"resource": ""
} |
q255032 | Queue.run | test | public function run()
{
while (($payload = array_shift($this->payloads)) !== null) {
list($ttr, $message) = $payload;
$this->startedId = $this->finishedId + 1;
$this->handleMessage($this->startedId, $message, $ttr, 1);
$this->finishedId = $this->startedId;
$this->startedId = 0;
}
} | php | {
"resource": ""
} |
q255033 | Queue.reserve | test | protected function reserve()
{
return $this->db->useMaster(function () {
if (!$this->mutex->acquire(__CLASS__ . $this->channel, $this->mutexTimeout)) {
throw new Exception('Has not waited the lock.');
}
try {
$this->moveExpired();
// Reserve one message
$payload = (new Query())
->from($this->tableName)
->andWhere(['channel' => $this->channel, 'reserved_at' => null])
->andWhere('[[pushed_at]] <= :time - [[delay]]', [':time' => time()])
->orderBy(['priority' => SORT_ASC, 'id' => SORT_ASC])
->limit(1)
->one($this->db);
if (is_array($payload)) {
$payload['reserved_at'] = time();
$payload['attempt'] = (int) $payload['attempt'] + 1;
$this->db->createCommand()->update($this->tableName, [
'reserved_at' => $payload['reserved_at'],
'attempt' => $payload['attempt'],
], [
'id' => $payload['id'],
])->execute();
// pgsql
if (is_resource($payload['job'])) {
$payload['job'] = stream_get_contents($payload['job']);
}
}
} finally {
$this->mutex->release(__CLASS__ . $this->channel);
}
return $payload;
});
} | php | {
"resource": ""
} |
q255034 | Queue.moveExpired | test | private function moveExpired()
{
if ($this->reserveTime !== time()) {
$this->reserveTime = time();
$this->db->createCommand()->update(
$this->tableName,
['reserved_at' => null],
'[[reserved_at]] < :time - [[ttr]] and [[done_at]] is null',
[':time' => $this->reserveTime]
)->execute();
}
} | php | {
"resource": ""
} |
q255035 | Behavior.beforePush | test | public function beforePush(PushEvent $event)
{
if ($event->job instanceof \Closure) {
$serializer = new Serializer();
$serialized = $serializer->serialize($event->job);
$event->job = new Job();
$event->job->serialized = $serialized;
}
} | php | {
"resource": ""
} |
q255036 | Queue.delete | test | protected function delete($id)
{
$this->redis->zrem("$this->channel.reserved", $id);
$this->redis->hdel("$this->channel.attempts", $id);
$this->redis->hdel("$this->channel.messages", $id);
} | php | {
"resource": ""
} |
q255037 | Queue.runWorker | test | protected function runWorker(callable $handler)
{
$this->_workerPid = getmypid();
/** @var LoopInterface $loop */
$loop = Yii::createObject($this->loopConfig, [$this]);
$event = new WorkerEvent(['loop' => $loop]);
$this->trigger(self::EVENT_WORKER_START, $event);
if ($event->exitCode !== null) {
return $event->exitCode;
}
$exitCode = null;
try {
call_user_func($handler, function () use ($loop, $event) {
$this->trigger(self::EVENT_WORKER_LOOP, $event);
return $event->exitCode === null && $loop->canContinue();
});
} finally {
$this->trigger(self::EVENT_WORKER_STOP, $event);
$this->_workerPid = null;
}
return $event->exitCode;
} | php | {
"resource": ""
} |
q255038 | Queue.handle | test | public function handle($id, $message, $ttr, $attempt)
{
return $this->handleMessage($id, $message, $ttr, $attempt);
} | php | {
"resource": ""
} |
q255039 | SignalLoop.init | test | public function init()
{
parent::init();
if (extension_loaded('pcntl')) {
foreach ($this->exitSignals as $signal) {
pcntl_signal($signal, function () {
self::$exit = true;
});
}
foreach ($this->suspendSignals as $signal) {
pcntl_signal($signal, function () {
self::$pause = true;
});
}
foreach ($this->resumeSignals as $signal) {
pcntl_signal($signal, function () {
self::$pause = false;
});
}
}
} | php | {
"resource": ""
} |
q255040 | SignalLoop.canContinue | test | public function canContinue()
{
if (extension_loaded('pcntl')) {
pcntl_signal_dispatch();
// Wait for resume signal until loop is suspended
while (self::$pause && !self::$exit) {
usleep(10000);
pcntl_signal_dispatch();
}
}
return !self::$exit;
} | php | {
"resource": ""
} |
q255041 | Queue.reserve | test | protected function reserve()
{
$id = null;
$ttr = null;
$attempt = null;
$this->touchIndex(function (&$data) use (&$id, &$ttr, &$attempt) {
if (!empty($data['reserved'])) {
foreach ($data['reserved'] as $key => $payload) {
if ($payload[1] + $payload[3] < time()) {
list($id, $ttr, $attempt, $time) = $payload;
$data['reserved'][$key][2] = ++$attempt;
$data['reserved'][$key][3] = time();
return;
}
}
}
if (!empty($data['delayed']) && $data['delayed'][0][2] <= time()) {
list($id, $ttr, $time) = array_shift($data['delayed']);
} elseif (!empty($data['waiting'])) {
list($id, $ttr) = array_shift($data['waiting']);
}
if ($id) {
$attempt = 1;
$data['reserved']["job$id"] = [$id, $ttr, $attempt, time()];
}
});
if ($id) {
return [$id, file_get_contents("$this->path/job$id.data"), $ttr, $attempt];
}
return null;
} | php | {
"resource": ""
} |
q255042 | Queue.delete | test | protected function delete($payload)
{
$id = $payload[0];
$this->touchIndex(function (&$data) use ($id) {
foreach ($data['reserved'] as $key => $payload) {
if ($payload[0] === $id) {
unset($data['reserved'][$key]);
break;
}
}
});
unlink("$this->path/job$id.data");
} | php | {
"resource": ""
} |
q255043 | Reader.parse | test | public function parse(): array
{
$previousEntityState = libxml_disable_entity_loader(true);
$previousSetting = libxml_use_internal_errors(true);
try {
while (self::ELEMENT !== $this->nodeType) {
if (!$this->read()) {
$errors = libxml_get_errors();
libxml_clear_errors();
if ($errors) {
throw new LibXMLException($errors);
}
}
}
$result = $this->parseCurrentElement();
// last line of defense in case errors did occur above
$errors = libxml_get_errors();
libxml_clear_errors();
if ($errors) {
throw new LibXMLException($errors);
}
} finally {
libxml_use_internal_errors($previousSetting);
libxml_disable_entity_loader($previousEntityState);
}
return $result;
} | php | {
"resource": ""
} |
q255044 | Reader.parseGetElements | test | public function parseGetElements(array $elementMap = null): array
{
$result = $this->parseInnerTree($elementMap);
if (!is_array($result)) {
return [];
}
return $result;
} | php | {
"resource": ""
} |
q255045 | Reader.parseInnerTree | test | public function parseInnerTree(array $elementMap = null)
{
$text = null;
$elements = [];
if (self::ELEMENT === $this->nodeType && $this->isEmptyElement) {
// Easy!
$this->next();
return null;
}
if (!is_null($elementMap)) {
$this->pushContext();
$this->elementMap = $elementMap;
}
try {
if (!$this->read()) {
$errors = libxml_get_errors();
libxml_clear_errors();
if ($errors) {
throw new LibXMLException($errors);
}
throw new ParseException('This should never happen (famous last words)');
}
while (true) {
if (!$this->isValid()) {
$errors = libxml_get_errors();
if ($errors) {
libxml_clear_errors();
throw new LibXMLException($errors);
}
}
switch ($this->nodeType) {
case self::ELEMENT:
$elements[] = $this->parseCurrentElement();
break;
case self::TEXT:
case self::CDATA:
$text .= $this->value;
$this->read();
break;
case self::END_ELEMENT:
// Ensuring we are moving the cursor after the end element.
$this->read();
break 2;
case self::NONE:
throw new ParseException('We hit the end of the document prematurely. This likely means that some parser "eats" too many elements. Do not attempt to continue parsing.');
default:
// Advance to the next element
$this->read();
break;
}
}
} finally {
if (!is_null($elementMap)) {
$this->popContext();
}
}
return $elements ? $elements : $text;
} | php | {
"resource": ""
} |
q255046 | Reader.readText | test | public function readText(): string
{
$result = '';
$previousDepth = $this->depth;
while ($this->read() && $this->depth != $previousDepth) {
if (in_array($this->nodeType, [XMLReader::TEXT, XMLReader::CDATA, XMLReader::WHITESPACE])) {
$result .= $this->value;
}
}
return $result;
} | php | {
"resource": ""
} |
q255047 | Reader.parseCurrentElement | test | public function parseCurrentElement(): array
{
$name = $this->getClark();
$attributes = [];
if ($this->hasAttributes) {
$attributes = $this->parseAttributes();
}
$value = call_user_func(
$this->getDeserializerForElementName((string) $name),
$this
);
return [
'name' => $name,
'value' => $value,
'attributes' => $attributes,
];
} | php | {
"resource": ""
} |
q255048 | Reader.parseAttributes | test | public function parseAttributes(): array
{
$attributes = [];
while ($this->moveToNextAttribute()) {
if ($this->namespaceURI) {
// Ignoring 'xmlns', it doesn't make any sense.
if ('http://www.w3.org/2000/xmlns/' === $this->namespaceURI) {
continue;
}
$name = $this->getClark();
$attributes[$name] = $this->value;
} else {
$attributes[$this->localName] = $this->value;
}
}
$this->moveToElement();
return $attributes;
} | php | {
"resource": ""
} |
q255049 | Reader.getDeserializerForElementName | test | public function getDeserializerForElementName(string $name): callable
{
if (!array_key_exists($name, $this->elementMap)) {
if ('{}' == substr($name, 0, 2) && array_key_exists(substr($name, 2), $this->elementMap)) {
$name = substr($name, 2);
} else {
return ['Sabre\\Xml\\Element\\Base', 'xmlDeserialize'];
}
}
$deserializer = $this->elementMap[$name];
if (is_subclass_of($deserializer, 'Sabre\\Xml\\XmlDeserializable')) {
return [$deserializer, 'xmlDeserialize'];
}
if (is_callable($deserializer)) {
return $deserializer;
}
$type = gettype($deserializer);
if ('string' === $type) {
$type .= ' ('.$deserializer.')';
} elseif ('object' === $type) {
$type .= ' ('.get_class($deserializer).')';
}
throw new \LogicException('Could not use this type as a deserializer: '.$type.' for element: '.$name);
} | php | {
"resource": ""
} |
q255050 | ContextStackTrait.pushContext | test | public function pushContext()
{
$this->contextStack[] = [
$this->elementMap,
$this->contextUri,
$this->namespaceMap,
$this->classMap,
];
} | php | {
"resource": ""
} |
q255051 | ContextStackTrait.popContext | test | public function popContext()
{
list(
$this->elementMap,
$this->contextUri,
$this->namespaceMap,
$this->classMap
) = array_pop($this->contextStack);
} | php | {
"resource": ""
} |
q255052 | Service.getWriter | test | public function getWriter(): Writer
{
$w = new Writer();
$w->namespaceMap = $this->namespaceMap;
$w->classMap = $this->classMap;
return $w;
} | php | {
"resource": ""
} |
q255053 | Service.parse | test | public function parse($input, string $contextUri = null, string &$rootElementName = null)
{
if (is_resource($input)) {
// Unfortunately the XMLReader doesn't support streams. When it
// does, we can optimize this.
$input = (string) stream_get_contents($input);
}
$r = $this->getReader();
$r->contextUri = $contextUri;
$r->XML($input, null, $this->options);
$result = $r->parse();
$rootElementName = $result['name'];
return $result['value'];
} | php | {
"resource": ""
} |
q255054 | Service.expect | test | public function expect($rootElementName, $input, string $contextUri = null)
{
if (is_resource($input)) {
// Unfortunately the XMLReader doesn't support streams. When it
// does, we can optimize this.
$input = (string) stream_get_contents($input);
}
$r = $this->getReader();
$r->contextUri = $contextUri;
$r->XML($input, null, $this->options);
$rootElementName = (array) $rootElementName;
foreach ($rootElementName as &$rEl) {
if ('{' !== $rEl[0]) {
$rEl = '{}'.$rEl;
}
}
$result = $r->parse();
if (!in_array($result['name'], $rootElementName, true)) {
throw new ParseException('Expected '.implode(' or ', $rootElementName).' but received '.$result['name'].' as the root element');
}
return $result['value'];
} | php | {
"resource": ""
} |
q255055 | Service.write | test | public function write(string $rootElementName, $value, string $contextUri = null)
{
$w = $this->getWriter();
$w->openMemory();
$w->contextUri = $contextUri;
$w->setIndent(true);
$w->startDocument();
$w->writeElement($rootElementName, $value);
return $w->outputMemory();
} | php | {
"resource": ""
} |
q255056 | Service.mapValueObject | test | public function mapValueObject(string $elementName, string $className)
{
list($namespace) = self::parseClarkNotation($elementName);
$this->elementMap[$elementName] = function (Reader $reader) use ($className, $namespace) {
return \Sabre\Xml\Deserializer\valueObject($reader, $className, $namespace);
};
$this->classMap[$className] = function (Writer $writer, $valueObject) use ($namespace) {
return \Sabre\Xml\Serializer\valueObject($writer, $valueObject, $namespace);
};
$this->valueObjectMap[$className] = $elementName;
} | php | {
"resource": ""
} |
q255057 | Service.writeValueObject | test | public function writeValueObject($object, string $contextUri = null)
{
if (!isset($this->valueObjectMap[get_class($object)])) {
throw new \InvalidArgumentException('"'.get_class($object).'" is not a registered value object class. Register your class with mapValueObject.');
}
return $this->write(
$this->valueObjectMap[get_class($object)],
$object,
$contextUri
);
} | php | {
"resource": ""
} |
q255058 | Service.parseClarkNotation | test | public static function parseClarkNotation(string $str): array
{
static $cache = [];
if (!isset($cache[$str])) {
if (!preg_match('/^{([^}]*)}(.*)$/', $str, $matches)) {
throw new \InvalidArgumentException('\''.$str.'\' is not a valid clark-notation formatted string');
}
$cache[$str] = [
$matches[1],
$matches[2],
];
}
return $cache[$str];
} | php | {
"resource": ""
} |
q255059 | XmlFragment.xmlDeserialize | test | public static function xmlDeserialize(Reader $reader)
{
$result = new self($reader->readInnerXml());
$reader->next();
return $result;
} | php | {
"resource": ""
} |
q255060 | Uri.xmlDeserialize | test | public static function xmlDeserialize(Xml\Reader $reader)
{
return new self(
\Sabre\Uri\resolve(
(string) $reader->contextUri,
$reader->readText()
)
);
} | php | {
"resource": ""
} |
q255061 | Writer.startElement | test | public function startElement($name): bool
{
if ('{' === $name[0]) {
list($namespace, $localName) =
Service::parseClarkNotation($name);
if (array_key_exists($namespace, $this->namespaceMap)) {
$result = $this->startElementNS(
'' === $this->namespaceMap[$namespace] ? null : $this->namespaceMap[$namespace],
$localName,
null
);
} else {
// An empty namespace means it's the global namespace. This is
// allowed, but it mustn't get a prefix.
if ('' === $namespace || null === $namespace) {
$result = $this->startElement($localName);
$this->writeAttribute('xmlns', '');
} else {
if (!isset($this->adhocNamespaces[$namespace])) {
$this->adhocNamespaces[$namespace] = 'x'.(count($this->adhocNamespaces) + 1);
}
$result = $this->startElementNS($this->adhocNamespaces[$namespace], $localName, $namespace);
}
}
} else {
$result = parent::startElement($name);
}
if (!$this->namespacesWritten) {
foreach ($this->namespaceMap as $namespace => $prefix) {
$this->writeAttribute(($prefix ? 'xmlns:'.$prefix : 'xmlns'), $namespace);
}
$this->namespacesWritten = true;
}
return $result;
} | php | {
"resource": ""
} |
q255062 | Writer.writeElement | test | public function writeElement($name, $content = null): bool
{
$this->startElement($name);
if (!is_null($content)) {
$this->write($content);
}
$this->endElement();
return true;
} | php | {
"resource": ""
} |
q255063 | Writer.writeAttributes | test | public function writeAttributes(array $attributes)
{
foreach ($attributes as $name => $value) {
$this->writeAttribute($name, $value);
}
} | php | {
"resource": ""
} |
q255064 | Writer.writeAttribute | test | public function writeAttribute($name, $value): bool
{
if ('{' !== $name[0]) {
return parent::writeAttribute($name, $value);
}
list(
$namespace,
$localName
) = Service::parseClarkNotation($name);
if (array_key_exists($namespace, $this->namespaceMap)) {
// It's an attribute with a namespace we know
return $this->writeAttribute(
$this->namespaceMap[$namespace].':'.$localName,
$value
);
}
// We don't know the namespace, we must add it in-line
if (!isset($this->adhocNamespaces[$namespace])) {
$this->adhocNamespaces[$namespace] = 'x'.(count($this->adhocNamespaces) + 1);
}
return $this->writeAttributeNS(
$this->adhocNamespaces[$namespace],
$localName,
$namespace,
$value
);
} | php | {
"resource": ""
} |
q255065 | RelationFinder.getModelRelations | test | public function getModelRelations(string $model)
{
$class = new ReflectionClass($model);
$traitMethods = Collection::make($class->getTraits())->map(function (ReflectionClass $trait) {
return Collection::make($trait->getMethods(ReflectionMethod::IS_PUBLIC));
})->flatten();
$methods = Collection::make($class->getMethods(ReflectionMethod::IS_PUBLIC))
->merge($traitMethods)
->reject(function (ReflectionMethod $method) use ($model) {
return $method->class !== $model || $method->getNumberOfParameters() > 0;
});
$relations = Collection::make();
$methods->map(function (ReflectionMethod $method) use ($model, &$relations) {
$relations = $relations->merge($this->getRelationshipFromMethodAndModel($method, $model));
});
$relations = $relations->filter();
if ($ignoreRelations = array_get(config('erd-generator.ignore', []),$model))
{
$relations = $relations->diffKeys(array_flip($ignoreRelations));
}
return $relations;
} | php | {
"resource": ""
} |
q255066 | CronCreateCommand.validateJobName | test | protected function validateJobName($name)
{
if (!$name || strlen($name) == 0) {
throw new \InvalidArgumentException('Please set a name.');
}
if ($this->queryJob($name)) {
throw new \InvalidArgumentException('Name already in use.');
}
return $name;
} | php | {
"resource": ""
} |
q255067 | CronCreateCommand.validateCommand | test | protected function validateCommand($command)
{
$parts = explode(' ', $command);
$this->getApplication()->get((string) $parts[0]);
return $command;
} | php | {
"resource": ""
} |
q255068 | Resolver.createJob | test | protected function createJob(CronJob $dbJob)
{
$job = new ShellJob();
$job->setCommand($this->commandBuilder->build($dbJob->getCommand()), $this->rootDir);
$job->setSchedule(new CrontabSchedule($dbJob->getSchedule()));
$job->raw = $dbJob;
return $job;
} | php | {
"resource": ""
} |
q255069 | CurrentTraceContext.createScopeAndRetrieveItsCloser | test | public function createScopeAndRetrieveItsCloser(?TraceContext $currentContext = null): callable
{
$previous = $this->context;
$self = $this;
$this->context = $currentContext;
return function () use ($previous, $self) {
$self->context = $previous;
};
} | php | {
"resource": ""
} |
q255070 | Span.finish | test | public function finish(?int $finishTimestamp = null): void
{
if ($this->finished) {
return;
}
if ($this->timestamp !== null && $finishTimestamp !== null) {
$this->duration = $finishTimestamp - $this->timestamp;
}
$this->finished = true;
} | php | {
"resource": ""
} |
q255071 | Tracer.getCurrentSpan | test | public function getCurrentSpan(): ?Span
{
$currentContext = $this->currentTraceContext->getContext();
return $currentContext === null ? null : $this->toSpan($currentContext);
} | php | {
"resource": ""
} |
q255072 | Tracer.toSpan | test | private function toSpan(TraceContext $context): Span
{
if (!$this->isNoop && $context->isSampled()) {
return RealSpan::create($context, $this->recorder);
}
return NoopSpan::create($context);
} | php | {
"resource": ""
} |
q255073 | RealSpan.start | test | public function start(?int $timestamp = null): void
{
if ($timestamp === null) {
$timestamp = now();
} else {
if (!isValid($timestamp)) {
throw new InvalidArgumentException(
sprintf('Invalid timestamp. Expected int, got %s', $timestamp)
);
}
}
$this->recorder->start($this->traceContext, $timestamp);
} | php | {
"resource": ""
} |
q255074 | RealSpan.setName | test | public function setName(string $name): void
{
$this->recorder->setName($this->traceContext, $name);
} | php | {
"resource": ""
} |
q255075 | RealSpan.annotate | test | public function annotate(string $value, ?int $timestamp = null): void
{
if (!isValid($timestamp)) {
throw new InvalidArgumentException(
sprintf('Valid timestamp represented microtime expected, got \'%s\'', $timestamp)
);
}
$this->recorder->annotate($this->traceContext, $timestamp, $value);
} | php | {
"resource": ""
} |
q255076 | RealSpan.setRemoteEndpoint | test | public function setRemoteEndpoint(Endpoint $remoteEndpoint): void
{
$this->recorder->setRemoteEndpoint($this->traceContext, $remoteEndpoint);
} | php | {
"resource": ""
} |
q255077 | Guard.generateNewToken | test | public function generateNewToken(ServerRequestInterface $request)
{
$pair = $this->generateToken();
$request = $this->attachRequestAttributes($request, $pair);
return $request;
} | php | {
"resource": ""
} |
q255078 | Guard.getFromStorage | test | protected function getFromStorage($name)
{
return isset($this->storage[$name]) ? $this->storage[$name] : false;
} | php | {
"resource": ""
} |
q255079 | Guard.getLastKeyPair | test | protected function getLastKeyPair()
{
// Use count, since empty ArrayAccess objects can still return false for `empty`
if (count($this->storage) < 1) {
return null;
}
foreach ($this->storage as $name => $value) {
continue;
}
$keyPair = [
$this->prefix . '_name' => $name,
$this->prefix . '_value' => $value
];
return $keyPair;
} | php | {
"resource": ""
} |
q255080 | Guard.enforceStorageLimit | test | protected function enforceStorageLimit()
{
if ($this->storageLimit < 1) {
return;
}
// $storage must be an array or implement Countable and Traversable
if (!is_array($this->storage)
&& !($this->storage instanceof Countable && $this->storage instanceof Traversable)
) {
return;
}
if (is_array($this->storage)) {
while (count($this->storage) > $this->storageLimit) {
array_shift($this->storage);
}
} else {
// array_shift() doesn't work for ArrayAccess, so we need an iterator in order to use rewind()
// and key(), so that we can then unset
$iterator = $this->storage;
if ($this->storage instanceof \IteratorAggregate) {
$iterator = $this->storage->getIterator();
}
while (count($this->storage) > $this->storageLimit) {
$iterator->rewind();
unset($this->storage[$iterator->key()]);
}
}
} | php | {
"resource": ""
} |
q255081 | Sanitizer.create | test | public static function create(array $config): SanitizerInterface
{
$builder = new SanitizerBuilder();
$builder->registerExtension(new BasicExtension());
$builder->registerExtension(new ListExtension());
$builder->registerExtension(new ImageExtension());
$builder->registerExtension(new CodeExtension());
$builder->registerExtension(new TableExtension());
$builder->registerExtension(new IframeExtension());
$builder->registerExtension(new DetailsExtension());
$builder->registerExtension(new ExtraExtension());
return $builder->build($config);
} | php | {
"resource": ""
} |
q255082 | TagVisitorTrait.setAttributes | test | private function setAttributes(\DOMNode $domNode, TagNodeInterface $node, array $allowedAttributes = [])
{
if (!\count($domNode->attributes)) {
return;
}
/** @var \DOMAttr $attribute */
foreach ($domNode->attributes as $attribute) {
$name = strtolower($attribute->name);
if (\in_array($name, $allowedAttributes, true)) {
$node->setAttribute($name, $attribute->value);
}
}
} | php | {
"resource": ""
} |
q255083 | TagVisitorTrait.getAttribute | test | private function getAttribute(\DOMNode $domNode, string $name): ?string
{
if (!\count($domNode->attributes)) {
return null;
}
/** @var \DOMAttr $attribute */
foreach ($domNode->attributes as $attribute) {
if ($attribute->name === $name) {
return $attribute->value;
}
}
return null;
} | php | {
"resource": ""
} |
q255084 | DefaultConfigPass.processDefaultEntity | test | private function processDefaultEntity(array $backendConfig)
{
$entityNames = \array_keys($backendConfig['entities']);
$firstEntityName = $entityNames[0] ?? null;
$backendConfig['default_entity_name'] = $firstEntityName;
return $backendConfig;
} | php | {
"resource": ""
} |
q255085 | DefaultConfigPass.processDefaultMenuItem | test | private function processDefaultMenuItem(array $backendConfig)
{
$defaultMenuItem = $this->findDefaultMenuItem($backendConfig['design']['menu']);
if ('empty' === $defaultMenuItem['type']) {
throw new \RuntimeException(\sprintf('The "menu" configuration sets "%s" as the default item, which is not possible because its type is "empty" and it cannot redirect to a valid URL.', $defaultMenuItem['label']));
}
$backendConfig['default_menu_item'] = $defaultMenuItem;
return $backendConfig;
} | php | {
"resource": ""
} |
q255086 | FormTypeHelper.getTypeName | test | public static function getTypeName($typeFqcn)
{
// needed to avoid collisions between immutable and non-immutable date types,
// which are mapped to the same Symfony Form type classes
$filteredNameToClassMap = \array_filter(self::$nameToClassMap, function ($typeName) {
return !\in_array($typeName, ['datetime_immutable', 'date_immutable', 'time_immutable']);
}, ARRAY_FILTER_USE_KEY);
$classToNameMap = \array_flip($filteredNameToClassMap);
return $classToNameMap[$typeFqcn] ?? $typeFqcn;
} | php | {
"resource": ""
} |
q255087 | PropertyConfigPass.getFormTypeOptionsOfProperty | test | private function getFormTypeOptionsOfProperty(array $mergedConfig, array $guessedConfig, array $userDefinedConfig)
{
$resolvedFormOptions = $mergedConfig['type_options'];
// if the user has defined a 'type', the type options
// must be reset so they don't get mixed with the form components guess.
// Only the 'required' and user defined option are kept
if (
isset($userDefinedConfig['type'], $guessedConfig['fieldType'])
&& $userDefinedConfig['type'] !== $guessedConfig['fieldType']
) {
$resolvedFormOptions = \array_merge(
\array_intersect_key($resolvedFormOptions, ['required' => null]),
isset($userDefinedConfig['type_options']) ? $userDefinedConfig['type_options'] : []
);
}
// if the user has defined the "type" or "type_options"
// AND the "type" is the same as the default one
elseif (
(
isset($userDefinedConfig['type'])
&& isset($guessedConfig['fieldType'])
&& $userDefinedConfig['type'] === $guessedConfig['fieldType']
) || (
!isset($userDefinedConfig['type']) && isset($userDefinedConfig['type_options'])
)
) {
$resolvedFormOptions = \array_merge(
$resolvedFormOptions,
isset($userDefinedConfig['type_options']) ? $userDefinedConfig['type_options'] : []
);
}
return $resolvedFormOptions;
} | php | {
"resource": ""
} |
q255088 | AdminControllerTrait.initialize | test | protected function initialize(Request $request)
{
$this->dispatch(EasyAdminEvents::PRE_INITIALIZE);
$this->config = $this->get('easyadmin.config.manager')->getBackendConfig();
if (0 === \count($this->config['entities'])) {
throw new NoEntitiesConfiguredException();
}
// this condition happens when accessing the backend homepage and before
// redirecting to the default page set as the homepage
if (null === $entityName = $request->query->get('entity')) {
return;
}
if (!\array_key_exists($entityName, $this->config['entities'])) {
throw new UndefinedEntityException(['entity_name' => $entityName]);
}
$this->entity = $this->get('easyadmin.config.manager')->getEntityConfig($entityName);
$action = $request->query->get('action', 'list');
if (!$request->query->has('sortField')) {
$sortField = $this->entity[$action]['sort']['field'] ?? $this->entity['primary_key_field_name'];
$request->query->set('sortField', $sortField);
}
if (!$request->query->has('sortDirection')) {
$sortDirection = $this->entity[$action]['sort']['direction'] ?? 'DESC';
$request->query->set('sortDirection', $sortDirection);
}
$this->em = $this->getDoctrine()->getManagerForClass($this->entity['class']);
$this->request = $request;
$this->dispatch(EasyAdminEvents::POST_INITIALIZE);
} | php | {
"resource": ""
} |
q255089 | AdminControllerTrait.autocompleteAction | test | protected function autocompleteAction()
{
$results = $this->get('easyadmin.autocomplete')->find(
$this->request->query->get('entity'),
$this->request->query->get('query'),
$this->request->query->get('page', 1)
);
return new JsonResponse($results);
} | php | {
"resource": ""
} |
q255090 | AdminControllerTrait.listAction | test | protected function listAction()
{
$this->dispatch(EasyAdminEvents::PRE_LIST);
$fields = $this->entity['list']['fields'];
$paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->entity['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
$this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
$parameters = [
'paginator' => $paginator,
'fields' => $fields,
'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
];
return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
} | php | {
"resource": ""
} |
q255091 | AdminControllerTrait.editAction | test | protected function editAction()
{
$this->dispatch(EasyAdminEvents::PRE_EDIT);
$id = $this->request->query->get('id');
$easyadmin = $this->request->attributes->get('easyadmin');
$entity = $easyadmin['item'];
if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
$newValue = 'true' === \mb_strtolower($this->request->query->get('newValue'));
$fieldsMetadata = $this->entity['list']['fields'];
if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
throw new \RuntimeException(\sprintf('The type of the "%s" property is not "toggle".', $property));
}
$this->updateEntityProperty($entity, $property, $newValue);
// cast to integer instead of string to avoid sending empty responses for 'false'
return new Response((int) $newValue);
}
$fields = $this->entity['edit']['fields'];
$editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
$deleteForm = $this->createDeleteForm($this->entity['name'], $id);
$editForm->handleRequest($this->request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
$this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
$this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
return $this->redirectToReferrer();
}
$this->dispatch(EasyAdminEvents::POST_EDIT);
$parameters = [
'form' => $editForm->createView(),
'entity_fields' => $fields,
'entity' => $entity,
'delete_form' => $deleteForm->createView(),
];
return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
} | php | {
"resource": ""
} |
q255092 | AdminControllerTrait.showAction | test | protected function showAction()
{
$this->dispatch(EasyAdminEvents::PRE_SHOW);
$id = $this->request->query->get('id');
$easyadmin = $this->request->attributes->get('easyadmin');
$entity = $easyadmin['item'];
$fields = $this->entity['show']['fields'];
$deleteForm = $this->createDeleteForm($this->entity['name'], $id);
$this->dispatch(EasyAdminEvents::POST_SHOW, [
'deleteForm' => $deleteForm,
'fields' => $fields,
'entity' => $entity,
]);
$parameters = [
'entity' => $entity,
'fields' => $fields,
'delete_form' => $deleteForm->createView(),
];
return $this->executeDynamicMethod('render<EntityName>Template', ['show', $this->entity['templates']['show'], $parameters]);
} | php | {
"resource": ""
} |
q255093 | AdminControllerTrait.newAction | test | protected function newAction()
{
$this->dispatch(EasyAdminEvents::PRE_NEW);
$entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
$easyadmin = $this->request->attributes->get('easyadmin');
$easyadmin['item'] = $entity;
$this->request->attributes->set('easyadmin', $easyadmin);
$fields = $this->entity['new']['fields'];
$newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
$newForm->handleRequest($this->request);
if ($newForm->isSubmitted() && $newForm->isValid()) {
$this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
$this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
$this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
return $this->redirectToReferrer();
}
$this->dispatch(EasyAdminEvents::POST_NEW, [
'entity_fields' => $fields,
'form' => $newForm,
'entity' => $entity,
]);
$parameters = [
'form' => $newForm->createView(),
'entity_fields' => $fields,
'entity' => $entity,
];
return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
} | php | {
"resource": ""
} |
q255094 | AdminControllerTrait.deleteAction | test | protected function deleteAction()
{
$this->dispatch(EasyAdminEvents::PRE_DELETE);
if ('DELETE' !== $this->request->getMethod()) {
return $this->redirect($this->generateUrl('easyadmin', ['action' => 'list', 'entity' => $this->entity['name']]));
}
$id = $this->request->query->get('id');
$form = $this->createDeleteForm($this->entity['name'], $id);
$form->handleRequest($this->request);
if ($form->isSubmitted() && $form->isValid()) {
$easyadmin = $this->request->attributes->get('easyadmin');
$entity = $easyadmin['item'];
$this->dispatch(EasyAdminEvents::PRE_REMOVE, ['entity' => $entity]);
try {
$this->executeDynamicMethod('remove<EntityName>Entity', [$entity, $form]);
} catch (ForeignKeyConstraintViolationException $e) {
throw new EntityRemoveException(['entity_name' => $this->entity['name'], 'message' => $e->getMessage()]);
}
$this->dispatch(EasyAdminEvents::POST_REMOVE, ['entity' => $entity]);
}
$this->dispatch(EasyAdminEvents::POST_DELETE);
return $this->redirectToReferrer();
} | php | {
"resource": ""
} |
q255095 | AdminControllerTrait.searchAction | test | protected function searchAction()
{
$this->dispatch(EasyAdminEvents::PRE_SEARCH);
$query = \trim($this->request->query->get('query'));
// if the search query is empty, redirect to the 'list' action
if ('' === $query) {
$queryParameters = \array_replace($this->request->query->all(), ['action' => 'list']);
unset($queryParameters['query']);
return $this->redirect($this->get('router')->generate('easyadmin', $queryParameters));
}
$searchableFields = $this->entity['search']['fields'];
$defaultSortField = $this->entity['search']['sort']['field'] ?? null;
$defaultSortDirection = isset($this->entity['search']['sort']['direction']) ? $this->entity['search']['sort']['direction'] : null;
$paginator = $this->findBy(
$this->entity['class'],
$query,
$searchableFields,
$this->request->query->get('page', 1),
$this->entity['list']['max_results'],
$this->request->query->get('sortField', $defaultSortField),
$this->request->query->get('sortDirection', $defaultSortDirection),
$this->entity['search']['dql_filter']
);
$fields = $this->entity['list']['fields'];
$this->dispatch(EasyAdminEvents::POST_SEARCH, [
'fields' => $fields,
'paginator' => $paginator,
]);
$parameters = [
'paginator' => $paginator,
'fields' => $fields,
'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
];
return $this->executeDynamicMethod('render<EntityName>Template', ['search', $this->entity['templates']['list'], $parameters]);
} | php | {
"resource": ""
} |
q255096 | AdminControllerTrait.batchAction | test | protected function batchAction(): RedirectResponse
{
$batchForm = $this->createBatchForm($this->entity['name']);
$batchForm->handleRequest($this->request);
if ($batchForm->isSubmitted() && $batchForm->isValid()) {
$actionName = $batchForm->get('name')->getData();
$actionIds = $batchForm->get('ids')->getData();
$this->executeDynamicMethod($actionName.'<EntityName>BatchAction', [$actionIds, $batchForm]);
}
return $this->redirectToReferrer();
} | php | {
"resource": ""
} |
q255097 | AdminControllerTrait.updateEntityProperty | test | protected function updateEntityProperty($entity, $property, $value)
{
$entityConfig = $this->entity;
if (!$this->get('easyadmin.property_accessor')->isWritable($entity, $property)) {
throw new \RuntimeException(\sprintf('The "%s" property of the "%s" entity is not writable.', $property, $entityConfig['name']));
}
$this->get('easyadmin.property_accessor')->setValue($entity, $property, $value);
$this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity, 'newValue' => $value]);
$this->executeDynamicMethod('update<EntityName>Entity', [$entity]);
$this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity, 'newValue' => $value]);
$this->dispatch(EasyAdminEvents::POST_EDIT);
} | php | {
"resource": ""
} |
q255098 | AdminControllerTrait.findAll | test | protected function findAll($entityClass, $page = 1, $maxPerPage = 15, $sortField = null, $sortDirection = null, $dqlFilter = null)
{
if (null === $sortDirection || !\in_array(\strtoupper($sortDirection), ['ASC', 'DESC'])) {
$sortDirection = 'DESC';
}
$queryBuilder = $this->executeDynamicMethod('create<EntityName>ListQueryBuilder', [$entityClass, $sortDirection, $sortField, $dqlFilter]);
$this->dispatch(EasyAdminEvents::POST_LIST_QUERY_BUILDER, [
'query_builder' => $queryBuilder,
'sort_field' => $sortField,
'sort_direction' => $sortDirection,
]);
return $this->get('easyadmin.paginator')->createOrmPaginator($queryBuilder, $page, $maxPerPage);
} | php | {
"resource": ""
} |
q255099 | AdminControllerTrait.createListQueryBuilder | test | protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{
return $this->get('easyadmin.query_builder')->createListQueryBuilder($this->entity, $sortField, $sortDirection, $dqlFilter);
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.