Neos\Flow\Utility\PhpAnalyzer::extractNamespace PHP Method

extractNamespace() public method

Extracts the PHP namespace from the given PHP code
public extractNamespace ( ) : string
return string the PHP namespace in the form "Some\Namespace" (w/o leading backslash) - or NULL if no namespace modifier was found
    public function extractNamespace()
    {
        $namespaceParts = [];
        $tokens = token_get_all($this->phpCode);
        $numberOfTokens = count($tokens);
        for ($i = 0; $i < $numberOfTokens; $i++) {
            $token = $tokens[$i];
            if (is_string($token) || $token[0] !== T_NAMESPACE) {
                continue;
            }
            for (++$i; $i < $numberOfTokens; $i++) {
                $token = $tokens[$i];
                if (is_string($token)) {
                    break;
                }
                list($type, $value) = $token;
                if ($type === T_STRING) {
                    $namespaceParts[] = $value;
                    continue;
                }
                if ($type !== T_NS_SEPARATOR && $type !== T_WHITESPACE) {
                    break;
                }
            }
            break;
        }
        if ($namespaceParts === []) {
            return null;
        }
        return implode('\\', $namespaceParts);
    }

Usage Example

 /**
  * @param string $phpCode
  * @param string $namespace
  * @test
  * @dataProvider sampleClasses
  */
 public function extractNamespaceTests($phpCode, $namespace)
 {
     $phpAnalyzer = new PhpAnalyzer($phpCode);
     $this->assertSame($namespace, $phpAnalyzer->extractNamespace());
 }