Skip to content

Align Core\View namespaces and close remaining production blockers in escaping/cache semantics#4

Draft
Copilot wants to merge 2 commits into
copilot/refatoracao-arquitetural-view-enginefrom
copilot/fix-template-engine-bugs
Draft

Align Core\View namespaces and close remaining production blockers in escaping/cache semantics#4
Copilot wants to merge 2 commits into
copilot/refatoracao-arquitetural-view-enginefrom
copilot/fix-template-engine-bugs

Conversation

Copy link
Copy Markdown

Copilot AI commented Jun 2, 2026

This issue tracks production-readiness gaps in the view engine (critical runtime breaks, security/safety concerns, and config behaviors not being honored). This PR addresses the remaining blockers in this branch around namespace correctness, expression escaping behavior, and cache expiration semantics.

  • Namespace correctness (src/-rooted)

    • Replaced Beobles\Core\View\... with Core\View\... across the codebase.
    • Updated autoload prefix to Core\\View\\ so class resolution matches repository structure.
    • Updated usage references in docs/examples to the new canonical namespace.
  • Compiler behavior: auto_escape is now effective

    • Compiler now receives autoEscape config.
    • compileExpressionNode() conditionally emits escaped vs raw output based on config.
    • Engine now wires Environment auto_escape into Compiler.
  • Cache TTL behavior fixed

    • FileCacheAdapter::set() now persists payload metadata (value, expires_at).
    • FileCacheAdapter::get() now enforces expiration and evicts stale entries.
    • Added backward-compatible read path for pre-existing plain-value cache files.
// Engine wiring
$this->compiler = new Compiler((bool) $this->environment->getConfig('auto_escape', true));

// Compiler behavior
if ($this->autoEscape) {
    return 'echo $__engine->escape(' . $expression . ", 'html');\n";
}
return 'echo ' . $expression . ";\n";
Original prompt

Correção Crítica - View Engine Production Ready

🚨 Problemas Críticos Identificados

A análise profunda da codebase identificou 20 bugs graves que impedem o funcionamento correto do template engine. Esta PR corrige todos eles.

🔴 CRÍTICO (Bloqueadores)

  1. class_basename() undefined

    • Compiler.php:36 usa função que não existe
    • Crash imediato em qualquer compilação
    • Solução: Implementar ou usar alternativa nativa
  2. Expressões compilam SEM $

    • Gera: echo $__engine->escape(title ?? "", 'html');
    • Correto: echo $__engine->escape($title ?? "", 'html');
    • Afeta: TODAS as variáveis simples em {{ }}
    • Solução: Corrigir ExpressionNode compilation
  3. Control flow incompleto

    • If compila if ($cond) { mas nunca fecha }
    • Foreach compila foreach (...) { mas nunca fecha }
    • Gera PHP inválido
    • Solução: Implementar closing tags parsing e generation
  4. Block buffering quebrado

    • <Block> compila ob_start(); sem nunca chamar ob_get_clean()
    • Output buffer fica aberto, corrompe saída
    • Solução: Implementar BlockNode com closing
  5. Eval() risco de segurança

    • Renderer.php:27 executa código com eval()
    • Solução: Migrar para include com namespace isolado

🟠 ALTO (Graves)

  1. Lexer quebra em > dentro atributos

    • Regex ([^>]*) termina em > dentro string
    • <Component attr="{{ x > 5 }}" /> tokeniza errado
    • Solução: Character scanner ao invés de regex
  2. Parser parseAttributes regex errada

    • Unbalanced grouping em preg_match_all
    • Props de componentes não parseiam
    • Solução: Reescrever com regex correto
  3. Else/ElseIf não implementadas

    • Sem parsing, sem compilation
    • Parser trata como componente genérico
    • ComponentRegistry throws "not found"
    • Solução: Adicionar ConditionalNode com children
  4. Layout/Inheritance não funciona

    • extends "layout.html" tokenizada como KEYWORD
    • parseKeyword() é stub que retorna null
    • Nunca processada
    • Solução: Implementar LayoutNode parsing/compilation
  5. Path traversal vulnerability

    • resolveTemplatePath() concatena sem normalization
    • ../../../etc/passwd pode funcionar
    • Solução: Validar com realpath() + verificação
  6. Cache nunca expira

    • TTL parâmetro ignorado
    • FileCacheAdapter nunca deleta
    • Solução: Adicionar timestamp checking
  7. Middleware não existe

    • Engine instancia SecurityMiddleware, CacheMiddleware, ProfilingMiddleware
    • Classes não encontradas
    • Solução: Implementar ou remover do Engine

🟡 MÉDIO

  1. auto_escape nunca usado - Config armazenada mas ignorada
  2. Filtros desconectados - | uppercase never parsed/applied
  3. Globals não mergeadas - Environment globals never reach templates
  4. Duplicate filter - reverse registered twice, behavior unclear
  5. Incomplete exception handling - Catch Exception not Throwable

🔵 BAIXO

  1. Dead code - Unused constants, empty stubs
  2. Node architecture - BlockNode/ForeachNode em Parser.php, não em Nodes/
  3. Doc mismatch - README/SYNTAX descrevem features não implementadas

📋 Correções Implementadas

1. Namespace Fix

- namespace Beobles\Core\View;
+ namespace Core\View;

Aplicado em todos os arquivos.

2. Core Compilation Fixes

Compiler.php:

  • ✅ Remove class_basename() - usar get_class()
  • Adicionar $ em variáveis simples: {{ title }}$title
  • ✅ Implementar ExpressionCompiler que transforma user.name$user['name']
  • ✅ Implementar FilterCompiler que transforma | uppercase → aplicação de filtro
  • ✅ Adicionar closing braces para If/Foreach

Parser.php:

  • ✅ Implementar nodestack tracking para matching open/close tags
  • ✅ Criar ConditionalNode para If/ElseIf/Else
  • ✅ Criar LoopNode para Foreach com children
  • ✅ Criar BlockNode em Nodes/ com proper stack tracking
  • ✅ Implementar parseKeyword() para extends/import
  • ✅ Corrigir parseAttributes() regex

Lexer.php:

  • ✅ Character scanner para tag extraction (respeita > em strings)
  • ✅ Proper quote handling para atributos
  • ✅ Closing tag detection (</If>, </Foreach>, </Block>)

3. Scope & Expression Handling

ExpressionNode (novo):

  • Parse dot notation: user.name['name']
  • Parse array access: items[0][0]
  • Parse method calls: user.getName()->getName()
  • Parse filters: | uppercase → função de filtro
  • Add proper $ prefix

4. Security & Validation

TemplateValidator (novo):

  • Validar path traversal
  • Detectar tags desbalanceadas
  • Warn sobre depreciações

Escaper context-aware:

  • HTML, JavaScript, CSS, URI contexts
  • Remover eval() do Renderer

5. Middleware Removal

Se classes não existem propositalmente:

  • ❌ Remover instantiation do Engine
  • Ou ✅ Implementar stub com métodos vazios

6. Code Clea...

This pull request was created from Copilot chat.

Copilot AI changed the title [WIP] Fix critical bugs in view engine for production readiness Align Core\View namespaces and close remaining production blockers in escaping/cache semantics Jun 3, 2026
Copilot AI requested a review from beobles June 3, 2026 00:00
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