Automattic\WooCommerce\Api\Infrastructure

Main::extract_namespace_from_php_sourceprivate staticWC 1.0

Extract an unbracketed namespace …; declaration from a PHP source fragment.

Uses PHP's tokenizer rather than a regex so the parse isn't fooled by declarations inside heredocs, comments, or bracketed-namespace syntax, and continues to work if the generator's output format changes (e.g. attributes before the declaration, single-line <?php namespace).

Method of the class: Main{}

No Hooks.

Returns

?String. The namespace FQN without leading or trailing separator, or null if none found.

Usage

$result = Main::extract_namespace_from_php_source( $source ): ?string;
$source(string) (required)
PHP source code.

Main::extract_namespace_from_php_source() code WC 10.9.1

private static function extract_namespace_from_php_source( string $source ): ?string {
	$tokens = token_get_all( $source );
	$count  = count( $tokens );
	for ( $i = 0; $i < $count; $i++ ) {
		if ( ! is_array( $tokens[ $i ] ) || T_NAMESPACE !== $tokens[ $i ][0] ) {
			continue;
		}
		$namespace = '';
		for ( $j = $i + 1; $j < $count; $j++ ) {
			$token = $tokens[ $j ];
			if ( is_array( $token ) ) {
				// T_NAME_QUALIFIED and T_NAME_FULLY_QUALIFIED exist on PHP 8+ and already
				// contain the full namespace path; T_STRING / T_NS_SEPARATOR are the
				// equivalent pieces on older versions.
				if ( in_array( $token[0], array( T_STRING, T_NS_SEPARATOR ), true )
					|| ( defined( 'T_NAME_QUALIFIED' ) && T_NAME_QUALIFIED === $token[0] )
					|| ( defined( 'T_NAME_FULLY_QUALIFIED' ) && T_NAME_FULLY_QUALIFIED === $token[0] ) ) {
					$namespace .= $token[1];
					continue;
				}
				if ( T_WHITESPACE === $token[0] ) {
					continue;
				}
			}
			// Single-character tokens `;` (unbracketed namespace) and `{` (bracketed) end the declaration.
			break;
		}
		$namespace = trim( $namespace, '\\' );
		if ( '' !== $namespace ) {
			return $namespace;
		}
	}
	return null;
}