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 boot() { if ($this->app->runningInConsole()) { $this->publishes([ __DIR__.'/../config/domain-driven-design.php' => config_path('domain-driven-design.php'), ], 'laravel-domain-driven-design'); // Registering package commands. $this->commands($this->registeredCommands()); } // Pick proper Factory class name Factory::guessFactoryNamesUsing(static function (string $modelName) { return 'Database\\Factories\\'.class_basename($modelName).'Factory'; }); }
Bootstrap the application services.
boot
php
thejano/laravel-domain-driven-design
src/LaravelDomainDrivenDesignServiceProvider.php
https://github.com/thejano/laravel-domain-driven-design/blob/master/src/LaravelDomainDrivenDesignServiceProvider.php
MIT
public function register() { $this->mergeConfigFrom( __DIR__.'/../config/domain-driven-design.php', 'domain-driven-design' ); // // Register the main class to use with the facade // $this->app->singleton('laravel-domain-driven-design', function () { // return new LaravelDomainDrivenDesign(); // }); }
Register the application services.
register
php
thejano/laravel-domain-driven-design
src/LaravelDomainDrivenDesignServiceProvider.php
https://github.com/thejano/laravel-domain-driven-design/blob/master/src/LaravelDomainDrivenDesignServiceProvider.php
MIT
protected function generateFormRequests($modelClass, $storeRequestClass, $updateRequestClass) { $storeRequestClass = 'Store'.class_basename($modelClass).'Request'; $this->call('d:make:request', [ 'name' => $storeRequestClass, '--domain' => $this->option('domain'), ]); $updateRequestClass = 'Update'.class_basename($modelClass).'Request'; $this->call('d:make:request', [ 'name' => $updateRequestClass, '--domain' => $this->option('domain'), ]); return [$storeRequestClass, $updateRequestClass]; }
Generate the form requests for the given model and classes. @param string $modelClass @param string $storeRequestClass @param string $updateRequestClass @return array
generateFormRequests
php
thejano/laravel-domain-driven-design
src/Commands/MainCommands/CreateControllerCommand.php
https://github.com/thejano/laravel-domain-driven-design/blob/master/src/Commands/MainCommands/CreateControllerCommand.php
MIT
public function __construct( string $apiKey, float $timeout = Constants::TIMEOUT, string $apiBase = Constants::API_BASE, ?object $mockingUtility = null ) { // Client properties $this->apiKey = $apiKey; $this->timeout = $timeout; $this->apiBase = $apiBase; $this->mockingUtility = $mockingUtility; $this->requestEvent = new RequestHook(); $this->responseEvent = new ResponseHook(); $this->httpClient = new Client(); }
Constructor for an EasyPostClient. @param string $apiKey @param float $timeout @param string $apiBase @param object|null $mockingUtility
__construct
php
EasyPost/easypost-php
lib/EasyPost/EasyPostClient.php
https://github.com/EasyPost/easypost-php/blob/master/lib/EasyPost/EasyPostClient.php
MIT
public function __get(string $serviceName) { $serviceClassMap = [ 'address' => AddressService::class, 'apiKeys' => ApiKeyService::class, 'batch' => BatchService::class, 'betaRate' => BetaRateService::class, 'betaReferralCustomer' => BetaReferralCustomerService::class, 'billing' => BillingService::class, 'carrierAccount' => CarrierAccountService::class, 'carrierMetadata' => CarrierMetadataService::class, 'claim' => ClaimService::class, 'customsInfo' => CustomsInfoService::class, 'customsItem' => CustomsItemService::class, 'endShipper' => EndShipperService::class, 'event' => EventService::class, 'insurance' => InsuranceService::class, 'order' => OrderService::class, 'parcel' => ParcelService::class, 'pickup' => PickupService::class, 'rate' => RateService::class, 'referralCustomer' => ReferralCustomerService::class, 'refund' => RefundService::class, 'report' => ReportService::class, 'scanForm' => ScanFormService::class, 'shipment' => ShipmentService::class, 'smartRate' => SmartRateService::class, 'tracker' => TrackerService::class, 'user' => UserService::class, 'webhook' => WebhookService::class, ]; if (array_key_exists($serviceName, $serviceClassMap)) { return new $serviceClassMap[$serviceName]($this); } else { // TODO: checking for `_parent` is a hack and should be fixed when we revisit the // (de)serialization of objects in this lib. if ($serviceName != '_parent') { throw new EasyPostException( sprintf(Constants::UNDEFINED_PROPERTY_ERROR, 'EasyPostClient', $serviceName) ); } } }
Get a Service when calling a property of an EasyPostClient. @param string $serviceName @return mixed @throws EasyPostException
__get
php
EasyPost/easypost-php
lib/EasyPost/EasyPostClient.php
https://github.com/EasyPost/easypost-php/blob/master/lib/EasyPost/EasyPostClient.php
MIT
public function __construct(mixed $parent = null, mixed $name = null) { $this->_values = []; $this->_immutableValues = ['id']; $this->_parent = $parent; $this->_name = $name; }
Constructor for EasyPost objects. @param mixed $parent @param mixed $name
__construct
php
EasyPost/easypost-php
lib/EasyPost/EasyPostObject.php
https://github.com/EasyPost/easypost-php/blob/master/lib/EasyPost/EasyPostObject.php
MIT
protected function __construct($client) { $this->client = $client; }
Service constructor shared by all child services. @param EasyPostClient $client
__construct
php
EasyPost/easypost-php
lib/EasyPost/Service/BaseService.php
https://github.com/EasyPost/easypost-php/blob/master/lib/EasyPost/Service/BaseService.php
MIT
public function getNextPage(mixed $addresses, ?int $pageSize = null) { return $this->getNextPageResources(self::serviceModelClassName(self::class), $addresses, $pageSize); }
Retrieve the next page of Address collection @param mixed $addresses @param int|null $pageSize @return mixed
getNextPage
php
EasyPost/easypost-php
lib/EasyPost/Service/AddressService.php
https://github.com/EasyPost/easypost-php/blob/master/lib/EasyPost/Service/AddressService.php
MIT
public static function getLowestStatelessRate(array $statelessRates, array $carriers = [], array $services = []) { $lowestStatelessRate = false; $carriersInclude = []; $carriersExclude = []; $servicesInclude = []; $servicesExclude = []; for ($i = 0; $i < count($carriers); $i++) { $carriers[$i] = trim(strtolower($carriers[$i])); if (substr($carriers[$i], 0, 1) == '!') { $carriersExclude[] = substr($carriers[$i], 1); } else { $carriersInclude[] = $carriers[$i]; } } for ($i = 0; $i < count($services); $i++) { $services[$i] = trim(strtolower($services[$i])); if (substr($services[$i], 0, 1) == '!') { $servicesExclude[] = substr($services[$i], 1); } else { $servicesInclude[] = $services[$i]; } } for ($i = 0; $i < count($statelessRates); $i++) { $rateCarrier = strtolower($statelessRates[$i]->carrier); if (!empty($carriersInclude[0]) && !in_array($rateCarrier, $carriersInclude)) { continue; } if (!empty($carriersExclude[0]) && in_array($rateCarrier, $carriersExclude)) { continue; } $rateService = strtolower($statelessRates[$i]->service); if (!empty($servicesInclude[0]) && !in_array($rateService, $servicesInclude)) { continue; } if (!empty($servicesExclude[0]) && in_array($rateService, $servicesExclude)) { continue; } if (!$lowestStatelessRate || floatval($statelessRates[$i]->rate) < floatval($lowestStatelessRate->rate)) { $lowestStatelessRate = clone ($statelessRates[$i]); } } if ($lowestStatelessRate == false) { throw new FilteringException(Constants::NO_RATES_ERROR); } return $lowestStatelessRate; }
Get the lowest stateless rate. To exclude a carrier or service, prepend the string with `!`. @param array<Rate> $statelessRates @param array<string> $carriers @param array<string> $services @return Rate @throws EasyPostException
getLowestStatelessRate
php
EasyPost/easypost-php
lib/EasyPost/Util/Util.php
https://github.com/EasyPost/easypost-php/blob/master/lib/EasyPost/Util/Util.php
MIT
public function addHandler(callable $handler) { $this->eventHandlers[] = $handler; return $this; }
Add an HTTP handler to the list of handlers. @param callable $handler @return EventHook
addHandler
php
EasyPost/easypost-php
lib/EasyPost/Hook/EventHook.php
https://github.com/EasyPost/easypost-php/blob/master/lib/EasyPost/Hook/EventHook.php
MIT
public function removeHandler(callable $handler) { $index = array_search($handler, $this->eventHandlers, true); if ($index !== false) { array_splice($this->eventHandlers, (int)$index, 1); } return $this; }
Remove an HTTP handler from the list of handlers. @param callable $handler @return EventHook
removeHandler
php
EasyPost/easypost-php
lib/EasyPost/Hook/EventHook.php
https://github.com/EasyPost/easypost-php/blob/master/lib/EasyPost/Hook/EventHook.php
MIT
public function __construct(string $message = '') { parent::__construct($message); }
EasyPostException constructor. @param string $message
__construct
php
EasyPost/easypost-php
lib/EasyPost/Exception/General/EasyPostException.php
https://github.com/EasyPost/easypost-php/blob/master/lib/EasyPost/Exception/General/EasyPostException.php
MIT
public function __construct() { parent::__construct(Constants::END_OF_PAGINATION); }
EndOfPaginationException constructor.
__construct
php
EasyPost/easypost-php
lib/EasyPost/Exception/General/EndOfPaginationException.php
https://github.com/EasyPost/easypost-php/blob/master/lib/EasyPost/Exception/General/EndOfPaginationException.php
MIT
public function __construct(array $mockRequests) { $this->mockRequests = $mockRequests; }
Construct a new MockingUtility. @param array<MockRequest> $mockRequests
__construct
php
EasyPost/easypost-php
test/EasyPost/Mocking/MockingUtility.php
https://github.com/EasyPost/easypost-php/blob/master/test/EasyPost/Mocking/MockingUtility.php
MIT
public function register() { // Retrieve the groups only once and don't set up a listener if there are no groups. if ( false === $this->setup_groups() ) { return array(); } return array( \T_DOUBLE_ARROW, \T_CLOSE_SQUARE_BRACKET, \T_CONSTANT_ENCAPSED_STRING, \T_DOUBLE_QUOTED_STRING, ); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractArrayAssignmentRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractArrayAssignmentRestrictionsSniff.php
MIT
public function process_token( $stackPtr ) { $this->excluded_groups = RulesetPropertyHelper::merge_custom_array( $this->exclude ); if ( array_diff_key( $this->groups_cache, $this->excluded_groups ) === array() ) { // All groups have been excluded. // Don't remove the listener as the exclude property can be changed inline. return; } $token = $this->tokens[ $stackPtr ]; if ( \T_CLOSE_SQUARE_BRACKET === $token['code'] ) { $equalPtr = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); if ( \T_EQUAL !== $this->tokens[ $equalPtr ]['code'] && \T_COALESCE_EQUAL !== $this->tokens[ $equalPtr ]['code'] ) { // This is not an assignment. Bow out. return; } } // Instances: Multi-dimensional array. $inst = array(); /* * Covers array assignments: * `$foo = array( 'bar' => 'taz' );` * `$foo['bar'] = $taz;` */ if ( \T_CLOSE_SQUARE_BRACKET === $token['code'] || \T_DOUBLE_ARROW === $token['code'] ) { $operator = $stackPtr; // T_DOUBLE_ARROW. if ( \T_CLOSE_SQUARE_BRACKET === $token['code'] ) { $operator = $equalPtr; } $keyIdx = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true ); if ( isset( Tokens::$stringTokens[ $this->tokens[ $keyIdx ]['code'] ] ) && ! is_numeric( $this->tokens[ $keyIdx ]['content'] ) ) { $key = TextStrings::stripQuotes( $this->tokens[ $keyIdx ]['content'] ); $valStart = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $operator + 1 ), null, true ); $valEnd = BCFile::findEndOfStatement( $this->phpcsFile, $valStart, \T_COLON ); if ( \T_COMMA === $this->tokens[ $valEnd ]['code'] || \T_SEMICOLON === $this->tokens[ $valEnd ]['code'] ) { // FindEndOfStatement includes the comma/semi-colon if that's the end of the statement. // That's not what we want (and inconsistent), so remove it. --$valEnd; } $val = trim( GetTokensAsString::compact( $this->phpcsFile, $valStart, $valEnd, true ) ); $inst[ $key ] = array( 'value' => $val, 'line' => $token['line'], 'keyptr' => $keyIdx, ); } } elseif ( isset( Tokens::$stringTokens[ $token['code'] ] ) ) { /* * Covers assignments via query parameters: `$foo = 'bar=taz&other=thing';`. */ if ( preg_match_all( '#(?:^|&)([a-z_]+)=([^&]*)#i', TextStrings::stripQuotes( $token['content'] ), $matches ) <= 0 ) { return; // No assignments here, nothing to check. } foreach ( $matches[1] as $match_nr => $key ) { $inst[ $key ] = array( 'value' => $matches[2][ $match_nr ], 'line' => $token['line'], 'keyptr' => $stackPtr, ); } } if ( empty( $inst ) ) { return; } foreach ( $this->groups_cache as $groupName => $group ) { if ( isset( $this->excluded_groups[ $groupName ] ) ) { continue; } foreach ( $inst as $key => $assignment ) { if ( ! \in_array( $key, $group['keys'], true ) ) { continue; } $output = \call_user_func( array( $this, 'callback' ), $key, $assignment['value'], $assignment['line'], $group ); if ( ! isset( $output ) || false === $output ) { continue; } elseif ( true === $output ) { $message = $group['message']; } else { $message = $output; } MessageHelper::addMessage( $this->phpcsFile, $message, $assignment['keyptr'], ( 'error' === $group['type'] ), MessageHelper::stringToErrorcode( $groupName . '_' . $key ), array( $key, $assignment['value'] ) ); } } }
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/AbstractArrayAssignmentRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractArrayAssignmentRestrictionsSniff.php
MIT
public function getGroups() { if ( empty( $this->target_functions ) ) { return array(); } return array( $this->group_name => array( 'functions' => array_keys( $this->target_functions ), ), ); }
Groups of functions to restrict. @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractFunctionParameterSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractFunctionParameterSniff.php
MIT
public function process_matched_token( $stackPtr, $group_name, $matched_content ) { $parameters = PassedParameters::getParameters( $this->phpcsFile, $stackPtr ); if ( empty( $parameters ) ) { return $this->process_no_parameters( $stackPtr, $group_name, $matched_content ); } else { return $this->process_parameters( $stackPtr, $group_name, $matched_content, $parameters ); } }
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/AbstractFunctionParameterSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractFunctionParameterSniff.php
MIT
public function is_targetted_token( $stackPtr ) { if ( ! parent::is_targetted_token( $stackPtr ) ) { return false; } $next = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); if ( \T_OPEN_PARENTHESIS !== $this->tokens[ $next ]['code'] ) { // Not a function call (likely a function import). return false; } if ( isset( $this->tokens[ $next ]['parenthesis_closer'] ) === false ) { // Syntax error or live coding: missing closing parenthesis. return false; } // First class callable. $firstNonEmpty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $next + 1 ), null, true ); if ( \T_ELLIPSIS === $this->tokens[ $firstNonEmpty ]['code'] ) { $secondNonEmpty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $firstNonEmpty + 1 ), null, true ); if ( \T_CLOSE_PARENTHESIS === $this->tokens[ $secondNonEmpty ]['code'] ) { return false; } } return true; }
Verify if the current token is a function call. Behaves like the parent method, except that it returns false if there is no opening parenthesis after the function name (likely a function import) or if it is a first class callable. @param int $stackPtr The position of the current token in the stack. @return bool
is_targetted_token
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractFunctionParameterSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractFunctionParameterSniff.php
MIT
public function process_no_parameters( $stackPtr, $group_name, $matched_content ) {}
Process the function if no parameters were found. Defaults to doing nothing. Can be overloaded in child classes to handle functions were parameters are expected, but none found. @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_no_parameters
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractFunctionParameterSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractFunctionParameterSniff.php
MIT
public function process( File $phpcsFile, $stackPtr ) { $this->phpcsFile = $phpcsFile; $this->tokens = $phpcsFile->getTokens(); return $this->process_token( $stackPtr ); }
Set sniff properties and hand off to child class for processing of the token. @since 0.11.0 @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return int|void Integer stack pointer to skip forward or void to continue normal file processing.
process
php
WordPress/WordPress-Coding-Standards
WordPress/Sniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniff.php
MIT
public function register() { // Prepare the function group regular expressions only once. if ( false === $this->setup_groups( 'classes' ) ) { return array(); } return array( \T_DOUBLE_COLON, \T_NEW, \T_EXTENDS, \T_IMPLEMENTS, ); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractClassRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractClassRestrictionsSniff.php
MIT
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_CLOSE_PARENTHESIS, \T_CLOSE_TAG ), ( $stackPtr + 2 ) ) - 1 ); } else { $nameEnd = ( $this->phpcsFile->findNext( array( \T_CLOSE_CURLY_BRACKET, \T_WHITESPACE ), ( $stackPtr + 2 ) ) - 1 ); } if ( isset( $this->tokens[ $stackPtr + 2 ] ) && false !== $nameEnd ) { $classname = GetTokensAsString::noEmpties( $this->phpcsFile, ( $stackPtr + 2 ), $nameEnd ); $classname = $this->get_namespaced_classname( $classname, ( $stackPtr - 1 ) ); } } if ( \T_DOUBLE_COLON === $token['code'] ) { $nameEnd = $this->phpcsFile->findPrevious( Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true ); if ( \T_STRING !== $this->tokens[ $nameEnd ]['code'] ) { // Hierarchy keyword or object stored in variable. return false; } $nameStart = ( $this->phpcsFile->findPrevious( Collections::namespacedNameTokens(), ( $nameEnd - 1 ), null, true ) + 1 ); $classname = GetTokensAsString::noEmpties( $this->phpcsFile, $nameStart, $nameEnd ); $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 one of the hierarchy keywords - 'parent', 'self' or 'static' - is used. if ( \in_array( strtolower( $classname ), array( '\parent', '\self', '\static' ), true ) ) { return false; } $this->classname = $classname; return true; }
Determine if we have a valid classname for the target token. @since 0.11.0 This logic was originally contained in the `process()` method. @param int $stackPtr The position of the current token in the stack. @return bool
is_targetted_token
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractClassRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractClassRestrictionsSniff.php
MIT
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 ); }
Verify if the current token is one of the targeted classes. @since 0.11.0 Split out from the `process()` method. @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.
check_for_matches
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractClassRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractClassRestrictionsSniff.php
MIT
public function process_matched_token( $stackPtr, $group_name, $matched_content ) { parent::process_matched_token( $stackPtr, $group_name, $matched_content ); }
Process a matched token. @since 0.11.0 Split out from the `process()` 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 it original case. @return int|void Integer stack pointer to skip forward or void to continue normal file processing. @phpcs:disable Generic.CodeAnalysis.UselessOverridingMethod.Found
process_matched_token
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractClassRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractClassRestrictionsSniff.php
MIT
protected function prepare_name_for_regex( $classname ) { $classname = trim( $classname, '\\' ); // Make sure all classnames have a \ prefix, but only one. return parent::prepare_name_for_regex( $classname ); }
Prepare the class name for use in a regular expression. The getGroups() method allows for providing class names with a wildcard * to target a group of classes within a namespace. It also allows for providing class names as 'ordinary' names or prefixed with one or more namespaces. This prepare routine takes that into account while still safely escaping the class name for use in a regular expression. @param string $classname Class name, potentially prefixed with namespaces. @return string Regex escaped class name.
prepare_name_for_regex
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractClassRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractClassRestrictionsSniff.php
MIT
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 === stripos( $classname, 'namespace\\' ) ) { $classname = substr( $classname, 10 ); } $namespace = Namespaces::determineNamespace( $this->phpcsFile, $search_from ); if ( '' === $namespace ) { // No namespace keyword found at all, so global namespace. $classname = '\\' . $classname; } else { $classname = '\\' . $namespace . '\\' . $classname; } return $classname; }
See if the classname was found in a namespaced file and if so, add the namespace to the classname. @param string $classname The full classname as found. @param int $search_from The token position to search up from. @return string Classname, potentially prefixed with the namespace.
get_namespaced_classname
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractClassRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractClassRestrictionsSniff.php
MIT
public function register() { // Prepare the function group regular expressions only once. if ( false === $this->setup_groups( 'functions' ) ) { return array(); } return array( \T_STRING, ); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractFunctionRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractFunctionRestrictionsSniff.php
MIT
public function process_token( $stackPtr ) { $this->excluded_groups = RulesetPropertyHelper::merge_custom_array( $this->exclude ); if ( array_diff_key( $this->groups, $this->excluded_groups ) === array() ) { // All groups have been excluded. // Don't remove the listener as the exclude property can be changed inline. return; } // Preliminary check. If the content of the T_STRING is not one of the functions we're // looking for, we can bow out before doing the heavy lifting of checking whether // this is a function call. if ( preg_match( $this->prelim_check_regex, $this->tokens[ $stackPtr ]['content'] ) !== 1 ) { return; } if ( true === $this->is_targetted_token( $stackPtr ) ) { return $this->check_for_matches( $stackPtr ); } }
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/AbstractFunctionRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractFunctionRestrictionsSniff.php
MIT
public function is_targetted_token( $stackPtr ) { // Exclude function definitions, class methods, and namespaced calls. if ( ContextHelper::has_object_operator_before( $this->phpcsFile, $stackPtr ) === true ) { return false; } if ( ContextHelper::is_token_namespaced( $this->phpcsFile, $stackPtr ) === true ) { return false; } if ( Context::inAttribute( $this->phpcsFile, $stackPtr ) ) { // Class instantiation or constant in attribute, not function call. return false; } $search = Tokens::$emptyTokens; $search[ \T_BITWISE_AND ] = \T_BITWISE_AND; $prev = $this->phpcsFile->findPrevious( $search, ( $stackPtr - 1 ), null, true ); // Skip sniffing on function, OO definitions or for function aliases in use statements. $invalid_tokens = Tokens::$ooScopeTokens; $invalid_tokens += array( \T_FUNCTION => \T_FUNCTION, \T_NEW => \T_NEW, \T_AS => \T_AS, // Use declaration alias. ); if ( isset( $invalid_tokens[ $this->tokens[ $prev ]['code'] ] ) ) { return false; } // Check if this could even be a function call. $next = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); if ( false === $next ) { return false; } // Check for `use function ... (as|;)`. if ( ( \T_STRING === $this->tokens[ $prev ]['code'] && 'function' === $this->tokens[ $prev ]['content'] ) && ( \T_AS === $this->tokens[ $next ]['code'] || \T_SEMICOLON === $this->tokens[ $next ]['code'] ) ) { return true; } // If it's not a `use` statement, there should be parenthesis. if ( \T_OPEN_PARENTHESIS !== $this->tokens[ $next ]['code'] ) { return false; } return true; }
Verify if the current token is a function call. @since 0.11.0 Split out from the `process()` method. @param int $stackPtr The position of the current token in the stack. @return bool
is_targetted_token
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractFunctionRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractFunctionRestrictionsSniff.php
MIT
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['allow'][ $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 ); }
Verify if the current token is one of the targeted functions. @since 0.11.0 Split out from the `process()` method. @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.
check_for_matches
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractFunctionRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractFunctionRestrictionsSniff.php
MIT
public function process_matched_token( $stackPtr, $group_name, $matched_content ) { MessageHelper::addMessage( $this->phpcsFile, $this->groups[ $group_name ]['message'], $stackPtr, ( 'error' === $this->groups[ $group_name ]['type'] ), MessageHelper::stringToErrorcode( $group_name . '_' . $matched_content ), array( $matched_content ) ); }
Process a matched token. @since 0.11.0 Split out from the `process()` 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 int|void Integer stack pointer to skip forward or void to continue normal file processing.
process_matched_token
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractFunctionRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractFunctionRestrictionsSniff.php
MIT
protected function prepare_name_for_regex( $function_name ) { $function_name = str_replace( array( '.*', '*' ), '@@', $function_name ); // Replace wildcards with placeholder. $function_name = preg_quote( $function_name, '`' ); $function_name = str_replace( '@@', '.*', $function_name ); // Replace placeholder with regex wildcard. return $function_name; }
Prepare the function name for use in a regular expression. The getGroups() method allows for providing function names with a wildcard * to target a group of functions. This prepare routine takes that into account while still safely escaping the function name for use in a regular expression. @since 0.10.0 @param string $function_name Function name. @return string Regex escaped function name.
prepare_name_for_regex
php
WordPress/WordPress-Coding-Standards
WordPress/AbstractFunctionRestrictionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/AbstractFunctionRestrictionsSniff.php
MIT
public static function get_names() { return self::$wp_globals; }
Retrieve a list with the names of global WP variables. @since 3.0.0 @return array<string, bool> Array with the variables names as keys. The value is irrelevant.
get_names
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/WPGlobalVariablesHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/WPGlobalVariablesHelper.php
MIT
public static function is_wp_global( $name ) { if ( strpos( $name, '$' ) === 0 ) { $name = substr( $name, 1 ); } return isset( self::$wp_globals[ $name ] ); }
Verify if a given variable name is the name of a WP global variable. @since 3.0.0 @param string $name The full variable name with or without leading dollar sign. This allows for passing an array key variable name, such as `'_GET'` retrieved from `$GLOBALS['_GET']`. > Note: when passing an array key, string quotes are expected to have been stripped already. @return bool
is_wp_global
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/WPGlobalVariablesHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/WPGlobalVariablesHelper.php
MIT
public static function is_formatting_function( $functionName ) { return isset( self::$formattingFunctions[ strtolower( $functionName ) ] ); }
Check if a particular function is regarded as a formatting function. @since 3.0.0 @param string $functionName The name of the function to check. @return bool
is_formatting_function
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/FormattingFunctionsHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/FormattingFunctionsHelper.php
MIT
private function normalize_version_number( $version ) { if ( preg_match( '`^\d+\.\d+$`', $version ) ) { $version .= '.0'; } return $version; }
Normalize a version number. Ensures that a version number is comparable via the PHP version_compare() function by making sure it complies with the minimum "PHP-standardized" version number requirements. Presumes the input is a numeric version number string. The behaviour with other input is undefined. @since 3.0.0 @param string $version Version number. @return string
normalize_version_number
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/MinimumWPVersionTrait.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/MinimumWPVersionTrait.php
MIT
public static function get_functions() { return self::$unslashingFunctions; }
Retrieve a list of the unslashing functions. @since 3.0.0 @return array<string, bool>
get_functions
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/UnslashingFunctionsHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/UnslashingFunctionsHelper.php
MIT
public static function is_unslashing_function( $functionName ) { return isset( self::$unslashingFunctions[ strtolower( $functionName ) ] ); }
Check if a particular function is regarded as a unslashing function. @since 3.0.0 @param string $functionName The name of the function to check. @return bool
is_unslashing_function
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/UnslashingFunctionsHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/UnslashingFunctionsHelper.php
MIT
public static function is_in_type_test( File $phpcsFile, $stackPtr ) { /* * Casting the potential integer stack pointer return value to boolean here is fine. * The return can never be `0` as there will always be a PHP open tag before the * function call. */ return (bool) self::is_in_function_call( $phpcsFile, $stackPtr, self::$typeTestFunctions ); }
Check if a token is inside of an is_...() statement. @since 2.1.0 @since 3.0.0 - Moved from the Sniff class to this class. - The method visibility was changed from `protected` to `public static`. - 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. @return bool Whether the token is being type tested.
is_in_type_test
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/ContextHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/ContextHelper.php
MIT
public static function is_in_isset_or_empty( File $phpcsFile, $stackPtr ) { if ( Parentheses::lastOwnerIn( $phpcsFile, $stackPtr, array( \T_ISSET, \T_EMPTY ) ) !== false ) { return true; } $functionPtr = self::is_in_function_call( $phpcsFile, $stackPtr, self::$key_exists_functions ); if ( false !== $functionPtr ) { /* * Both functions being checked have the same parameters. If the function list would * be expanded, this needs to be revisited. */ $array_param = PassedParameters::getParameter( $phpcsFile, $functionPtr, 2, 'array' ); if ( false !== $array_param && ( $stackPtr >= $array_param['start'] && $stackPtr <= $array_param['end'] ) ) { return true; } } return false; }
Check if a token is inside of an isset(), empty() or array_key_exists() statement. @since 0.5.0 @since 2.1.0 Now checks for the token being used as the array parameter in function calls to array_key_exists() and key_exists() as well. @since 3.0.0 - Moved from the Sniff class to this class. - The method visibility was changed from `protected` to `public static`. - 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. @return bool Whether the token is inside an isset() or empty() statement.
is_in_isset_or_empty
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/ContextHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/ContextHelper.php
MIT
public static function get_safe_cast_tokens() { return self::$safe_casts; }
Retrieve a list of the tokens which are regarded as "safe casts". @since 3.0.0 @return array<int|string, true>
get_safe_cast_tokens
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/ContextHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/ContextHelper.php
MIT
public static function is_safe_casted( File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); if ( isset( $tokens[ $stackPtr ] ) === false ) { return false; } $prev = $phpcsFile->findPrevious( Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true ); return isset( self::$safe_casts[ $tokens[ $prev ]['code'] ] ); }
Check if something is being casted to a safe value. @since 0.5.0 @since 3.0.0 - Moved from the Sniff class to this class. - The method visibility was changed from `protected` to `public static`. - 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. @return bool Whether the token being casted.
is_safe_casted
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/ContextHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/ContextHelper.php
MIT
public static function is_in_array_comparison( File $phpcsFile, $stackPtr ) { $function_ptr = self::is_in_function_call( $phpcsFile, $stackPtr, self::$arrayCompareFunctions, true, true ); if ( false === $function_ptr ) { return false; } $tokens = $phpcsFile->getTokens(); $function_name = strtolower( $tokens[ $function_ptr ]['content'] ); if ( true === self::$arrayCompareFunctions[ $function_name ] ) { return true; } $target_param = self::$arrayCompareFunctions[ $function_name ]; $found_param = PassedParameters::getParameter( $phpcsFile, $function_ptr, $target_param['position'], $target_param['name'] ); if ( false !== $found_param ) { return true; } return false; }
Check if a token is inside of an array-value comparison function. @since 2.1.0 @since 3.0.0 - Moved from the Sniff class to this class. - The method visibility was changed from `protected` to `public static`. - 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. @return bool Whether the token is (part of) a parameter to an array-value comparison function.
is_in_array_comparison
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/ContextHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/ContextHelper.php
MIT
public static function is_use_of_global_constant( File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); // Check for the existence of the token. if ( ! isset( $tokens[ $stackPtr ] ) ) { return false; } // Is this one of the tokens this function handles ? if ( \T_STRING !== $tokens[ $stackPtr ]['code'] ) { return false; } $next = $phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); if ( false !== $next && ( \T_OPEN_PARENTHESIS === $tokens[ $next ]['code'] || \T_DOUBLE_COLON === $tokens[ $next ]['code'] ) ) { // Function call or declaration. return false; } // Array of tokens which if found preceding the $stackPtr indicate that a T_STRING is not a global constant. $tokens_to_ignore = array( \T_NAMESPACE => true, \T_USE => true, \T_EXTENDS => true, \T_IMPLEMENTS => true, \T_NEW => true, \T_FUNCTION => true, \T_INSTANCEOF => true, \T_INSTEADOF => true, \T_GOTO => true, ); $tokens_to_ignore += Tokens::$ooScopeTokens; $tokens_to_ignore += Collections::objectOperators(); $tokens_to_ignore += Tokens::$scopeModifiers; $prev = $phpcsFile->findPrevious( Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true ); if ( isset( $tokens_to_ignore[ $tokens[ $prev ]['code'] ] ) ) { // Not the use of a constant. return false; } if ( ContextHelper::is_token_namespaced( $phpcsFile, $stackPtr ) === true ) { // Namespaced constant of the same name. return false; } if ( \T_CONST === $tokens[ $prev ]['code'] && Scopes::isOOConstant( $phpcsFile, $prev ) ) { // Class constant declaration of the same name. return false; } /* * Deal with a number of variations of use statements. */ for ( $i = $stackPtr; $i > 0; $i-- ) { if ( $tokens[ $i ]['line'] !== $tokens[ $stackPtr ]['line'] ) { break; } } $firstOnLine = $phpcsFile->findNext( Tokens::$emptyTokens, ( $i + 1 ), null, true ); if ( false !== $firstOnLine && \T_USE === $tokens[ $firstOnLine ]['code'] ) { $nextOnLine = $phpcsFile->findNext( Tokens::$emptyTokens, ( $firstOnLine + 1 ), null, true ); if ( false !== $nextOnLine ) { if ( \T_STRING === $tokens[ $nextOnLine ]['code'] && 'const' === $tokens[ $nextOnLine ]['content'] ) { $hasNsSep = $phpcsFile->findNext( \T_NS_SEPARATOR, ( $nextOnLine + 1 ), $stackPtr ); if ( false !== $hasNsSep ) { // Namespaced const (group) use statement. return false; } } else { // Not a const use statement. return false; } } } return true; }
Determine whether an arbitrary T_STRING token is the use of a global constant. @since 1.0.0 @since 3.0.0 - Moved from the Sniff class to this class. - The method was changed to be `static`. - The `$phpcsFile` parameter was added. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the function call token. @return bool
is_use_of_global_constant
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/ConstantsHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/ConstantsHelper.php
MIT
public static function is_function_deprecated( File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); if ( isset( $tokens[ $stackPtr ] ) === false ) { return false; } $ignore = Tokens::$methodPrefixes; $ignore[ \T_WHITESPACE ] = \T_WHITESPACE; for ( $comment_end = ( $stackPtr - 1 ); $comment_end >= 0; $comment_end-- ) { if ( isset( $ignore[ $tokens[ $comment_end ]['code'] ] ) === true ) { continue; } if ( \T_ATTRIBUTE_END === $tokens[ $comment_end ]['code'] && isset( $tokens[ $comment_end ]['attribute_opener'] ) === true ) { $comment_end = $tokens[ $comment_end ]['attribute_opener']; continue; } break; } if ( \T_DOC_COMMENT_CLOSE_TAG !== $tokens[ $comment_end ]['code'] ) { // Function doesn't have a doc comment or is using the wrong type of comment. return false; } $comment_start = $tokens[ $comment_end ]['comment_opener']; foreach ( $tokens[ $comment_start ]['comment_tags'] as $tag ) { if ( '@deprecated' === $tokens[ $tag ]['content'] ) { return true; } } return false; }
Check whether a function has been marked as deprecated via a @deprecated tag in the function docblock. @since 2.2.0 @since 3.0.0 Moved from the Sniff class to this class. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of a T_FUNCTION token in the stack. @return bool
is_function_deprecated
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/DeprecationHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/DeprecationHelper.php
MIT
public static function get_functions( $include_deprecated = true ) { $hooks = array_fill_keys( array_keys( self::$hookInvokeFunctions ), true ); if ( false === $include_deprecated ) { unset( $hooks['do_action_deprecated'], $hooks['apply_filters_deprecated'] ); } return $hooks; }
Retrieve a list of the WordPress functions which invoke hooks. @since 3.0.0 @param bool $include_deprecated Whether to include the names of functions which are used to invoke deprecated hooks. Defaults to `true`. @return array<string, bool> Array with the function names as keys. The value is irrelevant.
get_functions
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/WPHookHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/WPHookHelper.php
MIT
public static function get_hook_name_param( $function_name, array $parameters ) { $function_lc = strtolower( $function_name ); if ( isset( self::$hookInvokeFunctions[ $function_lc ] ) === false ) { return false; } return PassedParameters::getParameterFromStack( $parameters, self::$hookInvokeFunctions[ $function_lc ]['position'], self::$hookInvokeFunctions[ $function_lc ]['name'] ); }
Retrieve the parameter information for the hook name parameter from a stack of parameters passed to one of the WP hook functions. @since 3.0.0 @param string $function_name The name of the WP hook function which the parameters were passed to. @param array $parameters The output of a previous call to PassedParameters::getParameters(). @return array|false Array with information on the parameter at the specified offset, or with the specified name. Or `FALSE` if the specified parameter is not found. See the PHPCSUtils PassedParameters::getParameters() documentation for the format of the returned (single-dimensional) array.
get_hook_name_param
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/WPHookHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/WPHookHelper.php
MIT
public static function get_functions() { return \array_fill_keys( \array_keys( self::$arrayWalkingFunctions ), true ); }
Retrieve a list of the supported "array walking" functions. @since 3.0.0 @return array<string, bool>
get_functions
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/ArrayWalkingFunctionsHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/ArrayWalkingFunctionsHelper.php
MIT
public static function is_array_walking_function( $functionName ) { return isset( self::$arrayWalkingFunctions[ strtolower( $functionName ) ] ); }
Check if a particular function is an "array walking" function. @since 3.0.0 @param string $functionName The name of the function to check. @return bool
is_array_walking_function
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/ArrayWalkingFunctionsHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/ArrayWalkingFunctionsHelper.php
MIT
public static function get_callback_parameter( File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); if ( isset( $tokens[ $stackPtr ] ) === false ) { return false; } $functionName = strtolower( $tokens[ $stackPtr ]['content'] ); if ( isset( self::$arrayWalkingFunctions[ $functionName ] ) === false ) { return false; } return PassedParameters::getParameter( $phpcsFile, $stackPtr, self::$arrayWalkingFunctions[ $functionName ]['position'], self::$arrayWalkingFunctions[ $functionName ]['name'] ); }
Retrieve the parameter information for the callback parameter for an array walking function. @since 3.0.0 @param \PHP_CodeSniffer\Files\File $phpcsFile The file where this token was found. @param int $stackPtr The position of function call name token. @return array|false Array with information on the callback parameter. Or `FALSE` if the parameter is not found. See the PHPCSUtils PassedParameters::getParameters() documentation for the format of the returned (single-dimensional) array.
get_callback_parameter
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/ArrayWalkingFunctionsHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/ArrayWalkingFunctionsHelper.php
MIT
public static function get_array_access_keys( File $phpcsFile, $stackPtr, $all = true ) { $tokens = $phpcsFile->getTokens(); $keys = array(); if ( isset( $tokens[ $stackPtr ] ) === false || \T_VARIABLE !== $tokens[ $stackPtr ]['code'] ) { return $keys; } $current = $stackPtr; do { // Find the next non-empty token. $open_bracket = $phpcsFile->findNext( Tokens::$emptyTokens, ( $current + 1 ), null, true ); // If it isn't a bracket, this isn't an array-access. if ( false === $open_bracket || \T_OPEN_SQUARE_BRACKET !== $tokens[ $open_bracket ]['code'] || ! isset( $tokens[ $open_bracket ]['bracket_closer'] ) ) { break; } $key = GetTokensAsString::compact( $phpcsFile, ( $open_bracket + 1 ), ( $tokens[ $open_bracket ]['bracket_closer'] - 1 ), true ); $keys[] = trim( $key ); $current = $tokens[ $open_bracket ]['bracket_closer']; } while ( isset( $tokens[ $current ] ) && true === $all ); return $keys; }
Get the index keys of an array variable. E.g., "bar" and "baz" in $foo['bar']['baz']. @since 2.1.0 @since 3.0.0 - Moved from the Sniff class to this class. - Visibility is now `public` (was `protected`) and the method `static`. - The `$phpcsFile` parameter was added. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The index of the variable token in the stack. @param bool $all Whether to get all keys or only the first. Defaults to `true`(= all). @return array An array of index keys whose value is being accessed. or an empty array if this is not array access.
get_array_access_keys
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/VariableHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/VariableHelper.php
MIT
public static function get_array_access_key( File $phpcsFile, $stackPtr ) { $keys = self::get_array_access_keys( $phpcsFile, $stackPtr, false ); if ( isset( $keys[0] ) ) { return $keys[0]; } return false; }
Get the index key of an array variable. E.g., "bar" in $foo['bar']. @since 0.5.0 @since 2.1.0 Now uses get_array_access_keys() under the hood. @since 3.0.0 - Moved from the Sniff class to this class. - Visibility is now `public` (was `protected`) and the method `static`. - The `$phpcsFile` parameter was added. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The index of the variable token in the stack. @return string|false The array index key whose value is being accessed.
get_array_access_key
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/VariableHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/VariableHelper.php
MIT
public static function is_comparison( File $phpcsFile, $stackPtr, $include_coalesce = true ) { $tokens = $phpcsFile->getTokens(); if ( isset( $tokens[ $stackPtr ] ) === false ) { return false; } $comparisonTokens = Tokens::$comparisonTokens; if ( false === $include_coalesce ) { unset( $comparisonTokens[ \T_COALESCE ] ); } // We first check if this is a switch or match statement (switch ( $var )). if ( Parentheses::lastOwnerIn( $phpcsFile, $stackPtr, array( \T_SWITCH, \T_MATCH ) ) !== false ) { return true; } // Find the previous non-empty token. We check before the var first because // yoda conditions are usually expected. $previous_token = $phpcsFile->findPrevious( Tokens::$emptyTokens, ( $stackPtr - 1 ), null, true ); if ( isset( $comparisonTokens[ $tokens[ $previous_token ]['code'] ] ) ) { return true; } // Maybe the comparison operator is after this. $next_token = $phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); // This might be an opening square bracket in the case of arrays ($var['a']). while ( false !== $next_token && \T_OPEN_SQUARE_BRACKET === $tokens[ $next_token ]['code'] && isset( $tokens[ $next_token ]['bracket_closer'] ) ) { $next_token = $phpcsFile->findNext( Tokens::$emptyTokens, ( $tokens[ $next_token ]['bracket_closer'] + 1 ), null, true ); } if ( false !== $next_token && isset( $comparisonTokens[ $tokens[ $next_token ]['code'] ] ) ) { return true; } return false; }
Check whether a variable is being compared to another value. E.g., $var === 'foo', 1 <= $var, etc. Also recognizes `switch ( $var )` and `match ( $var )`. @since 0.5.0 @since 2.1.0 Added the $include_coalesce parameter. @since 3.0.0 - Moved from the Sniff class to this class. - Visibility is now `public` (was `protected`) and the method `static`. - The `$phpcsFile` parameter was added. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The index of this token in the stack. @param bool $include_coalesce Optional. Whether or not to regard the null coalesce operator - ?? - as a comparison operator. Defaults to true. Null coalesce is a special comparison operator in this sense as it doesn't compare a variable to whatever is on the other side of the comparison operator. @return bool Whether this is a comparison.
is_comparison
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/VariableHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/VariableHelper.php
MIT
private static function strip_quotes_from_array_values( array $text_strings ) { return array_map( array( 'PHPCSUtils\Utils\TextStrings', 'stripQuotes' ), $text_strings ); }
Strip quotes of all the values in an array containing only text strings. @since 3.0.0 @param string[] $text_strings The input array. @return string[]
strip_quotes_from_array_values
php
WordPress/WordPress-Coding-Standards
WordPress/Helpers/ValidationHelper.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Helpers/ValidationHelper.php
MIT
public function register() { $headers = array_map( 'preg_quote', array_keys( $this->theme_headers ), array_fill( 0, \count( $this->theme_headers ), '`' ) ); $this->theme_header_regex = sprintf( $this->header_regex_template, implode( '|', $headers ) ); $headers = array_map( 'preg_quote', array_keys( $this->plugin_headers ), array_fill( 0, \count( $this->plugin_headers ), '`' ) ); $this->plugin_header_regex = sprintf( $this->header_regex_template, implode( '|', $headers ) ); $targets = parent::register(); $targets[] = \T_DOC_COMMENT_OPEN_TAG; $targets[] = \T_COMMENT; return $targets; }
Returns an array of tokens this test wants to listen for. @since 1.2.0 @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Utils/I18nTextDomainFixerSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Utils/I18nTextDomainFixerSniff.php
MIT
public function process_comments( $stackPtr ) { if ( true === $this->header_found && ! defined( 'PHP_CODESNIFFER_IN_TESTS' ) ) { return; } $regex = $this->plugin_header_regex; $headers = $this->plugin_headers; $type = 'plugin'; $file = TextStrings::stripQuotes( $this->phpcsFile->getFileName() ); if ( 'STDIN' === $file ) { return; } $file_name = basename( $file ); if ( isset( $this->phpcsFile->tokenizerType ) && 'CSS' === $this->phpcsFile->tokenizerType ) { if ( 'style.css' !== $file_name && ! defined( 'PHP_CODESNIFFER_IN_TESTS' ) ) { // CSS files only need to be examined for the file header. return $this->phpcsFile->numTokens; } $regex = $this->theme_header_regex; $headers = $this->theme_headers; $type = 'theme'; } $comment_details = array( 'required_header_found' => false, 'headers_found' => 0, 'text_domain_ptr' => false, 'text_domain_found' => '', 'last_header_ptr' => false, 'last_header_matches' => array(), ); if ( \T_COMMENT === $this->tokens[ $stackPtr ]['code'] ) { $block_comment = false; if ( substr( $this->tokens[ $stackPtr ]['content'], 0, 2 ) === '/*' ) { $block_comment = true; } $current = $stackPtr; do { if ( false === $comment_details['text_domain_ptr'] || false === $comment_details['required_header_found'] || $comment_details['headers_found'] < 3 ) { $comment_details = $this->examine_comment_line( $current, $regex, $headers, $comment_details ); } if ( true === $block_comment && substr( $this->tokens[ $current ]['content'], -2 ) === '*/' ) { ++$current; break; } ++$current; } while ( isset( $this->tokens[ $current ] ) && \T_COMMENT === $this->tokens[ $current ]['code'] ); $skip_to = $current; } else { if ( ! isset( $this->tokens[ $stackPtr ]['comment_closer'] ) ) { return; } $closer = $this->tokens[ $stackPtr ]['comment_closer']; $current = $stackPtr; while ( ( $current = $this->phpcsFile->findNext( \T_DOC_COMMENT_STRING, ( $current + 1 ), $closer ) ) !== false ) { $comment_details = $this->examine_comment_line( $current, $regex, $headers, $comment_details ); if ( false !== $comment_details['text_domain_ptr'] && true === $comment_details['required_header_found'] && $comment_details['headers_found'] >= 3 ) { // No need to look at the rest of the docblock. break; } } $skip_to = $closer; } // So, was this the plugin/theme header ? if ( true === $comment_details['required_header_found'] && $comment_details['headers_found'] >= 3 ) { $this->header_found = true; $text_domain_ptr = $comment_details['text_domain_ptr']; $text_domain_found = $comment_details['text_domain_found']; if ( false !== $text_domain_ptr ) { if ( $this->new_text_domain !== $text_domain_found && ( \in_array( $text_domain_found, $this->old_text_domain, true ) ) ) { $fix = $this->phpcsFile->addFixableError( 'Mismatched text domain in %s header. Expected \'%s\' but found \'%s\'', $text_domain_ptr, 'TextDomainHeaderMismatch', array( $type, $this->new_text_domain, $text_domain_found, ) ); if ( true === $fix ) { if ( isset( $this->tokens[ $text_domain_ptr ]['orig_content'] ) ) { $replacement = $this->tokens[ $text_domain_ptr ]['orig_content']; } else { $replacement = $this->tokens[ $text_domain_ptr ]['content']; } $replacement = str_replace( $text_domain_found, $this->new_text_domain, $replacement ); $this->phpcsFile->fixer->replaceToken( $text_domain_ptr, $replacement ); } } } else { $last_header_ptr = $comment_details['last_header_ptr']; $last_header_matches = $comment_details['last_header_matches']; $fix = $this->phpcsFile->addFixableError( 'Missing "Text Domain" in %s header', $last_header_ptr, 'MissingTextDomainHeader', array( $type ) ); if ( true === $fix ) { if ( isset( $this->tokens[ $last_header_ptr ]['orig_content'] ) ) { $replacement = $this->tokens[ $last_header_ptr ]['orig_content']; } else { $replacement = $this->tokens[ $last_header_ptr ]['content']; } $replacement = str_replace( $last_header_matches[1], 'Text Domain', $replacement ); $replacement = str_replace( $last_header_matches[2], $this->new_text_domain, $replacement ); if ( \T_DOC_COMMENT_OPEN_TAG === $this->tokens[ $stackPtr ]['code'] ) { for ( $i = ( $last_header_ptr - 1 ); ; $i-- ) { if ( $this->tokens[ $i ]['line'] !== $this->tokens[ $last_header_ptr ]['line'] ) { ++$i; break; } } $replacement = $this->phpcsFile->eolChar . GetTokensAsString::origContent( $this->phpcsFile, $i, ( $last_header_ptr - 1 ) ) . $replacement; } $this->phpcsFile->fixer->addContent( $comment_details['last_header_ptr'], $replacement ); } } } return $skip_to; }
Process comments to find the plugin/theme headers. @since 1.2.0 @param int $stackPtr The position of the current token in the stack. @return int|void Integer stack pointer to skip forward or void to continue normal file processing.
process_comments
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Utils/I18nTextDomainFixerSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Utils/I18nTextDomainFixerSniff.php
MIT
protected function examine_comment_line( $stackPtr, $regex, $headers, $comment_details ) { if ( preg_match( $regex, $this->tokens[ $stackPtr ]['content'], $matches ) === 1 ) { ++$comment_details['headers_found']; if ( true === $headers[ $matches[1] ] ) { $comment_details['required_header_found'] = true; } if ( 'Text Domain' === $matches[1] ) { $comment_details['text_domain_ptr'] = $stackPtr; $comment_details['text_domain_found'] = trim( $matches[2] ); } $comment_details['last_header_ptr'] = $stackPtr; $comment_details['last_header_matches'] = $matches; } return $comment_details; }
Examine an individual token in a larger comment for plugin/theme headers. @since 1.2.0 @param int $stackPtr The position of the current token in the stack. @param string $regex The regex to use to examine the comment line. @param array $headers Valid headers for a plugin or theme. @param array $comment_details The information collected so far. @return array Adjusted $comment_details array
examine_comment_line
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Utils/I18nTextDomainFixerSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Utils/I18nTextDomainFixerSniff.php
MIT
public function register() { if ( \defined( '\PHP_CODESNIFFER_IN_TESTS' ) ) { $this->hyphenation_exceptions += $this->unittest_hyphenation_exceptions; } return Collections::phpOpenTags(); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Files/FileNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Files/FileNameSniff.php
MIT
public function process_token( $stackPtr ) { // Usage of `stripQuotes` is to ensure `stdin_path` passed by IDEs does not include quotes. $file = TextStrings::stripQuotes( $this->phpcsFile->getFileName() ); if ( 'STDIN' === $file ) { return $this->phpcsFile->numTokens; } $class_ptr = $this->phpcsFile->findNext( \T_CLASS, $stackPtr ); if ( false !== $class_ptr && $this->is_test_class( $this->phpcsFile, $class_ptr ) ) { /* * This rule should not be applied to test classes (at all). * @link https://github.com/WordPress/WordPress-Coding-Standards/issues/1995 */ return $this->phpcsFile->numTokens; } // Respect phpcs:disable comments as long as they are not accompanied by an enable. $i = -1; while ( $i = $this->phpcsFile->findNext( \T_PHPCS_DISABLE, ( $i + 1 ) ) ) { if ( empty( $this->tokens[ $i ]['sniffCodes'] ) || isset( $this->tokens[ $i ]['sniffCodes']['WordPress'] ) || isset( $this->tokens[ $i ]['sniffCodes']['WordPress.Files'] ) || isset( $this->tokens[ $i ]['sniffCodes']['WordPress.Files.FileName'] ) ) { do { $i = $this->phpcsFile->findNext( \T_PHPCS_ENABLE, ( $i + 1 ) ); } while ( false !== $i && ! empty( $this->tokens[ $i ]['sniffCodes'] ) && ! isset( $this->tokens[ $i ]['sniffCodes']['WordPress'] ) && ! isset( $this->tokens[ $i ]['sniffCodes']['WordPress.Files'] ) && ! isset( $this->tokens[ $i ]['sniffCodes']['WordPress.Files.FileName'] ) ); if ( false === $i ) { // The entire (rest of the) file is disabled. return $this->phpcsFile->numTokens; } } } $file_name = basename( $file ); $this->check_filename_is_hyphenated( $file_name ); if ( true === $this->strict_class_file_names && false !== $class_ptr ) { $this->check_filename_has_class_prefix( $class_ptr, $file_name ); } if ( false !== strpos( $file, \DIRECTORY_SEPARATOR . 'wp-includes' . \DIRECTORY_SEPARATOR ) && false === $class_ptr ) { $this->check_filename_for_template_suffix( $stackPtr, $file_name ); } // Only run this sniff once per file, no need to run it again. return $this->phpcsFile->numTokens; }
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/Files/FileNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Files/FileNameSniff.php
MIT
protected function check_filename_is_hyphenated( $file_name ) { $extension = strrchr( $file_name, '.' ); $name = substr( $file_name, 0, ( strlen( $file_name ) - strlen( $extension ) ) ); $expected = strtolower( preg_replace( '`[[:punct:]]`', '-', $name ) ) . $extension; if ( $file_name === $expected || isset( $this->hyphenation_exceptions[ $file_name ] ) ) { return; } if ( true === $this->is_theme && 1 === preg_match( self::THEME_EXCEPTIONS_REGEX, $file_name ) ) { return; } $this->phpcsFile->addError( 'Filenames should be all lowercase with hyphens as word separators. Expected %s, but found %s.', 0, 'NotHyphenatedLowercase', array( $expected, $file_name ) ); }
Generic check for lowercase hyphenated file names. @since 3.0.0 @param string $file_name The name of the current file. @return void
check_filename_is_hyphenated
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Files/FileNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Files/FileNameSniff.php
MIT
protected function check_filename_has_class_prefix( $class_ptr, $file_name ) { $extension = strrchr( $file_name, '.' ); $class_name = ObjectDeclarations::getName( $this->phpcsFile, $class_ptr ); $expected = 'class-' . strtolower( str_replace( '_', '-', $class_name ) ) . $extension; if ( $file_name === $expected ) { return; } $this->phpcsFile->addError( 'Class file names should be based on the class name with "class-" prepended. Expected %s, but found %s.', 0, 'InvalidClassFileName', array( $expected, $file_name, ) ); }
Check files containing a class for the "class-" prefix and that the rest of the file name reflects the class name. @since 3.0.0 @param int $class_ptr Stack pointer to the first T_CLASS in the file. @param string $file_name The name of the current file. @return void
check_filename_has_class_prefix
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Files/FileNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Files/FileNameSniff.php
MIT
protected function check_filename_for_template_suffix( $stackPtr, $file_name ) { $subpackage_tag = $this->phpcsFile->findNext( \T_DOC_COMMENT_TAG, $stackPtr, null, false, '@subpackage' ); if ( false === $subpackage_tag ) { return; } $subpackage = $this->phpcsFile->findNext( \T_DOC_COMMENT_STRING, $subpackage_tag ); if ( false === $subpackage ) { return; } $fileName_end = substr( $file_name, -13 ); if ( ( 'Template' === trim( $this->tokens[ $subpackage ]['content'] ) && $this->tokens[ $subpackage_tag ]['line'] === $this->tokens[ $subpackage ]['line'] ) && ( ( ! \defined( '\PHP_CODESNIFFER_IN_TESTS' ) && '-template.php' !== $fileName_end ) || ( \defined( '\PHP_CODESNIFFER_IN_TESTS' ) && '-template.inc' !== $fileName_end ) ) ) { $this->phpcsFile->addError( 'Files containing template tags should have "-template" appended to the end of the file name. Expected %s, but found %s.', 0, 'InvalidTemplateTagFileName', array( substr( $file_name, 0, -4 ) . '-template.php', $file_name, ) ); } }
Check non-class files in "wp-includes" with a "@subpackage Template" tag for a "-template" suffix. @since 3.0.0 @param int $stackPtr Stack pointer to the first PHP open tag in the file. @param string $file_name The name of the current file. @return void
check_filename_for_template_suffix
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/Files/FileNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/Files/FileNameSniff.php
MIT
public function register() { return array( \T_VARIABLE, ); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/DB/DirectDatabaseQuerySniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/DirectDatabaseQuerySniff.php
MIT
public function process_token( $stackPtr ) { // Check for $wpdb variable. if ( '$wpdb' !== $this->tokens[ $stackPtr ]['content'] ) { return; } $is_object_call = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); if ( false === $is_object_call || ( \T_OBJECT_OPERATOR !== $this->tokens[ $is_object_call ]['code'] && \T_NULLSAFE_OBJECT_OPERATOR !== $this->tokens[ $is_object_call ]['code'] ) ) { // This is not a call to the wpdb object. return; } $methodPtr = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $is_object_call + 1 ), null, true ); $method = strtolower( $this->tokens[ $methodPtr ]['content'] ); $this->mergeFunctionLists(); if ( ! isset( $this->methods['all'][ $method ] ) ) { return; } $endOfStatement = $this->phpcsFile->findNext( array( \T_SEMICOLON, \T_CLOSE_TAG ), ( $stackPtr + 1 ) ); if ( false === $endOfStatement ) { return; } // Check for Database Schema Changes/ table truncation. for ( $_pos = ( $stackPtr + 1 ); $_pos < $endOfStatement; $_pos++ ) { $_pos = $this->phpcsFile->findNext( Tokens::$textStringTokens, $_pos, $endOfStatement ); if ( false === $_pos ) { break; } if ( strpos( strtoupper( TextStrings::stripQuotes( $this->tokens[ $_pos ]['content'] ) ), 'TRUNCATE ' ) === 0 ) { // Ignore queries to truncate the database as caching those is irrelevant and they need a direct db query. return; } if ( preg_match( '#\b(?:ALTER|CREATE|DROP)\b#i', $this->tokens[ $_pos ]['content'] ) > 0 ) { $this->phpcsFile->addWarning( 'Attempting a database schema change is discouraged.', $_pos, 'SchemaChange' ); } } $this->phpcsFile->addWarning( 'Use of a direct database call is discouraged.', $stackPtr, 'DirectQuery' ); if ( ! isset( $this->methods['cachable'][ $method ] ) ) { return $endOfStatement; } $cached = false; $wp_cache_get = false; $scope_function = Conditions::getLastCondition( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); if ( false !== $scope_function ) { $scopeStart = $this->tokens[ $scope_function ]['scope_opener']; $scopeEnd = $this->tokens[ $scope_function ]['scope_closer']; for ( $i = ( $scopeStart + 1 ); $i < $scopeEnd; $i++ ) { if ( \T_STRING === $this->tokens[ $i ]['code'] ) { if ( isset( $this->cacheDeleteFunctions[ $this->tokens[ $i ]['content'] ] ) ) { if ( \in_array( $method, array( 'query', 'update', 'replace', 'delete' ), true ) ) { $cached = true; break; } } elseif ( isset( $this->cacheGetFunctions[ $this->tokens[ $i ]['content'] ] ) ) { $wp_cache_get = true; } elseif ( isset( $this->cacheSetFunctions[ $this->tokens[ $i ]['content'] ] ) ) { if ( $wp_cache_get ) { $cached = true; break; } } } } } if ( ! $cached ) { $message = 'Direct database call without caching detected. Consider using wp_cache_get() / wp_cache_set() or wp_cache_delete().'; $this->phpcsFile->addWarning( $message, $stackPtr, 'NoCaching' ); } return $endOfStatement; }
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/DB/DirectDatabaseQuerySniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/DirectDatabaseQuerySniff.php
MIT
protected function mergeFunctionLists() { if ( ! isset( $this->methods['all'] ) ) { $this->methods['all'] = array_merge( $this->methods['cachable'], $this->methods['noncachable'] ); } if ( $this->customCacheGetFunctions !== $this->addedCustomFunctions['cacheget'] ) { $this->cacheGetFunctions = RulesetPropertyHelper::merge_custom_array( $this->customCacheGetFunctions, $this->cacheGetFunctions ); $this->addedCustomFunctions['cacheget'] = $this->customCacheGetFunctions; } if ( $this->customCacheSetFunctions !== $this->addedCustomFunctions['cacheset'] ) { $this->cacheSetFunctions = RulesetPropertyHelper::merge_custom_array( $this->customCacheSetFunctions, $this->cacheSetFunctions ); $this->addedCustomFunctions['cacheset'] = $this->customCacheSetFunctions; } if ( $this->customCacheDeleteFunctions !== $this->addedCustomFunctions['cachedelete'] ) { $this->cacheDeleteFunctions = RulesetPropertyHelper::merge_custom_array( $this->customCacheDeleteFunctions, $this->cacheDeleteFunctions ); $this->addedCustomFunctions['cachedelete'] = $this->customCacheDeleteFunctions; } }
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/DB/DirectDatabaseQuerySniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/DirectDatabaseQuerySniff.php
MIT
public function getGroups() { return array( 'mysql' => array( 'type' => 'error', 'message' => 'Accessing the database directly should be avoided. Please use the $wpdb object and associated functions instead. Found: %s.', 'functions' => array( 'mysql_*', 'mysqli_*', 'mysqlnd_ms_*', 'mysqlnd_qc_*', 'mysqlnd_uh_*', 'mysqlnd_memcache_*', 'maxdb_*', ), 'allow' => array( 'mysql_to_rfc3339' => true, ), ), ); }
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/DB/RestrictedFunctionsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/RestrictedFunctionsSniff.php
MIT
public function getGroups() { return array( 'mysql' => array( 'type' => 'error', 'message' => 'Accessing the database directly should be avoided. Please use the $wpdb object and associated functions instead. Found: %s.', 'classes' => array( 'mysqli', 'PDO', 'PDOStatement', ), ), ); }
Groups of classes to restrict. Example: groups => array( 'lambda' => array( 'type' => 'error' | 'warning', 'message' => 'Avoid direct calls to the database.', 'classes' => array( 'PDO', '\Namespace\Classname' ), ) ) @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/DB/RestrictedClassesSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/RestrictedClassesSniff.php
MIT
public function register() { // Enrich the array of tokens which can be safely ignored. $this->ignored_tokens += Tokens::$bracketTokens; $this->ignored_tokens += Tokens::$heredocTokens; $this->ignored_tokens += Tokens::$castTokens; $this->ignored_tokens += Tokens::$arithmeticTokens; $this->ignored_tokens += Collections::incrementDecrementOperators(); $this->ignored_tokens += Collections::objectOperators(); $this->ignored_tokens += Tokens::$emptyTokens; // The contents of heredoc tokens needs to be examined. unset( $this->ignored_tokens[ \T_HEREDOC ] ); return array( \T_VARIABLE, \T_STRING, ); }
Returns an array of tokens this test wants to listen for. @since 0.8.0 @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/DB/PreparedSQLSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/PreparedSQLSniff.php
MIT
public function getGroups() { return array( 'slow_db_query' => array( 'type' => 'warning', 'message' => 'Detected usage of %s, possible slow query.', 'keys' => array( 'tax_query', 'meta_query', 'meta_key', 'meta_value', ), ), ); }
Groups of variables to restrict. @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/DB/SlowDBQuerySniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/SlowDBQuerySniff.php
MIT
public function callback( $key, $val, $line, $group ) { return true; }
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 Always returns TRUE as the value is irrelevant.
callback
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/DB/SlowDBQuerySniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/SlowDBQuerySniff.php
MIT
public function register() { return array( \T_VARIABLE, \T_STRING, ); }
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/DB/PreparedSQLPlaceholdersSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/PreparedSQLPlaceholdersSniff.php
MIT
protected function get_regex_quote_snippet( $stripped_content, $original_content ) { $regex_quote = $this->regex_quote; if ( $original_content !== $stripped_content ) { $quote_style = $original_content[0]; if ( '"' === $quote_style ) { $regex_quote = '\\\\"|\''; } elseif ( "'" === $quote_style ) { $regex_quote = '"|\\\\\''; } } return $regex_quote; }
Retrieve a regex snippet to recognize and remember quotes based on the quote style used in the original string (if any). This allows for recognizing `"` and `\'` in single quoted strings, recognizing `'` and `\"` in double quotes strings and `'` and `"`when the quote style is unknown or it is a non-quoted string (heredoc/nowdoc and such). @since 0.14.0 @param string $stripped_content Text string content without surrounding quotes. @param string $original_content Original content for the same text string. @return string
get_regex_quote_snippet
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/DB/PreparedSQLPlaceholdersSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/PreparedSQLPlaceholdersSniff.php
MIT
protected function analyse_implode( $implode_token ) { $implode_params = PassedParameters::getParameters( $this->phpcsFile, $implode_token ); if ( empty( $implode_params ) || \count( $implode_params ) !== 2 ) { return false; } $implode_separator_param = PassedParameters::getParameterFromStack( $implode_params, 1, 'separator' ); if ( false === $implode_separator_param || preg_match( '`^(["\']), ?\1$`', $implode_separator_param['clean'] ) !== 1 ) { return false; } $implode_array_param = PassedParameters::getParameterFromStack( $implode_params, 2, 'array' ); if ( false === $implode_array_param ) { return false; } $array_fill = $this->phpcsFile->findNext( Tokens::$emptyTokens + array( \T_NS_SEPARATOR => \T_NS_SEPARATOR ), $implode_array_param['start'], $implode_array_param['end'], true ); if ( \T_STRING !== $this->tokens[ $array_fill ]['code'] || 'array_fill' !== strtolower( $this->tokens[ $array_fill ]['content'] ) ) { return false; } $array_fill_value_param = PassedParameters::getParameter( $this->phpcsFile, $array_fill, 3, 'value' ); if ( false === $array_fill_value_param ) { return false; } if ( "'%i'" === $array_fill_value_param['clean'] || '"%i"' === $array_fill_value_param['clean'] ) { $firstNonEmpty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $array_fill_value_param['start'], $array_fill_value_param['end'], true ); $this->phpcsFile->addError( 'The %i placeholder cannot be used within SQL `IN()` clauses.', $firstNonEmpty, 'IdentifierWithinIN' ); return false; } return (bool) preg_match( '`^(["\'])%[dfFs]\1$`', $array_fill_value_param['clean'] ); }
Analyse an implode() function call to see if it contains a specific code pattern to dynamically create placeholders. The pattern we are searching for is: `implode( ',', array_fill( 0, count( $something ), '%s' ) )` This pattern presumes unquoted placeholders! Identifiers (%i) are not supported, as this function is designed to work with `IN()`, which contains a list of values. In the future, it should be possible to simplify code using the implode/array_fill pattern to use a variable number of identifiers, e.g. `CONCAT(%...i)`, https://core.trac.wordpress.org/ticket/54042 @since 0.14.0 @param int $implode_token The stackPtr to the implode function call. @return bool True if the pattern is found, false otherwise.
analyse_implode
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/DB/PreparedSQLPlaceholdersSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/DB/PreparedSQLPlaceholdersSniff.php
MIT
public function getGroups() { // Only retrieve functions which are not used for deprecated hooks. $this->target_functions = WPHookHelper::get_functions( false ); return parent::getGroups(); }
Groups of functions to restrict. @since 0.11.0 @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php
MIT
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { $hook_name_param = WPHookHelper::get_hook_name_param( $matched_content, $parameters ); if ( false === $hook_name_param ) { return; } $regex = $this->prepare_regex(); $case_errors = 0; $underscores = 0; $content = array(); $expected = array(); $last_non_empty = null; for ( $i = $hook_name_param['start']; $i <= $hook_name_param['end']; $i++ ) { // Skip past comment tokens. if ( isset( Tokens::$commentTokens[ $this->tokens[ $i ]['code'] ] ) ) { continue; } $content[ $i ] = $this->tokens[ $i ]['content']; $expected[ $i ] = $this->tokens[ $i ]['content']; // Skip past potential variable array access: `$var['key']`. if ( \T_VARIABLE === $this->tokens[ $i ]['code'] ) { do { $open_bracket = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $i + 1 ), null, true ); if ( false === $open_bracket || \T_OPEN_SQUARE_BRACKET !== $this->tokens[ $open_bracket ]['code'] || ! isset( $this->tokens[ $open_bracket ]['bracket_closer'] ) ) { $last_non_empty = $i; continue 2; } $i = $this->tokens[ $open_bracket ]['bracket_closer']; } while ( isset( $this->tokens[ $i ] ) && $i <= $hook_name_param['end'] ); $last_non_empty = $i; continue; } // Skip over parameters passed to function calls. if ( \T_OPEN_PARENTHESIS === $this->tokens[ $i ]['code'] && ( \T_STRING === $this->tokens[ $last_non_empty ]['code'] || \T_VARIABLE === $this->tokens[ $last_non_empty ]['code'] ) && isset( $this->tokens[ $i ]['parenthesis_closer'] ) ) { $i = $this->tokens[ $i ]['parenthesis_closer']; $last_non_empty = $i; continue; } // Skip past non text string tokens. if ( isset( Tokens::$stringTokens[ $this->tokens[ $i ]['code'] ] ) === false ) { $last_non_empty = $i; continue; } $last_non_empty = $i; $string = TextStrings::stripQuotes( $this->tokens[ $i ]['content'] ); /* * Here be dragons - a double quoted string can contain extrapolated variables * which don't have to comply with these rules. */ if ( \T_DOUBLE_QUOTED_STRING === $this->tokens[ $i ]['code'] ) { $transform = $this->transform_complex_string( $string, $regex ); $case_transform = $this->transform_complex_string( $string, $regex, 'case' ); $punct_transform = $this->transform_complex_string( $string, $regex, 'punctuation' ); } else { $transform = $this->transform( $string, $regex ); $case_transform = $this->transform( $string, $regex, 'case' ); $punct_transform = $this->transform( $string, $regex, 'punctuation' ); } if ( $string === $transform ) { continue; } if ( \T_DOUBLE_QUOTED_STRING === $this->tokens[ $i ]['code'] ) { $expected[ $i ] = '"' . $transform . '"'; } else { $expected[ $i ] = '\'' . $transform . '\''; } if ( $string !== $case_transform ) { ++$case_errors; } if ( $string !== $punct_transform ) { ++$underscores; } } $first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $hook_name_param['start'], ( $hook_name_param['end'] + 1 ), true ); $data = array( trim( implode( '', $expected ) ), trim( implode( '', $content ) ), ); if ( $case_errors > 0 ) { $error = 'Hook names should be lowercase. Expected: %s, but found: %s.'; $this->phpcsFile->addError( $error, $first_non_empty, 'NotLowercase', $data ); } if ( $underscores > 0 ) { $error = 'Words in hook names should be separated using underscores. Expected: %s, but found: %s.'; $this->phpcsFile->addWarning( $error, $first_non_empty, 'UseUnderscores', $data ); } }
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/NamingConventions/ValidHookNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php
MIT
protected function prepare_regex() { $extra = ''; if ( '' !== $this->additionalWordDelimiters && \is_string( $this->additionalWordDelimiters ) ) { $extra = preg_quote( $this->additionalWordDelimiters, '`' ); } return sprintf( $this->punctuation_regex, $extra ); }
Prepare the punctuation regular expression. Merges the existing regular expression with potentially provided extra word delimiters to allow. This is done 'late' and for each found token as otherwise inline `phpcs:set` directives would be ignored. @return string
prepare_regex
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php
MIT
protected function transform( $text_string, $regex, $transform_type = 'full' ) { switch ( $transform_type ) { case 'case': return strtolower( $text_string ); case 'punctuation': return preg_replace( $regex, '_', $text_string ); case 'full': default: return preg_replace( $regex, '_', strtolower( $text_string ) ); } }
Transform an arbitrary string to lowercase and replace punctuation and spaces with underscores. @param string $text_string The target string. @param string $regex The punctuation regular expression to use. @param string $transform_type Whether to do a partial or complete transform. Valid values are: 'full', 'case', 'punctuation'. @return string
transform
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidHookNameSniff.php
MIT
protected function processVariable( File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); // If it's a php reserved var, then its ok. if ( Variables::isPHPReservedVarName( $tokens[ $stackPtr ]['content'] ) ) { return; } // Merge any custom variables with the defaults. $this->merge_allow_lists(); $var_name = ltrim( $tokens[ $stackPtr ]['content'], '$' ); // Likewise if it is a mixed-case var used by WordPress core. if ( isset( $this->wordpress_mixed_case_vars[ $var_name ] ) ) { return; } $obj_operator = $phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); if ( \T_OBJECT_OPERATOR === $tokens[ $obj_operator ]['code'] || \T_NULLSAFE_OBJECT_OPERATOR === $tokens[ $obj_operator ]['code'] ) { // Check to see if we are using a variable from an object. $var = $phpcsFile->findNext( Tokens::$emptyTokens, ( $obj_operator + 1 ), null, true ); if ( \T_STRING === $tokens[ $var ]['code'] ) { $bracket = $phpcsFile->findNext( Tokens::$emptyTokens, ( $var + 1 ), null, true ); if ( \T_OPEN_PARENTHESIS !== $tokens[ $bracket ]['code'] ) { $obj_var_name = $tokens[ $var ]['content']; if ( isset( $this->allowed_mixed_case_member_var_names[ $obj_var_name ] ) ) { return; } $suggested_name = SnakeCaseHelper::get_suggestion( $obj_var_name ); if ( $suggested_name !== $obj_var_name ) { $error = 'Object property "$%s" is not in valid snake_case format, try "$%s"'; $data = array( $obj_var_name, $suggested_name, ); $phpcsFile->addError( $error, $var, 'UsedPropertyNotSnakeCase', $data ); } } } } $in_class = false; if ( ContextHelper::has_object_operator_before( $phpcsFile, $stackPtr ) === true ) { // The variable lives within a class, and is referenced like // this: MyClass::$_variable or $class->variable. $in_class = true; } $suggested_name = SnakeCaseHelper::get_suggestion( $var_name ); if ( $suggested_name !== $var_name ) { if ( $in_class && ! isset( $this->allowed_mixed_case_member_var_names[ $var_name ] ) ) { $error = 'Object property "$%s" is not in valid snake_case format, try "$%s"'; $error_name = 'UsedPropertyNotSnakeCase'; } elseif ( ! $in_class ) { $error = 'Variable "$%s" is not in valid snake_case format, try "$%s"'; $error_name = 'VariableNotSnakeCase'; } if ( isset( $error, $error_name ) ) { $data = array( $var_name, $suggested_name, ); $phpcsFile->addError( $error, $stackPtr, $error_name, $data ); } } }
Processes this test, when one of its tokens is encountered. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
processVariable
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php
MIT
protected function processMemberVar( File $phpcsFile, $stackPtr ) { // Make sure this is actually an OO property and not an OO method parameter or illegal property declaration. if ( Scopes::isOOProperty( $phpcsFile, $stackPtr ) === false ) { return; } // Merge any custom variables with the defaults. $this->merge_allow_lists(); $tokens = $phpcsFile->getTokens(); $var_name = ltrim( $tokens[ $stackPtr ]['content'], '$' ); if ( isset( $this->allowed_mixed_case_member_var_names[ $var_name ] ) ) { return; } $suggested_name = SnakeCaseHelper::get_suggestion( $var_name ); if ( $suggested_name !== $var_name ) { $error = 'Member variable "$%s" is not in valid snake_case format, try "$%s"'; $data = array( $var_name, $suggested_name, ); $phpcsFile->addError( $error, $stackPtr, 'PropertyNotSnakeCase', $data ); } }
Processes class member variables. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void
processMemberVar
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php
MIT
protected function processVariableInString( File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); // There will always be embeds if the processVariableInString() was called. $embeds = TextStrings::getEmbeds( $tokens[ $stackPtr ]['content'] ); // Merge any custom variables with the defaults. $this->merge_allow_lists(); foreach ( $embeds as $embed ) { // Grab any variables contained in the embed. if ( preg_match_all( '`\$(\{)?(?<name>[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*)(?(1)\})`', $embed, $matches ) === 0 ) { continue; } foreach ( $matches['name'] as $var_name ) { // If it's a php reserved var, then its ok. if ( Variables::isPHPReservedVarName( $var_name ) ) { continue; } // Likewise if it is a mixed-case var used by WordPress core. if ( isset( $this->wordpress_mixed_case_vars[ $var_name ] ) ) { continue; } $suggested_name = SnakeCaseHelper::get_suggestion( $var_name ); if ( $suggested_name !== $var_name ) { $error = 'Variable "$%s" is not in valid snake_case format, try "$%s"'; $data = array( $var_name, $suggested_name, ); $phpcsFile->addError( $error, $stackPtr, 'InterpolatedVariableNotSnakeCase', $data ); } } } }
Processes the variables found within a double quoted string. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the double quoted string. @return void
processVariableInString
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php
MIT
protected function merge_allow_lists() { if ( $this->allowed_custom_properties !== $this->addedCustomProperties['properties'] ) { // Fix property potentially passed as comma-delimited string. $customProperties = RulesetPropertyHelper::merge_custom_array( $this->allowed_custom_properties, array(), false ); $this->allowed_mixed_case_member_var_names = RulesetPropertyHelper::merge_custom_array( $customProperties, $this->allowed_mixed_case_member_var_names ); $this->addedCustomProperties['properties'] = $this->allowed_custom_properties; } }
Merge a custom allow list provided via a custom ruleset with the predefined allow list, if we haven't already. @since 0.10.0 @since 2.0.0 Removed unused $phpcs_file parameter. @since 3.0.0 Renamed from `mergeWhiteList()` to `merge_allow_lists()`. @return void
merge_allow_lists
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidVariableNameSniff.php
MIT
public function register() { $this->valid_tokens = Tokens::$textStringTokens + Tokens::$heredocTokens + Tokens::$emptyTokens; return parent::register(); }
Returns an array of tokens this test wants to listen for. @since 2.2.0 @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidPostTypeSlugSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidPostTypeSlugSniff.php
MIT
public function register() { // Get a list of all PHP native functions. $all_functions = get_defined_functions(); $this->built_in_functions = array_flip( $all_functions['internal'] ); $this->built_in_functions = array_change_key_case( $this->built_in_functions, \CASE_LOWER ); // Make sure the pluggable functions and classes list can be easily compared. $this->pluggable_functions = array_change_key_case( $this->pluggable_functions, \CASE_LOWER ); $this->pluggable_classes = array_change_key_case( $this->pluggable_classes, \CASE_LOWER ); // Set the sniff targets. $targets = array( \T_NAMESPACE => \T_NAMESPACE, \T_FUNCTION => \T_FUNCTION, \T_CONST => \T_CONST, \T_VARIABLE => \T_VARIABLE, \T_DOLLAR => \T_DOLLAR, // Variable variables. \T_FN_ARROW => \T_FN_ARROW, // T_FN_ARROW is only used for skipping over (for now). ); $targets += Tokens::$ooScopeTokens; // T_ANON_CLASS is only used for skipping over test classes. $targets += Collections::listOpenTokensBC(); // Add function call target for hook names and constants defined using define(). $parent = parent::register(); if ( ! empty( $parent ) ) { $targets[] = \T_STRING; } return $targets; }
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/NamingConventions/PrefixAllGlobalsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
MIT
public function getGroups() { // Only retrieve functions which are not used for deprecated hooks. $this->target_functions = WPHookHelper::get_functions( false ); $this->target_functions['define'] = true; return parent::getGroups(); }
Groups of functions to restrict. @since 0.12.0 @return array
getGroups
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
MIT
protected function process_variable_variable( $stackPtr ) { static $indicators = array( \T_OPEN_CURLY_BRACKET => true, \T_VARIABLE => true, ); // Is this a variable variable ? // Not concerned with nested ones as those will be recognized on their own token. $next_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true ); if ( false === $next_non_empty || ! isset( $indicators[ $this->tokens[ $next_non_empty ]['code'] ] ) ) { return; } if ( \T_OPEN_CURLY_BRACKET === $this->tokens[ $next_non_empty ]['code'] && isset( $this->tokens[ $next_non_empty ]['bracket_closer'] ) ) { // Skip over the variable part. $next_non_empty = $this->tokens[ $next_non_empty ]['bracket_closer']; } $maybe_assignment = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $next_non_empty + 1 ), null, true, null, true ); while ( false !== $maybe_assignment && \T_OPEN_SQUARE_BRACKET === $this->tokens[ $maybe_assignment ]['code'] && isset( $this->tokens[ $maybe_assignment ]['bracket_closer'] ) ) { $maybe_assignment = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $this->tokens[ $maybe_assignment ]['bracket_closer'] + 1 ), null, true, null, true ); } if ( false === $maybe_assignment ) { return; } if ( ! isset( Tokens::$assignmentTokens[ $this->tokens[ $maybe_assignment ]['code'] ] ) ) { // Not an assignment. return; } $error = self::ERROR_MSG; /* * Local variable variables in a function do not need to be prefixed. * But a variable variable could evaluate to the name of an imported global * variable. * Not concerned with imported variable variables (global.. ) as that has been * forbidden since PHP 7.0. Presuming cross-version code and if not, that * is for the PHPCompatibility standard to detect. */ $functionPtr = Conditions::getLastCondition( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); if ( false !== $functionPtr ) { $has_global = $this->phpcsFile->findPrevious( \T_GLOBAL, ( $stackPtr - 1 ), $this->tokens[ $functionPtr ]['scope_opener'] ); if ( false === $has_global ) { // No variable import happening. return; } $error = 'Variable variable which could potentially override an imported global variable detected. ' . $error; } $variable_name = $this->phpcsFile->getTokensAsString( $stackPtr, ( ( $next_non_empty - $stackPtr ) + 1 ) ); // Still here ? In that case, the variable name should be prefixed. $recorded = $this->phpcsFile->addWarning( $error, $stackPtr, 'NonPrefixedVariableFound', array( 'Global variables defined', $variable_name, ) ); if ( true === $recorded ) { $this->record_potential_prefix_metric( $stackPtr, $variable_name ); } // Skip over the variable part of the variable. return ( $next_non_empty + 1 ); }
Handle variable variables defined in the global namespace. @since 0.12.0 @param int $stackPtr The position of the current token in the stack. @return int|void Integer stack pointer to skip forward or void to continue normal file processing.
process_variable_variable
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
MIT
protected function process_variable_assignment( $stackPtr, $in_list = false ) { /* * We're only concerned with variables which are being defined. * `is_assignment()` will not recognize property assignments, which is good in this case. * However it will also not recognize $b in `foreach( $a as $b )` as an assignment, so * we need a separate check for that. */ if ( false === $in_list && false === VariableHelper::is_assignment( $this->phpcsFile, $stackPtr ) && Context::inForeachCondition( $this->phpcsFile, $stackPtr ) !== 'afterAs' ) { return; } $is_error = true; $variable_name = substr( $this->tokens[ $stackPtr ]['content'], 1 ); // Strip the dollar sign. // Bow out early if we know for certain no prefix is needed. if ( 'GLOBALS' !== $variable_name && $this->variable_prefixed_or_allowed( $stackPtr, $variable_name ) === true ) { return; } if ( 'GLOBALS' === $variable_name ) { $array_open = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true, null, true ); if ( false === $array_open || \T_OPEN_SQUARE_BRACKET !== $this->tokens[ $array_open ]['code'] ) { // Live coding or something very silly. return; } $array_key = $this->phpcsFile->findNext( Tokens::$emptyTokens, ( $array_open + 1 ), null, true, null, true ); if ( false === $array_key ) { // No key found, nothing to do. return; } $stackPtr = $array_key; $variable_name = TextStrings::stripQuotes( $this->tokens[ $array_key ]['content'] ); // Check whether a prefix is needed. if ( isset( Tokens::$stringTokens[ $this->tokens[ $array_key ]['code'] ] ) && $this->variable_prefixed_or_allowed( $stackPtr, $variable_name ) === true ) { return; } if ( \T_DOUBLE_QUOTED_STRING === $this->tokens[ $array_key ]['code'] ) { // If the array key is a double quoted string, try again with only // the part before the first variable (if any). $exploded = explode( '$', $variable_name ); $first = rtrim( $exploded[0], '{' ); if ( '' !== $first ) { if ( $this->variable_prefixed_or_allowed( $array_key, $first ) === true ) { return; } } else { // If the first part was dynamic, throw a warning. $is_error = false; } } elseif ( ! isset( Tokens::$stringTokens[ $this->tokens[ $array_key ]['code'] ] ) ) { // Dynamic array key, throw a warning. $is_error = false; } } else { // Function parameters do not need to be prefixed. if ( false === $in_list ) { $functionPtr = Parentheses::getLastOwner( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); if ( false !== $functionPtr ) { return; } unset( $functionPtr ); } // Properties in a class do not need to be prefixed. if ( false === $in_list && true === Scopes::isOOProperty( $this->phpcsFile, $stackPtr ) ) { return; } // Local variables in a function do not need to be prefixed unless they are being imported. $functionPtr = Conditions::getLastCondition( $this->phpcsFile, $stackPtr, Collections::functionDeclarationTokens() ); if ( false !== $functionPtr ) { $has_global = $this->phpcsFile->findPrevious( \T_GLOBAL, ( $stackPtr - 1 ), $this->tokens[ $functionPtr ]['scope_opener'] ); if ( false === $has_global || Conditions::getLastCondition( $this->phpcsFile, $has_global, Collections::functionDeclarationTokens() ) !== $functionPtr ) { // No variable import happening in the current scope. return; } // Ok, this may be an imported global variable. $end_of_statement = $this->phpcsFile->findNext( array( \T_SEMICOLON, \T_CLOSE_TAG ), ( $has_global + 1 ) ); if ( false === $end_of_statement ) { // No semi-colon - live coding. return; } for ( $ptr = ( $has_global + 1 ); $ptr <= $end_of_statement; $ptr++ ) { // Move the stack pointer to the next variable. $ptr = $this->phpcsFile->findNext( \T_VARIABLE, $ptr, $end_of_statement, false, null, true ); if ( false === $ptr ) { // Reached the end of the global statement without finding the variable, // so this must be a local variable. return; } if ( substr( $this->tokens[ $ptr ]['content'], 1 ) === $variable_name ) { break; } } unset( $has_global, $end_of_statement, $ptr ); } } // Still here ? In that case, the variable name should be prefixed. $recorded = MessageHelper::addMessage( $this->phpcsFile, self::ERROR_MSG, $stackPtr, $is_error, 'NonPrefixedVariableFound', array( 'Global variables defined', '$' . $variable_name, ) ); if ( true === $recorded ) { $this->record_potential_prefix_metric( $stackPtr, $variable_name ); } }
Check that defined global variables are prefixed. @since 0.12.0 @since 2.2.0 Added $in_list parameter. @param int $stackPtr The position of the current token in the stack. @param bool $in_list Whether or not this is a variable in a list assignment. Defaults to false. @return int|void Integer stack pointer to skip forward or void to continue normal file processing.
process_variable_assignment
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
MIT
public function process_parameters( $stackPtr, $group_name, $matched_content, $parameters ) { if ( 'define' === $matched_content ) { $target_param = PassedParameters::getParameterFromStack( $parameters, 1, 'constant_name' ); } else { $target_param = WPHookHelper::get_hook_name_param( $matched_content, $parameters ); } if ( false === $target_param ) { return; } $is_error = true; $clean_content = TextStrings::stripQuotes( $target_param['clean'] ); if ( ( 'define' !== $matched_content && isset( $this->allowed_core_hooks[ $clean_content ] ) ) || ( 'define' === $matched_content && isset( $this->allowed_core_constants[ $clean_content ] ) ) ) { return; } if ( $this->is_prefixed( $target_param['start'], $clean_content ) === true ) { return; } else { // This may be a dynamic hook/constant name. $first_non_empty = $this->phpcsFile->findNext( Tokens::$emptyTokens, $target_param['start'], ( $target_param['end'] + 1 ), true ); if ( false === $first_non_empty ) { return; } $first_non_empty_content = TextStrings::stripQuotes( $this->tokens[ $first_non_empty ]['content'] ); // Try again with just the first token if it's a text string. if ( isset( Tokens::$stringTokens[ $this->tokens[ $first_non_empty ]['code'] ] ) && $this->is_prefixed( $target_param['start'], $first_non_empty_content ) === true ) { return; } if ( \T_DOUBLE_QUOTED_STRING === $this->tokens[ $first_non_empty ]['code'] ) { // If the first part of the parameter is a double quoted string, try again with only // the part before the first variable (if any). $exploded = explode( '$', $first_non_empty_content ); $first = rtrim( $exploded[0], '{' ); if ( '' !== $first ) { if ( $this->is_prefixed( $target_param['start'], $first ) === true ) { return; } } else { // Start of hook/constant name is dynamic, throw a warning. $is_error = false; } } elseif ( ! isset( Tokens::$stringTokens[ $this->tokens[ $first_non_empty ]['code'] ] ) ) { // Dynamic hook/constant name, throw a warning. $is_error = false; } } if ( 'define' === $matched_content ) { if ( \defined( '\\' . $clean_content ) ) { // Backfill for PHP native constant. return; } if ( strpos( $clean_content, '\\' ) !== false ) { // Namespaced or unreachable constant. return; } $data = array( 'Global constants defined' ); $error_code = 'NonPrefixedConstantFound'; if ( false === $is_error ) { $error_code = 'VariableConstantNameFound'; } } else { $data = array( 'Hook names invoked' ); $error_code = 'NonPrefixedHooknameFound'; if ( false === $is_error ) { $error_code = 'DynamicHooknameFound'; } } $data[] = $clean_content; $recorded = MessageHelper::addMessage( $this->phpcsFile, self::ERROR_MSG, $first_non_empty, $is_error, $error_code, $data ); if ( true === $recorded ) { $this->record_potential_prefix_metric( $stackPtr, $clean_content ); } }
Process the parameters of a matched function. @since 0.12.0 @param int $stackPtr The position of the current token in the stack. @param string $group_name The name of the group which was matched. @param string $matched_content The token content (function name) which was matched in lowercase. @param array $parameters Array with information about the parameters. @return void
process_parameters
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
MIT
private function is_prefixed( $stackPtr, $name ) { foreach ( $this->validated_prefixes as $prefix ) { if ( stripos( $name, $prefix ) === 0 ) { $this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: allowed prefixes', $prefix ); return true; } } return false; }
Check if a function/class/constant/variable name is prefixed with one of the expected prefixes. @since 0.12.0 @since 0.14.0 Allows for other non-word characters as well as underscores to better support hook names. @since 1.0.0 Does not require a word separator anymore after a prefix. This allows for improved code style independent checking, i.e. allows for camelCase naming and the likes. @since 1.0.1 - Added $stackPtr parameter. - The function now also records metrics about the prefixes encountered. @param int $stackPtr The position of the token to record the metric against. @param string $name Name to check for a prefix. @return bool True when the name is one of the prefixes or starts with an allowed prefix. False otherwise.
is_prefixed
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
MIT
private function variable_prefixed_or_allowed( $stackPtr, $name ) { // Ignore superglobals and WP global variables. if ( Variables::isSuperglobalName( $name ) || WPGlobalVariablesHelper::is_wp_global( $name ) ) { return true; } return $this->is_prefixed( $stackPtr, $name ); }
Check if a variable name might need a prefix. Prefix is not needed for: - superglobals, - WP native globals, - variables which are already prefixed. @since 0.12.0 @since 1.0.1 Added $stackPtr parameter. @since 3.0.0 Renamed from `variable_prefixed_or_whitelisted()` to `variable_prefixed_or_allowed()`. @param int $stackPtr The position of the token to record the metric against. @param string $name Variable name without the dollar sign. @return bool True if the variable name is allowed or already prefixed. False otherwise.
variable_prefixed_or_allowed
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
MIT
private function record_potential_prefix_metric( $stackPtr, $construct_name ) { if ( preg_match( '`^([A-Z]*[a-z0-9]*+)`', ltrim( $construct_name, '\$_' ), $matches ) > 0 && '' !== $matches[1] ) { $this->phpcsFile->recordMetric( $stackPtr, 'Prefix all globals: potential prefixes - start of non-prefixed construct', strtolower( $matches[1] ) ); } }
Record the "potential prefix" metric. @since 1.0.1 @param int $stackPtr The position of the token to record the metric against. @param string $construct_name Name of the global construct to try and distill a potential prefix from. @return void
record_potential_prefix_metric
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/PrefixAllGlobalsSniff.php
MIT
public function register() { return array( \T_FUNCTION ); }
Returns an array of tokens this test wants to listen for. @since 3.0.0 @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php
MIT
public function process_token( $stackPtr ) { if ( DeprecationHelper::is_function_deprecated( $this->phpcsFile, $stackPtr ) === true ) { /* * Deprecated functions don't have to comply with the naming conventions, * otherwise functions deprecated in favour of a function with a compliant * name would still trigger an error. */ return; } $name = FunctionDeclarations::getName( $this->phpcsFile, $stackPtr ); if ( empty( $name ) === true ) { // Live coding or parse error. return; } if ( '' === ltrim( $name, '_' ) ) { // Ignore special functions, like __(). return; } $ooPtr = Scopes::validDirectScope( $this->phpcsFile, $stackPtr, Tokens::$ooScopeTokens ); if ( false === $ooPtr ) { $this->process_function_declaration( $stackPtr, $name ); } else { $this->process_method_declaration( $stackPtr, $name, $ooPtr ); } }
Processes this test, when one of its tokens is encountered. @since 3.0.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/NamingConventions/ValidFunctionNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php
MIT
protected function process_function_declaration( $stackPtr, $functionName ) { // PHP magic functions are exempt from our rules. if ( FunctionDeclarations::isMagicFunctionName( $functionName ) === true ) { return; } // Is the function name prefixed with "__" ? if ( preg_match( '`^__[^_]`', $functionName ) === 1 ) { $error = 'Function name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; $errorData = array( $functionName ); $this->phpcsFile->addError( $error, $stackPtr, 'FunctionDoubleUnderscore', $errorData ); } $suggested_name = SnakeCaseHelper::get_suggestion( $functionName ); if ( $suggested_name !== $functionName ) { $error = 'Function name "%s" is not in snake case format, try "%s"'; $errorData = array( $functionName, $suggested_name, ); $this->phpcsFile->addError( $error, $stackPtr, 'FunctionNameInvalid', $errorData ); } }
Processes a function declaration for a function in the global namespace. @since 0.1.0 @since 3.0.0 Renamed from `processTokenOutsideScope()` to `process_function_declaration()`. Method signature has been changed as well as this method no longer overloads a method from the PEAR sniff which was previously the sniff parent. @param int $stackPtr The position where this token was found. @param string $functionName The name of the function. @return void
process_function_declaration
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php
MIT
protected function process_method_declaration( $stackPtr, $methodName, $currScope ) { if ( \T_ANON_CLASS === $this->tokens[ $currScope ]['code'] ) { $className = '[Anonymous Class]'; } else { $className = ObjectDeclarations::getName( $this->phpcsFile, $currScope ); // PHP4 constructors are allowed to break our rules. if ( NamingConventions::isEqual( $methodName, $className ) === true ) { return; } // PHP4 destructors are allowed to break our rules. if ( NamingConventions::isEqual( $methodName, '_' . $className ) === true ) { return; } } // PHP magic methods are exempt from our rules. if ( FunctionDeclarations::isMagicMethodName( $methodName ) === true ) { return; } $extended = ObjectDeclarations::findExtendedClassName( $this->phpcsFile, $currScope ); $interfaces = ObjectDeclarations::findImplementedInterfaceNames( $this->phpcsFile, $currScope ); // If this is a child class or interface implementation, it may have to use camelCase or double underscores. if ( ! empty( $extended ) || ! empty( $interfaces ) ) { return; } // Is the method name prefixed with "__" ? if ( preg_match( '`^__[^_]`', $methodName ) === 1 ) { $error = 'Method name "%s" is invalid; only PHP magic methods should be prefixed with a double underscore'; $errorData = array( $className . '::' . $methodName ); $this->phpcsFile->addError( $error, $stackPtr, 'MethodDoubleUnderscore', $errorData ); } // Check for all lowercase. $suggested_name = SnakeCaseHelper::get_suggestion( $methodName ); if ( $suggested_name !== $methodName ) { $error = 'Method name "%s" in class %s is not in snake case format, try "%s"'; $errorData = array( $methodName, $className, $suggested_name, ); $this->phpcsFile->addError( $error, $stackPtr, 'MethodNameInvalid', $errorData ); } }
Processes a method declaration. @since 0.1.0 @since 3.0.0 Renamed from `processTokenWithinScope()` to `process_method_declaration()`. Method signature has been changed as well, as this method no longer overloads a method from the PEAR sniff which was previously the sniff parent. @param int $stackPtr The position where this token was found. @param string $methodName The name of the method. @param int $currScope The position of the current scope. @return void
process_method_declaration
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/NamingConventions/ValidFunctionNameSniff.php
MIT
public function register() { return Tokens::$castTokens; }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php
MIT
public function process_token( $stackPtr ) { if ( \T_WHITESPACE !== $this->tokens[ ( $stackPtr - 1 ) ]['code'] && \T_ELLIPSIS !== $this->tokens[ ( $stackPtr - 1 ) ]['code'] ) { $error = 'Expected a space before the type cast open parenthesis; none found'; $fix = $this->phpcsFile->addFixableError( $error, $stackPtr, 'NoSpaceBeforeOpenParenthesis' ); if ( true === $fix ) { $this->phpcsFile->fixer->addContentBefore( $stackPtr, ' ' ); } } }
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/WhiteSpace/CastStructureSpacingSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WhiteSpace/CastStructureSpacingSniff.php
MIT
public function register() { $tokens = parent::register(); $tokens[ \T_BOOLEAN_NOT ] = \T_BOOLEAN_NOT; $tokens += Tokens::$booleanOperators; return $tokens; }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WhiteSpace/OperatorSpacingSniff.php
MIT
public function register() { return array( \T_IF, \T_WHILE, \T_FOREACH, \T_FOR, \T_SWITCH, \T_DO, \T_ELSE, \T_ELSEIF, \T_TRY, \T_CATCH, \T_FINALLY, \T_MATCH, ); }
Returns an array of tokens this test wants to listen for. @return array
register
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WhiteSpace/ControlStructureSpacingSniff.php
MIT
public function process( File $phpcsFile, $stackPtr ) { $tokens = $phpcsFile->getTokens(); $property_adjusted = false; // Check for `::class` and don't ignore new lines in that case. if ( true === $this->ignoreNewlines && \T_DOUBLE_COLON === $tokens[ $stackPtr ]['code'] ) { $next_non_empty = $phpcsFile->findNext( Tokens::$emptyTokens, ( $stackPtr + 1 ), null, true ); if ( \T_STRING === $tokens[ $next_non_empty ]['code'] && 'class' === strtolower( $tokens[ $next_non_empty ]['content'] ) ) { $property_adjusted = true; $this->ignoreNewlines = false; } } $return = parent::process( $phpcsFile, $stackPtr ); if ( true === $property_adjusted ) { $this->ignoreNewlines = true; } return $return; }
Processes this test, when one of its tokens is encountered. @param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned. @param int $stackPtr The position of the current token in the stack passed in $tokens. @return void|int Optionally returns a stack pointer. The sniff will not be called again on the current file until the returned stack pointer is reached.
process
php
WordPress/WordPress-Coding-Standards
WordPress/Sniffs/WhiteSpace/ObjectOperatorSpacingSniff.php
https://github.com/WordPress/WordPress-Coding-Standards/blob/master/WordPress/Sniffs/WhiteSpace/ObjectOperatorSpacingSniff.php
MIT