PHP code example of bermudaphp / tokenizer

1. Go to this page and download the library: Download bermudaphp/tokenizer library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bermudaphp / tokenizer example snippets




use Bermuda\Tokenizer\Tokenizer;
use Bermuda\Tokenizer\TokenizerInterface;

$tokenizer = new Tokenizer();
$source = ' 
namespace App\Models;

abstract class User {
    // ...
}

interface UserInterface {
    // ...
}
';

// Find all declarations
$declarations = $tokenizer->parse($source);

foreach ($declarations as $classInfo) {
    echo "Found {$classInfo->type}: {$classInfo->fullQualifiedName}\n";
    echo "Namespace: {$classInfo->namespace}\n";
    echo "Class name: {$classInfo->name}\n";
    echo "Abstract: " . ($classInfo->isAbstract ? 'yes' : 'no') . "\n";
    echo "---\n";
}

// Search only classes
$classes = $tokenizer->parse($source, TokenizerInterface::SEARCH_CLASSES);

// Search only interfaces and traits
$interfaces = $tokenizer->parse($source, 
    TokenizerInterface::SEARCH_INTERFACES | TokenizerInterface::SEARCH_TRAITS
);

// Search everything (default)
$all = $tokenizer->parse($source, TokenizerInterface::SEARCH_ALL);

$classInfo->fullQualifiedName;  // string: Fully qualified class name
$classInfo->type;              // string: 'class'|'interface'|'trait'|'enum'
$classInfo->isAbstract;        // bool: Is abstract class
$classInfo->isFinal;           // bool: Is final class
$classInfo->isReadonly;        // bool: Is readonly class

$classInfo->name;              // string: Class name without namespace
$classInfo->namespace;         // string: Namespace without class name
$classInfo->isClass;          // bool: Is this a class?
$classInfo->isInterface;      // bool: Is this an interface?
$classInfo->isTrait;          // bool: Is this a trait?
$classInfo->isEnum;           // bool: Is this an enum?
$classInfo->isConcrete;       // bool: Is concrete class (not abstract)?
$classInfo->reflector;        // ReflectionClass|ReflectionEnum: Reflector instance

$classInfo->exists();         // bool: Does the class exist in memory

$source = file_get_contents('path/to/file.php');
$declarations = $tokenizer->parse($source, TokenizerInterface::SEARCH_CLASSES);

$concreteClasses = array_filter($declarations, fn($info) => $info->isConcrete);

foreach ($declarations as $classInfo) {
    if ($classInfo->exists()) {
        $reflection = $classInfo->reflector;
        echo "Class {$classInfo->name} has " . count($reflection->getMethods()) . " methods\n";
    }
}

$byNamespace = [];
foreach ($declarations as $classInfo) {
    $byNamespace[$classInfo->namespace][] = $classInfo->name;
}