# twigphp/twig architecture

> Architecture diagram of the GitHub repository twigphp/twig, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2025-03-29). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/twigphp/twig
- Repository: https://github.com/twigphp/twig

## Overview

##### Main Components
- Environment & Configuration: Begin by identifying the central Environment class (src/Environment.php) that sets up the runtime. This component configures loaders, caches, extensions, and error handling.
- Template Loader: Capture the Loader components (found in src/Loader/) such as FilesystemLoader, ArrayLoader, ChainLoader, etc., which are responsible for loading templates from various sources.
- Parser Infrastructure: Show the Lexer, Parser, and Expression Parser areas:
– Lexer (src/Lexer.php): Converts the raw template text into a stream of tokens.
– Parser (src/Parser.php) and ExpressionParser (src/ExpressionParser/…): Process these tokens to build an Abstract Syntax Tree (AST) represented by Node objects.
- AST / Compilation Components: Illustrate the core compiler (src/Compiler.php) that transforms the parsed AST into executable PHP code. Include relevant Node types (src/Node/*) representing different template language constructs (e.g., BlockNode, IfNode, ForNode) and expression sub-components.
- Runtime & Rendering: Include the Template (src/Template.php) and TemplateWrapper classes that manage the rendering process by using both compiled templates and runtime helpers.
- Cache Mechanism: Show how caching is abstracted among different types from src/Cache/ – for example, FilesystemCache, ReadOnlyFilesystemCache, ChainCache – to store compiled templates or intermediate results.
- Extensions & Plugins: Represent the modular extension system (src/Extension/) that allows users or built-in features (CoreExtension, EscaperExtension, DebugExtension, etc.) to extend the template engine’s capabilities. Also note the attribute-based auto-loading of Twig filters/functions (src/Attribute/*).
- Error Handling & Sandbox: Outline the error classes (src/Error/*) and the sandbox (src/Sandbox/) that ensure secure execution when running user-submitted templates.
- Additional Components:
– Highlight the runtime loader components (src/RuntimeLoader/) which dynamically resolve helper functions.
– Add the profiler (src/Profiler/) that collects rendering or compilation statistics.

##### Relationships and Interactions
- Data Flow Example: Begin at the Environment level where a template is requested. Then the Loader fetches the template, the Lexer tokenizes it, the Parser builds an AST from these tokens, and the Compiler converts the AST into PHP code. During rendering, the Template (with help from runtime, extensions, and cache) produces the final HTML output.
- Interaction with Extensions: Demonstrate how extensions (which can be third-party and are part of the “extra/” folders) plug into the core pipeline to modify parsing, filtering, or function execution.
- Caching Integration: Show how caching is used right after compilation to store generated code and later reused during template rendering.

##### Architectural Patterns and Design Principles
- Modularity & Extensibility: Emphasize how the project supports multiple loaders, extensions, and runtime loaders that allow for high configurability.
- Separation of Concerns: Clearly separate the concerns such as parsing, compiling, and rendering. Each component has its own dedicated directory and set of responsibilities.
- Interface-Based Design: Identify key interfaces (e.g., LoaderInterface, CacheInterface, ExtensionInterface) that allow swapping implementations seamlessly.
- Test-Driven Approach: Although not part of runtime architecture, note the extensive tests (in tests/) that verify each component, ensuring reliability and stability.

## Diagram (Mermaid)

```mermaid
flowchart TD
    %% Main Pipeline
    subgraph "Template Processing Pipeline"
        E["Environment & Configuration"]:::environment
        subgraph "Template Loader"
            FL["FilesystemLoader"]:::loader
            AL["ArrayLoader"]:::loader
            CL["ChainLoader"]:::loader
        end
        L["Lexer"]:::parser
        P["Parser"]:::parser
        EP["ExpressionParser"]:::parser
        subgraph "AST & Compilation"
            AST["AST (Node Tree)"]:::ast
            C["Compiler"]:::compiler
        end
        Cache["Cache Mechanism"]:::cache
        subgraph "Runtime & Rendering"
            T["Template"]:::runtime
            TW["TemplateWrapper"]:::runtime
        end
        O["Final Output"]:::output
    end

    %% Main Pipeline Connections
    E -->|"configures"| FL
    E -->|"configures"| AL
    E -->|"configures"| CL
    FL -->|"loads"| L
    AL -->|"loads"| L
    CL -->|"loads"| L
    L -->|"tokenizes"| P
    P -->|"parses"| EP
    EP -->|"buildsAST"| AST
    AST -->|"compiles"| C
    C -->|"storesCode"| Cache
    Cache -->|"retrieves"| T
    T -->|"wraps"| TW
    TW -->|"renders"| O

    %% Supporting Components
    subgraph "Extensions & Plugins"
        Ext["Extensions & Attribute Autoload"]:::extensions
    end
    subgraph "Error Handling & Sandbox"
        Err["Error & Sandbox Handlers"]:::error
    end
    subgraph "Runtime Loader & Profiler"
        RL["Runtime Loader"]:::runtime_loader
        Prof["Profiler"]:::profiler
    end

    %% Integration Arrows
    E ---|"loadsExtensions"| Ext
    P ---|"propagatesError"| Err
    T ---|"resolvesRuntime"| RL
    T ---|"tracksPerformance"| Prof

    %% Click Events
    click E "https://github.com/twigphp/twig/blob/3.x/src/Environment.php"
    click FL "https://github.com/twigphp/twig/blob/3.x/src/Loader/FilesystemLoader.php"
    click AL "https://github.com/twigphp/twig/blob/3.x/src/Loader/ArrayLoader.php"
    click CL "https://github.com/twigphp/twig/blob/3.x/src/Loader/ChainLoader.php"
    click L "https://github.com/twigphp/twig/blob/3.x/src/Lexer.php"
    click P "https://github.com/twigphp/twig/blob/3.x/src/Parser.php"
    click EP "https://github.com/twigphp/twig/tree/3.x/src/ExpressionParser/"
    click C "https://github.com/twigphp/twig/blob/3.x/src/Compiler.php"
    click AST "https://github.com/twigphp/twig/tree/3.x/src/Node/"
    click T "https://github.com/twigphp/twig/blob/3.x/src/Template.php"
    click TW "https://github.com/twigphp/twig/blob/3.x/src/TemplateWrapper.php"
    click Cache "https://github.com/twigphp/twig/tree/3.x/src/Cache/"
    click Ext "https://github.com/twigphp/twig/tree/3.x/src/Extension/"
    click Ext "https://github.com/twigphp/twig/tree/3.x/src/Attribute/"
    click Err "https://github.com/twigphp/twig/tree/3.x/src/Error/"
    click Err "https://github.com/twigphp/twig/tree/3.x/src/Sandbox/"
    click RL "https://github.com/twigphp/twig/tree/3.x/src/RuntimeLoader/"
    click Prof "https://github.com/twigphp/twig/tree/3.x/src/Profiler/"

    %% Styles
    classDef environment fill:#FFEEAD,stroke:#DAA520,stroke-width:2px;
    classDef loader fill:#B0E0E6,stroke:#4682B4,stroke-width:2px;
    classDef parser fill:#98FB98,stroke:#006400,stroke-width:2px;
    classDef ast fill:#FAD6A5,stroke:#CD853F,stroke-width:2px;
    classDef compiler fill:#FFC0CB,stroke:#FF69B4,stroke-width:2px;
    classDef cache fill:#D1C0E0,stroke:#9370DB,stroke-width:2px;
    classDef runtime fill:#C8E6C9,stroke:#2E7D32,stroke-width:2px;
    classDef output fill:#F0F0F0,stroke:#808080,stroke-width:2px;
    classDef extensions fill:#E3F2FD,stroke:#2196F3,stroke-width:2px;
    classDef error fill:#FFCDD2,stroke:#B71C1C,stroke-width:2px;
    classDef runtime_loader fill:#FFE0B2,stroke:#FB8C00,stroke-width:2px;
    classDef profiler fill:#E1BEE7,stroke:#8E24AA,stroke-width:2px;
```
