Skip to content

Refactor View Engine into modular pipeline with typed AST, directives, scoped runtime, and secure rendering#2

Draft
Copilot wants to merge 3 commits into
mainfrom
copilot/refatoracao-arquitetural-view-engine
Draft

Refactor View Engine into modular pipeline with typed AST, directives, scoped runtime, and secure rendering#2
Copilot wants to merge 3 commits into
mainfrom
copilot/refatoracao-arquitetural-view-engine

Conversation

Copy link
Copy Markdown

Copilot AI commented Jun 2, 2026

This PR reshapes the current View engine into a clearer, extensible architecture without changing the public usage model (Engine orchestration and render flow). It introduces explicit boundaries across parse/compile/runtime concerns while adding safer rendering and stronger template semantics.

  • Architecture split: Lexer → Parser → Compiler → Renderer

    • Engine now orchestrates specialized modules instead of embedding parsing/compilation concerns.
    • Added TemplateResolver, LayoutManager, TemplateValidator, MiddlewarePipeline, CacheKey, and FileWatcher to isolate core responsibilities.
  • AST foundation and node hierarchy

    • Introduced AbstractNode + upgraded NodeInterface to a compile-capable contract.
    • Added/updated node set: TextNode, ExpressionNode, RawNode, ComponentNode, IfNode, ForeachNode, BlockNode, SetNode, IncludeNode.
    • Compiler now delegates to node-driven compilation ($node->compile(...)), enabling custom node extensibility.
  • Directive system and parser validation

    • Added DirectiveRegistry with directives for If, Foreach, Block, Set, Include.
    • Parser now handles nested control flow with structural validation (unexpected/missing close tags, required attributes, control-branch boundaries).
  • Runtime scope, expressions, and filters

    • Added scoped variable stack (Scope, ScopeStack, Variable) and path resolution for dot notation.
    • Compiler expression pipeline now supports chained filters and scoped value resolution.
    • Refactored filter organization into domain groups (StringFilters, NumberFilters, DateFilters, ArrayFilters) via FilterRegistry.
  • Security and robustness

    • Replaced runtime eval with compiled-file include execution in Renderer.
    • Added context-aware escaping primitives (Escaper, HtmlEscaper, JavaScriptEscaper, UriEscaper).
    • Added exception structure extensions (CompileException, RuntimeException, CircularReferenceException) and debug scaffolding (SourceMap, RuntimeContext, TemplateDebugger, ErrorFormatter).
  • Docs alignment

    • Updated project structure section in README.md to reflect the new modular layout.
// Node-driven compilation contract
interface NodeInterface
{
    public function compile(Compiler $compiler): string;
    public function accept(callable $visitor);
    public function getLine(): int;
    public function getColumn(): int;
}
Original prompt

Refatoração Arquitetural - View Engine de Maestria

Seu PHP Template Engine tem uma base sólida, mas precisa de melhorias estruturais para ser um sistema robusto, extensível e profissional. Esta PR implementa as seguintes melhorias sem quebrar compatibilidade.

🎯 Objetivos

  1. Separação de Responsabilidades Clara

    • Node hierarchy com interface abstrata
    • Lexer → Parser → Compiler com fluxo definido
    • ScopeManager para contexto de variáveis
    • TemplateResolver para resolução de caminhos
  2. Robustez & Segurança

    • ValidatorNode para validação em tempo de parse
    • LayoutManager para herança de templates
    • Escape context-aware (HTML, JavaScript, CSS, URI)
    • Error tracking com linhas e colunas
  3. Performance & Caching Inteligente

    • FileWatcher para cache invalidation
    • Compiled code optimization
    • Asset versioning
    • Memory-efficient rendering
  4. Extensibilidade

    • DirectiveRegistry abstrato
    • FilterChain pattern
    • CustomNode pattern
    • MiddlewarePipeline
  5. Developer Experience

    • SourceMap para debugging
    • RuntimeContext para inspeção
    • TemplateDebugger com profiling
    • Better error messages com contexto

📁 Nova Estrutura

src/Core/View/
├── Engine.php                      # Orquestrador (refatorado)
├── Compiler.php                    # Compilador (refatorado)
├── Parser.php                      # Parser (refatorado)
├── Lexer.php                       # Lexer (refatorado)
├── Renderer.php                    # Renderizador (refatorado)
│
├── Abstract/
│   ├── AbstractNode.php            # Base para todos nodes
│   ├── AbstractDirective.php       # Base para directives
│   ├── AbstractFilter.php          # Base para filtros
│   └── AbstractMiddleware.php      # Base para middleware
│
├── Nodes/
│   ├── TextNode.php                # Nó de texto
│   ├── ExpressionNode.php          # Nó de expressão {{ }}
│   ├── RawNode.php                 # Nó raw {! !}
│   ├── ComponentNode.php           # Nó de componente
│   ├── IfNode.php                  # Nó If/ElseIf/Else
│   ├── ForeachNode.php             # Nó Foreach
│   ├── BlockNode.php               # Nó Block (herança)
│   ├── SetNode.php                 # Nó Set (variáveis)
│   └── IncludeNode.php             # Nó Include
│
├── Directives/
│   ├── IfDirective.php
│   ├── ForeachDirective.php
│   ├── BlockDirective.php
│   ├── SetDirective.php
│   ├── IncludeDirective.php
│   └── DirectiveRegistry.php       # Registry pattern
│
├── Filters/
│   ├── StringFilters.php
│   ├── NumberFilters.php
│   ├── DateFilters.php
│   ├── ArrayFilters.php
│   └── FilterRegistry.php          # Registry pattern
│
├── Scope/
│   ├── Scope.php                   # Gerenciamento de escopo
│   ├── ScopeStack.php              # Pilha de escopos
│   └── Variable.php                # Representação de variável
│
├── Cache/
│   ├── CacheManager.php
│   ├── FileCacheAdapter.php
│   ├── CacheKey.php
│   └── FileWatcher.php             # Watch de mudanças
│
├── Components/
│   ├── ComponentRegistry.php
│   ├── ComponentResolver.php
│   └── ComponentCache.php
│
├── Layout/
│   ├── LayoutManager.php           # Gerencia herança
│   ├── BlockStack.php              # Pilha de blocos
│   └── LayoutResolver.php
│
├── Debug/
│   ├── SourceMap.php               # Map para erro → linha original
│   ├── RuntimeContext.php          # Contexto em runtime
│   ├── TemplateDebugger.php        # Profiling
│   └── ErrorFormatter.php          # Formatação de erros
│
├── Middleware/
│   ├── SecurityMiddleware.php      # XSS, injection
│   ├── CacheMiddleware.php
│   ├── ProfilingMiddleware.php
│   └── MiddlewarePipeline.php
│
├── Validation/
│   ├── TemplateValidator.php       # Validação de templates
│   └── SyntaxValidator.php         # Validação de sintaxe
│
├── Escape/
│   ├── Escaper.php                 # Context-aware escaping
│   ├── HtmlEscaper.php
│   ├── JavaScriptEscaper.php
│   └── UriEscaper.php
│
└── Exceptions/
    ├── ViewException.php
    ├── SyntaxException.php
    ├── CompileException.php
    ├── RuntimeException.php
    └── CircularReferenceException.php

🔧 Implementações Chave

1. AbstractNode (Base para todos os nós)

abstract class AbstractNode
{
    protected int $line;
    protected int $column;
    protected array $metadata = [];
    
    abstract public function compile(Compiler $compiler): string;
    abstract public function accept(NodeVisitor $visitor);
}

2. ScopeManager (Contexto de variáveis)

Gerencia escopo local/global com pilha de escopos

3. LayoutManager (Herança de templates)

Implementa extends e <Block> corretamente

4. DirectiveRegistry

Padrão Registry para directives customizadas

5. ContextAwareEscaper

Escape inteligente baseado em contexto (HTML, JS, CSS, URI)

6. SourceMap

Mapeia erro no código compilado para linha original

7. MiddlewarePipeline

Permite interceptação de requests/responses

📊 Benefíci...

This pull request was created from Copilot chat.

Copilot AI changed the title [WIP] Refactor architectural improvements for master view engine Refactor View Engine into modular pipeline with typed AST, directives, scoped runtime, and secure rendering Jun 2, 2026
Copilot AI requested a review from beobles June 2, 2026 20:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants