Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions WebFiori/Http/RequestProcessor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
<?php

/**
* This file is licensed under MIT License.
*
* Copyright (c) 2019-present WebFiori Framework
*
* For more information on the license, please visit:
* https://github.com/WebFiori/http/blob/master/LICENSE
*/
namespace WebFiori\Http;

/**
* Processes a single WebService against an HTTP request without requiring
* manual service registration or a full WebServicesManager setup.
*
* This class provides a simplified entry point for processing a web service.
* It handles content type validation, HTTP method checking, parameter filtering,
* authorization, method invocation, and response serialization.
*
* Usage:
* ```php
* $processor = new RequestProcessor();
* $processor->process(new MyService(), Request::createFromGlobals());
* ```
*
* @author Ibrahim
*/
class RequestProcessor {
/**
* Process a request against a specific web service.
*
* The processor runs the full pipeline:
* 1. Content type validation
* 2. HTTP method matching
* 3. Parameter filtering and validation
* 4. Authorization check
* 5. Method invocation
* 6. Response serialization
*
* @param WebService $service The service to process.
* @param Request|null $request The incoming HTTP request. If null, creates from globals.
* @param resource|null $outputStream Optional output stream for testing.
*/
public function process(WebService $service, ?Request $request = null, $outputStream = null) : void {
if ($request === null) {
$request = Request::createFromGlobals();
}

$manager = new WebServicesManager($request);
$manager->addService($service);

if ($outputStream !== null) {
$manager->setOutputStream($outputStream);
}

$manager->process();
}
}
63 changes: 63 additions & 0 deletions examples/04-advanced/04-request-processor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# RequestProcessor — Standalone Service Processing

Demonstrates processing a web service directly without a `WebServicesManager`.

## What This Example Demonstrates

- Using `RequestProcessor` to process a single service
- No service registry or manager setup required
- Automatic request creation from globals
- Full pipeline: validation, auth, invocation, serialization

## Files

- [`index.php`](index.php) - Processes a service directly with RequestProcessor

## How to Run

```bash
php -S localhost:8080
```

## Testing

```bash
# GET request
curl "http://localhost:8080?name=Ibrahim"

# GET without param (uses default)
curl "http://localhost:8080"

# POST request
curl -X POST http://localhost:8080 \
-d "to=Alice&body=Hi there"
```

## Code Explanation

### Before (WebServicesManager)

```php
$manager = new WebServicesManager();
$manager->addService(new GreetService());
$manager->process();
```

### After (RequestProcessor)

```php
$processor = new RequestProcessor();
$processor->process(new GreetService());
```

The `RequestProcessor` is ideal when:
- You have a router that already resolved which service to call
- You want to process a single service without registry overhead
- You're building framework integrations that handle routing externally

### With explicit Request (for testing)

```php
$processor = new RequestProcessor();
$processor->process(new GreetService(), $request, $outputStream);
```
40 changes: 40 additions & 0 deletions examples/04-advanced/04-request-processor/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

require_once '../../../vendor/autoload.php';

use WebFiori\Http\Annotations\AllowAnonymous;
use WebFiori\Http\Annotations\GetMapping;
use WebFiori\Http\Annotations\PostMapping;
use WebFiori\Http\Annotations\RequestParam;
use WebFiori\Http\Annotations\ResponseBody;
use WebFiori\Http\Annotations\RestController;
use WebFiori\Http\ParamType;
use WebFiori\Http\RequestProcessor;
use WebFiori\Http\WebService;

#[RestController('greet')]
class GreetService extends WebService {
#[GetMapping]
#[ResponseBody]
#[AllowAnonymous]
#[RequestParam('name', ParamType::STRING, true)]
public function hello(?string $name): array {
return ['message' => 'Hello, ' . ($name ?? 'World') . '!'];
}

#[PostMapping]
#[ResponseBody]
#[AllowAnonymous]
#[RequestParam('to', ParamType::STRING)]
#[RequestParam('body', ParamType::STRING)]
public function sendGreeting(string $to, string $body): array {
return ['sent_to' => $to, 'body' => $body, 'timestamp' => time()];
}

public function isAuthorized(): bool { return true; }
public function processRequest() {}
}

// Process directly — no WebServicesManager needed
$processor = new RequestProcessor();
$processor->process(new GreetService());
162 changes: 162 additions & 0 deletions tests/WebFiori/Tests/Http/RequestProcessorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
<?php
namespace WebFiori\Tests\Http;

use WebFiori\Http\APITestCase;
use WebFiori\Http\Request;
use WebFiori\Http\RequestProcessor;
use WebFiori\Tests\Http\TestServices\AnnotatedMethodService;
use WebFiori\Tests\Http\TestServices\AllMethodsService;
use WebFiori\Tests\Http\TestServices\StringAuthDenialService;

/**
* Tests for RequestProcessor.
*
* @see https://github.com/WebFiori/http/issues/121
*/
class RequestProcessorTest extends APITestCase {

/**
* Test processing a GET request with ResponseBody annotation.
*/
public function testProcessGetWithResponseBody() {
$processor = new RequestProcessor();
$service = new AnnotatedMethodService();

putenv('REQUEST_METHOD=GET');
$_GET = ['param1' => 'hello'];
$_SERVER['CONTENT_TYPE'] = '';

$outFile = $this->getOutputFile();
$stream = fopen($outFile, 'w');
$request = Request::createFromGlobals();

$processor->process($service, $request, $stream);

$output = file_get_contents($outFile);
@unlink($outFile);

$this->assertNotEmpty($output);
}

/**
* Test processing a POST request with parameter validation.
*/
public function testProcessPostWithParams() {
$processor = new RequestProcessor();
$service = new AllMethodsService();

putenv('REQUEST_METHOD=POST');
$_POST = ['name' => 'John'];
$_SERVER['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';

$outFile = $this->getOutputFile();
$stream = fopen($outFile, 'w');
$request = Request::createFromGlobals();

$processor->process($service, $request, $stream);

$output = file_get_contents($outFile);
@unlink($outFile);

$this->assertNotEmpty($output);
}

/**
* Test that unauthorized service returns 401.
*/
public function testUnauthorizedReturnsError() {
$processor = new RequestProcessor();
$service = new StringAuthDenialService();

putenv('REQUEST_METHOD=GET');
$_GET = [];
$_SERVER['CONTENT_TYPE'] = '';

$outFile = $this->getOutputFile();
$stream = fopen($outFile, 'w');
$request = Request::createFromGlobals();

$processor->process($service, $request, $stream);

$output = file_get_contents($outFile);
@unlink($outFile);

$response = json_decode($output, true);
$this->assertIsArray($response);
$this->assertEquals('error', $response['type']);
$this->assertEquals(401, $response['http-code']);
$this->assertEquals('You must be a premium member to access this resource.', $response['message']);
}

/**
* Test that wrong HTTP method returns 405.
*/
public function testMethodNotAllowed() {
$processor = new RequestProcessor();
$service = new AnnotatedMethodService();

putenv('REQUEST_METHOD=DELETE');
$_GET = [];
$_SERVER['CONTENT_TYPE'] = '';

$outFile = $this->getOutputFile();
$stream = fopen($outFile, 'w');
$request = Request::createFromGlobals();

$processor->process($service, $request, $stream);

$output = file_get_contents($outFile);
@unlink($outFile);

$response = json_decode($output, true);
$this->assertIsArray($response);
$this->assertEquals('error', $response['type']);
}

/**
* Test that unsupported content type returns 415.
*/
public function testContentTypeNotSupported() {
$processor = new RequestProcessor();
$service = new AllMethodsService();

putenv('REQUEST_METHOD=POST');
$_POST = [];
$_SERVER['CONTENT_TYPE'] = 'text/xml';

$outFile = $this->getOutputFile();
$stream = fopen($outFile, 'w');
$request = Request::createFromGlobals();

$processor->process($service, $request, $stream);

$output = file_get_contents($outFile);
@unlink($outFile);

$response = json_decode($output, true);
$this->assertIsArray($response);
$this->assertEquals('error', $response['type']);
}

/**
* Test processing with null request (creates from globals).
*/
public function testProcessWithNullRequest() {
$processor = new RequestProcessor();
$service = new AnnotatedMethodService();

putenv('REQUEST_METHOD=GET');
$_GET = ['param1' => 'test'];
$_SERVER['CONTENT_TYPE'] = '';

$outFile = $this->getOutputFile();
$stream = fopen($outFile, 'w');

$processor->process($service, null, $stream);

$output = file_get_contents($outFile);
@unlink($outFile);

$this->assertNotEmpty($output);
}
}
Loading