PHPackages                             baraja-core/class-map-generator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. baraja-core/class-map-generator

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

baraja-core/class-map-generator
===============================

Find all classes in specific directory.

v1.1.0(5y ago)115PHPPHP ^7.4 || ^8.0CI passing

Since Dec 31Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/baraja-core/class-map-generator)[ Packagist](https://packagist.org/packages/baraja-core/class-map-generator)[ Docs](https://github.com/baraja-core/class-map-generator)[ RSS](/packages/baraja-core-class-map-generator/feed)WikiDiscussions master Synced today

READMEChangelog (3)Dependencies (4)Versions (7)Used By (0)

PHP Class Map Generator
=======================

[](#php-class-map-generator)

[![Integrity check](https://github.com/baraja-core/class-map-generator/workflows/Integrity%20check/badge.svg)](https://github.com/baraja-core/class-map-generator/workflows/Integrity%20check/badge.svg)

A lightweight PHP library for scanning directories and generating a complete map of all PHP classes, interfaces, and traits with their corresponding file paths.

🎯 Key Features
--------------

[](#-key-features)

- **Recursive directory scanning** - Automatically traverses all subdirectories to find PHP files
- **Token-based parsing** - Uses PHP's native `token_get_all()` for reliable class detection
- **Full namespace support** - Correctly resolves fully qualified class names with namespaces
- **Supports all class types** - Detects classes, interfaces, and traits
- **Memory efficient** - Includes garbage collection optimization for large codebases
- **Zero dependencies** - Pure PHP implementation with no external requirements
- **PHP 8.0+ compatible** - Built for modern PHP applications

🏗️ Architecture
---------------

[](#️-architecture)

The library consists of a single, focused class that handles all scanning and parsing logic:

```
┌─────────────────────────────────────────────────────────────────┐
│                     ClassMapGenerator                           │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌─────────────────┐    ┌──────────────────┐    ┌───────────┐  │
│  │   createMap()   │───►│  Directory Scan  │───►│  Output   │  │
│  │   (public)      │    │  (recursive)     │    │  Map      │  │
│  └─────────────────┘    └────────┬─────────┘    └───────────┘  │
│                                  │                              │
│                                  ▼                              │
│                         ┌──────────────────┐                    │
│                         │  findClasses()   │                    │
│                         │  (private)       │                    │
│                         └────────┬─────────┘                    │
│                                  │                              │
│                                  ▼                              │
│                         ┌──────────────────┐                    │
│                         │  Token Parser    │                    │
│                         │  - T_NAMESPACE   │                    │
│                         │  - T_CLASS       │                    │
│                         │  - T_INTERFACE   │                    │
│                         │  - T_TRAIT       │                    │
│                         └──────────────────┘                    │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

```

### How It Works

[](#how-it-works)

1. **Directory Iteration**: The `createMap()` method uses `RecursiveDirectoryIterator` to traverse all files in the specified directory and its subdirectories.
2. **File Filtering**: Only files with the `.php` extension are processed, skipping all other file types.
3. **Token Parsing**: Each PHP file is read and parsed using PHP's `token_get_all()` function, which breaks down the source code into tokens.
4. **Namespace Detection**: The parser tracks `T_NAMESPACE` tokens to build the current namespace context for class resolution.
5. **Class Detection**: When `T_CLASS`, `T_INTERFACE`, or `T_TRAIT` tokens are encountered, the parser extracts the class name and combines it with the current namespace.
6. **::class Constant Handling**: The parser intelligently skips `::class` constant usage (e.g., `SomeClass::class`) to avoid false positives.
7. **Memory Management**: After processing each file, `gc_mem_caches()` is called to address a known PHP memory issue with `token_get_all()`.

📦 Installation
--------------

[](#-installation)

It's best to use [Composer](https://getcomposer.org) for installation, and you can also find the package on [Packagist](https://packagist.org/packages/baraja-core/class-map-generator) and [GitHub](https://github.com/baraja-core/class-map-generator).

To install, simply use the command:

```
$ composer require baraja-core/class-map-generator
```

You can use the package manually by creating an instance of the internal classes, or register a DIC extension to link the services directly to the Nette Framework.

### Requirements

[](#requirements)

- PHP 8.0 or higher
- No external dependencies

🚀 Usage
-------

[](#-usage)

### Basic Usage

[](#basic-usage)

Generate a class map for a directory:

```
use Baraja\ClassMapGenerator\ClassMapGenerator;

$map = ClassMapGenerator::createMap(__DIR__ . '/src');
```

### Return Value

[](#return-value)

The `createMap()` method returns an associative array where:

- **Keys** are fully qualified class names (including namespace)
- **Values** are absolute file paths

```
// Example output:
[
    'App\Controllers\HomeController' => '/var/www/project/src/Controllers/HomeController.php',
    'App\Models\User' => '/var/www/project/src/Models/User.php',
    'App\Services\AuthService' => '/var/www/project/src/Services/AuthService.php',
]
```

### Practical Examples

[](#practical-examples)

#### Finding a Specific Class File

[](#finding-a-specific-class-file)

```
$map = ClassMapGenerator::createMap(__DIR__ . '/src');

if (isset($map['App\Services\PaymentService'])) {
    $filePath = $map['App\Services\PaymentService'];
    echo "PaymentService is located at: {$filePath}";
}
```

#### Listing All Classes in a Namespace

[](#listing-all-classes-in-a-namespace)

```
$map = ClassMapGenerator::createMap(__DIR__ . '/src');

$controllers = array_filter(
    $map,
    fn($class) => str_starts_with($class, 'App\\Controllers\\'),
    ARRAY_FILTER_USE_KEY
);

foreach ($controllers as $className => $filePath) {
    echo "{$className}\n";
}
```

#### Building an Autoloader

[](#building-an-autoloader)

```
$map = ClassMapGenerator::createMap(__DIR__ . '/src');

spl_autoload_register(function (string $class) use ($map): void {
    if (isset($map[$class])) {
        require_once $map[$class];
    }
});
```

#### Caching the Class Map

[](#caching-the-class-map)

For performance optimization in production environments:

```
$cacheFile = __DIR__ . '/cache/classmap.php';

if (file_exists($cacheFile)) {
    $map = require $cacheFile;
} else {
    $map = ClassMapGenerator::createMap(__DIR__ . '/src');

    file_put_contents(
        $cacheFile,
        '
