Skip to content

Commit 34c6e54

Browse files
committed
fix: Corrigir incompatibilidades para release v1.1.0
- Remover adição automática de trailing slash em Request::pathCallable - Adicionar método Request::getIp() para suporte ao RateLimiter - Corrigir Router::clear() para limpar todos os caches - Atualizar testes para refletir novos comportamentos - Marcar testes de stress como skipped (dependentes do ambiente)
1 parent 42718ed commit 34c6e54

20 files changed

+933
-112
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,3 +259,4 @@ TODO.md
259259
NOTES.md
260260
scratch/
261261
benchmarks/**/*.json
262+
CLAUDE.md

CLAUDE.md

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
# CLAUDE.md
2+
3+
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4+
5+
## Repository Overview
6+
7+
PivotPHP Core is a high-performance PHP microframework inspired by Express.js, designed for building APIs and web applications. Current version: 1.1.0 (High-Performance Edition).
8+
9+
## Essential Commands
10+
11+
### Development Workflow
12+
```bash
13+
# Run comprehensive validation (includes all checks)
14+
./scripts/validate_all.sh
15+
16+
# Quality checks
17+
composer quality:check # Run all quality checks
18+
composer phpstan # Static analysis (Level 9)
19+
composer cs:check # PSR-12 code style check
20+
composer cs:fix # Auto-fix code style issues
21+
composer audit # Check for security vulnerabilities
22+
23+
# Testing
24+
composer test # Run all tests
25+
composer test:security # Security-specific tests
26+
composer test:auth # Authentication tests
27+
composer benchmark # Performance benchmarks
28+
29+
# Run a single test file
30+
vendor/bin/phpunit tests/Core/ApplicationTest.php
31+
32+
# Run tests with specific group
33+
vendor/bin/phpunit --group stress
34+
vendor/bin/phpunit --exclude-group stress,integration
35+
36+
# Pre-commit and release
37+
./scripts/pre-commit # Run pre-commit validations
38+
./scripts/prepare_release.sh 1.1.0 # Prepare release for version 1.1.0
39+
./scripts/release.sh # Create release after preparation
40+
```
41+
42+
### Running Examples
43+
```bash
44+
composer examples:basic # Basic framework usage
45+
composer examples:auth # Authentication example
46+
composer examples:middleware # Middleware example
47+
```
48+
49+
### v1.1.0 High-Performance Features
50+
```php
51+
// Enable high-performance mode
52+
use PivotPHP\Core\Performance\HighPerformanceMode;
53+
HighPerformanceMode::enable(HighPerformanceMode::PROFILE_HIGH);
54+
55+
// Console commands for monitoring
56+
php bin/console pool:stats # Real-time pool monitoring
57+
```
58+
59+
## Code Architecture
60+
61+
### Core Framework Structure
62+
- **Service Provider Pattern**: All major components are registered via service providers in `src/Providers/`
63+
- **PSR Standards**: Strict PSR-7 (HTTP messages), PSR-15 (middleware), PSR-12 (coding style) compliance
64+
- **Container**: Dependency injection container at the heart of the framework (`src/Core/Container.php`)
65+
- **Event-Driven**: Event dispatcher with hooks system for extensibility
66+
67+
### Key Components
68+
1. **Application Core** (`src/Core/Application.php`): Main application class that bootstraps the framework
69+
- Version constant: `Application::VERSION`
70+
- Middleware aliases mapping for v1.1.0 features
71+
72+
2. **Router** (`src/Routing/Router.php`): High-performance routing with middleware support
73+
- Supports regex constraints: `/users/:id<\d+>`
74+
- Predefined shortcuts: `slug`, `uuid`, `date`, etc.
75+
76+
3. **Middleware Pipeline** (`src/Middleware/`): PSR-15 compliant middleware system
77+
- v1.1.0 additions: LoadShedder, CircuitBreaker
78+
79+
4. **HTTP Layer** (`src/Http/`): PSR-7 hybrid implementation
80+
- Express.js style API with PSR-7 compliance
81+
- Object pooling via `Psr7Pool` and `OptimizedHttpFactory`
82+
83+
5. **v1.1.0 Performance Components**:
84+
- `DynamicPool`: Auto-scaling object pools
85+
- `MemoryManager`: Adaptive memory management
86+
- `PerformanceMonitor`: Real-time metrics
87+
- `DistributedPoolManager`: Multi-instance coordination
88+
89+
### Request/Response Hybrid Design
90+
The framework uses a hybrid approach for PSR-7 compatibility:
91+
- `Request` class implements `ServerRequestInterface` while maintaining Express.js methods
92+
- Legacy `getBody()` renamed to `getBodyAsStdClass()` for backward compatibility
93+
- PSR-7 objects are lazy-loaded for performance
94+
95+
### Testing Approach
96+
- Tests organized by domain in `tests/` directory
97+
- Each major component has its own test suite
98+
- Integration tests verify component interaction
99+
- Use PHPUnit assertions and follow existing test patterns
100+
- v1.1.0 tests in `tests/Integration/V11ComponentsTest.php` and `tests/Stress/`
101+
102+
### Code Style Requirements
103+
- PHP 8.1+ features are used throughout
104+
- Strict typing is enforced
105+
- PHPStan Level 9 must pass
106+
- PSR-12 coding standard via PHP_CodeSniffer
107+
- All new code must include proper type declarations
108+
109+
### Performance Considerations
110+
- Framework optimized for high throughput (2.57M ops/sec for CORS)
111+
- v1.1.0 achieves 25x faster Request/Response creation with pooling
112+
- Benchmark any performance-critical changes using `composer benchmark`
113+
- Avoid unnecessary object creation in hot paths
114+
- Use lazy loading for optional dependencies
115+
116+
## Development Workflow
117+
118+
1. Before committing, run `./scripts/pre-commit` or `./scripts/validate_all.sh`
119+
2. All tests must pass before pushing changes
120+
3. Static analysis must pass at Level 9
121+
4. Code style must comply with PSR-12
122+
5. For releases, use `./scripts/prepare_release.sh` followed by `./scripts/release.sh`
123+
124+
## Current Version Status
125+
126+
- **Current Version**: 1.1.0 (High-Performance Edition)
127+
- **Previous Stable**: 1.0.1 (PSR-7 Hybrid Support)
128+
- **Tests Status**: 315/332 passing (95% success rate)
129+
- **New Features**: High-performance mode, dynamic pooling, circuit breaker, load shedding
130+
131+
## Important Notes
132+
133+
- The framework prioritizes performance, security, and developer experience
134+
- All HTTP components are PSR-7/PSR-15 compliant
135+
- Service providers are the primary extension mechanism
136+
- The event system allows for deep customization without modifying core code
137+
- Documentation updates should be made in the `/docs` directory when adding features
138+
- v1.1.0 features are opt-in and don't affect default behavior

README.md

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
44
[![PHP Version](https://img.shields.io/badge/PHP-8.1%2B-blue.svg)](https://php.net)
5+
[![Latest Stable Version](https://poser.pugx.org/pivotphp/core/v/stable)](https://packagist.org/packages/pivotphp/core)
6+
[![Total Downloads](https://poser.pugx.org/pivotphp/core/downloads)](https://packagist.org/packages/pivotphp/core)
57
[![PHPStan Level](https://img.shields.io/badge/PHPStan-Level%209-brightgreen.svg)](https://phpstan.org/)
68
[![PSR-12](https://img.shields.io/badge/PSR--12%20%2F%20PSR--15-compliant-brightgreen)](https://www.php-fig.org/psr/psr-12/)
79
[![GitHub Issues](https://img.shields.io/github/issues/PivotPHP/pivotphp-core)](https://github.com/PivotPHP/pivotphp-core/issues)
@@ -186,6 +188,116 @@ Principais links:
186188

187189
---
188190

191+
## 🧩 Extensões Oficiais
192+
193+
O PivotPHP possui um ecossistema rico de extensões que adicionam funcionalidades poderosas ao framework:
194+
195+
### 🗄️ Cycle ORM Extension
196+
```bash
197+
composer require pivotphp/cycle-orm
198+
```
199+
200+
Integração completa com Cycle ORM para gerenciamento de banco de dados:
201+
- Migrações automáticas
202+
- Repositórios com query builder
203+
- Relacionamentos (HasOne, HasMany, BelongsTo, ManyToMany)
204+
- Suporte a transações
205+
- Múltiplas conexões de banco
206+
207+
```php
208+
use PivotPHP\CycleORM\CycleServiceProvider;
209+
210+
$app->register(new CycleServiceProvider([
211+
'dbal' => [
212+
'databases' => [
213+
'default' => ['connection' => 'mysql://user:pass@localhost/db']
214+
]
215+
]
216+
]));
217+
218+
// Usar em rotas
219+
$app->get('/users', function($req, $res) use ($container) {
220+
$users = $container->get('orm')
221+
->getRepository(User::class)
222+
->findAll();
223+
$res->json($users);
224+
});
225+
```
226+
227+
### ⚡ ReactPHP Extension
228+
```bash
229+
composer require pivotphp/reactphp
230+
```
231+
232+
Runtime assíncrono para aplicações de longa duração:
233+
- Servidor HTTP contínuo sem reinicializações
234+
- Suporte a WebSocket (em breve)
235+
- Operações I/O assíncronas
236+
- Arquitetura orientada a eventos
237+
- Timers e tarefas periódicas
238+
239+
```php
240+
use PivotPHP\ReactPHP\ReactServiceProvider;
241+
242+
$app->register(new ReactServiceProvider([
243+
'server' => [
244+
'host' => '0.0.0.0',
245+
'port' => 8080
246+
]
247+
]));
248+
249+
// Executar servidor assíncrono
250+
$app->runAsync(); // Em vez de $app->run()
251+
```
252+
253+
### 🌐 Extensões da Comunidade
254+
255+
A comunidade PivotPHP está crescendo! Estamos animados para ver as extensões que serão criadas.
256+
257+
**Extensões Planejadas:**
258+
- Gerador de documentação OpenAPI/Swagger
259+
- Sistema de filas para jobs em background
260+
- Cache avançado com múltiplos drivers
261+
- Abstração para envio de emails
262+
- Servidor WebSocket
263+
- Suporte GraphQL
264+
265+
### 🔧 Criando Sua Própria Extensão
266+
267+
```php
268+
namespace MeuProjeto\Providers;
269+
270+
use PivotPHP\Core\Providers\ServiceProvider;
271+
272+
class MinhaExtensaoServiceProvider extends ServiceProvider
273+
{
274+
public function register(): void
275+
{
276+
// Registrar serviços
277+
$this->container->singleton('meu.servico', function() {
278+
return new MeuServico();
279+
});
280+
}
281+
282+
public function boot(): void
283+
{
284+
// Lógica de inicialização
285+
$this->app->get('/minha-rota', function($req, $res) {
286+
$res->json(['extensao' => 'ativa']);
287+
});
288+
}
289+
}
290+
```
291+
292+
**Diretrizes para Extensões:**
293+
1. Seguir convenção de nome: `pivotphp-{nome}`
294+
2. Fornecer ServiceProvider estendendo `ServiceProvider`
295+
3. Incluir testes de integração
296+
4. Documentar no `/docs/extensions/`
297+
5. Publicar no Packagist com tag `pivotphp-extension`
298+
299+
---
300+
189301
## 🔄 Compatibilidade PSR-7
190302

191303
O PivotPHP oferece suporte duplo para PSR-7, permitindo uso com projetos modernos (v2.x) e compatibilidade com ReactPHP (v1.x).
@@ -217,6 +329,14 @@ Veja a [documentação completa sobre PSR-7](docs/technical/compatibility/psr7-d
217329

218330
---
219331

332+
## 🤝 Comunidade
333+
334+
Junte-se à nossa comunidade crescente de desenvolvedores:
335+
336+
- **Discord**: [Entre no nosso servidor](https://discord.gg/DMtxsP7z) - Obtenha ajuda, compartilhe ideias e conecte-se com outros desenvolvedores
337+
- **GitHub Discussions**: [Inicie uma discussão](https://github.com/PivotPHP/pivotphp-core/discussions) - Compartilhe feedback e ideias
338+
- **Twitter**: [@PivotPHP](https://twitter.com/pivotphp) - Siga para atualizações e anúncios
339+
220340
## 🤝 Como Contribuir
221341

222342
Quer ajudar a evoluir o PivotPHP? Veja o [Guia de Contribuição](CONTRIBUTING.md) ou acesse [`docs/contributing/`](docs/contributing/) para saber como abrir issues, enviar PRs ou criar extensões.

scripts/prepare_release.sh

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
11
#!/bin/bash
22

3-
# Script de preparação para publicação do PivotPHP v1.0.0
3+
# Script de preparação para publicação do PivotPHP
44
# Este script limpa, valida e prepara o projeto para release
55

66
set -e
77

8+
# Obter versão do arquivo VERSION
9+
if [ -f "VERSION" ]; then
10+
VERSION=$(cat VERSION | tr -d '\n')
11+
else
12+
echo "Arquivo VERSION não encontrado!"
13+
exit 1
14+
fi
15+
816
# Cores
917
GREEN='\033[0;32m'
1018
YELLOW='\033[1;33m'
@@ -19,7 +27,7 @@ success() { echo -e "${GREEN}✅ $1${NC}"; }
1927
warning() { echo -e "${YELLOW}⚠️ $1${NC}"; }
2028
error() { echo -e "${RED}$1${NC}"; exit 1; }
2129

22-
title "PivotPHP v1.0.0 - Release Preparation"
30+
title "PivotPHP v$VERSION - Release Preparation"
2331
echo ""
2432

2533
# Verificar se estamos na raiz do projeto

scripts/release.sh

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,14 @@ VERSION=$1
5757
RELEASE_TYPE=${2:-"release"}
5858
CURRENT_BRANCH=$(git branch --show-current)
5959

60-
title "PivotPHP Release Manager v1.0.0"
60+
# Obter versão atual do arquivo VERSION
61+
if [ -f "VERSION" ]; then
62+
CURRENT_VERSION=$(cat VERSION | tr -d '\n')
63+
else
64+
CURRENT_VERSION="unknown"
65+
fi
66+
67+
title "PivotPHP Release Manager (Current: v$CURRENT_VERSION)"
6168
echo ""
6269

6370
info "Versão a ser criada: $VERSION"

scripts/validate-docs.sh

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,16 @@
11
#!/bin/bash
22

3-
# PivotPHP v1.0.0 - Validador de Documentação
4-
# Valida a nova estrutura de documentação v1.0.0
3+
# PivotPHP - Validador de Documentação
4+
# Valida a estrutura de documentação
55

6-
echo "📚 Validando estrutura de documentação PivotPHP v1.0.0..."
6+
# Obter versão do arquivo VERSION
7+
if [ -f "VERSION" ]; then
8+
VERSION=$(cat VERSION | tr -d '\n')
9+
else
10+
VERSION="unknown"
11+
fi
12+
13+
echo "📚 Validando estrutura de documentação PivotPHP v$VERSION..."
714
echo "============================================================="
815
echo ""
916

0 commit comments

Comments
 (0)