mirror of
https://github.com/manualdousuario/marreta.git
synced 2025-09-01 18:20:22 +00:00
classe url processor para otimizar rotas
This commit is contained in:
parent
bc06a7cbc9
commit
5da034322c
4 changed files with 164 additions and 215 deletions
|
@ -81,11 +81,11 @@ class Router
|
|||
require __DIR__ . '/views/home.php';
|
||||
});
|
||||
|
||||
// Rota da API - inclui api.php existente
|
||||
// API route - includes existing api.php
|
||||
// Rota da API - usa URLProcessor em modo API
|
||||
// API route - uses URLProcessor in API mode
|
||||
$r->addRoute('GET', '/api/{url:.+}', function($vars) {
|
||||
$_GET['url'] = $vars['url'];
|
||||
require __DIR__ . '/api.php';
|
||||
$processor = new URLProcessor($vars['url'], true);
|
||||
$processor->process();
|
||||
});
|
||||
|
||||
// Rota da API sem parâmetros - redireciona para raiz
|
||||
|
@ -95,11 +95,11 @@ class Router
|
|||
exit;
|
||||
});
|
||||
|
||||
// Rota de processamento - inclui p.php existente
|
||||
// Processing route - includes existing p.php
|
||||
// Rota de processamento - usa URLProcessor em modo web
|
||||
// Processing route - uses URLProcessor in web mode
|
||||
$r->addRoute('GET', '/p/{url:.+}', function($vars) {
|
||||
$_GET['url'] = $vars['url'];
|
||||
require __DIR__ . '/p.php';
|
||||
$processor = new URLProcessor($vars['url'], false);
|
||||
$processor->process();
|
||||
});
|
||||
|
||||
// Rota de processamento com query parameter ou sem parâmetros
|
||||
|
|
156
app/src/URLProcessor.php
Normal file
156
app/src/URLProcessor.php
Normal file
|
@ -0,0 +1,156 @@
|
|||
<?php
|
||||
|
||||
namespace App;
|
||||
|
||||
/**
|
||||
* URL Processor
|
||||
* Processador de URLs
|
||||
*
|
||||
* This class combines the functionality of the previous p.php and api.php files
|
||||
* to provide a unified interface for URL processing, handling both web and API responses.
|
||||
*
|
||||
* Esta classe combina as funcionalidades dos arquivos p.php e api.php anteriores
|
||||
* para fornecer uma interface unificada para processamento de URLs, tratando respostas web e API.
|
||||
*/
|
||||
class URLProcessor
|
||||
{
|
||||
private $url;
|
||||
private $isApi;
|
||||
private $analyzer;
|
||||
|
||||
/**
|
||||
* Constructor - initializes the processor with URL and mode
|
||||
* Construtor - inicializa o processador com URL e modo
|
||||
*
|
||||
* @param string $url The URL to process
|
||||
* @param bool $isApi Whether to return API response
|
||||
*/
|
||||
public function __construct(string $url = '', bool $isApi = false)
|
||||
{
|
||||
require_once __DIR__ . '/../config.php';
|
||||
require_once __DIR__ . '/../inc/URLAnalyzer.php';
|
||||
require_once __DIR__ . '/../inc/Language.php';
|
||||
|
||||
$this->url = urldecode($url);
|
||||
$this->isApi = $isApi;
|
||||
$this->analyzer = new \URLAnalyzer();
|
||||
|
||||
if ($isApi) {
|
||||
// Initialize language system for API responses
|
||||
\Language::init(LANGUAGE);
|
||||
|
||||
// Set API headers
|
||||
header('Content-Type: application/json');
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: GET');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a JSON response for API requests
|
||||
* Envia uma resposta JSON para requisições API
|
||||
*/
|
||||
private function sendApiResponse(array $data, int $statusCode = 200): void
|
||||
{
|
||||
http_response_code($statusCode);
|
||||
$response = ['status' => $statusCode];
|
||||
|
||||
if (isset($data['error'])) {
|
||||
$response['error'] = $data['error'];
|
||||
} else if (isset($data['url'])) {
|
||||
$response['url'] = $data['url'];
|
||||
}
|
||||
|
||||
echo json_encode($response);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles web redirects
|
||||
* Trata redirecionamentos web
|
||||
*/
|
||||
private function redirect(string $path, string $message = ''): void
|
||||
{
|
||||
$url = $message ? $path . '?message=' . $message : $path;
|
||||
header('Location: ' . $url);
|
||||
exit;
|
||||
}
|
||||
|
||||
/**
|
||||
* Process the URL and return appropriate response
|
||||
* Processa a URL e retorna resposta apropriada
|
||||
*/
|
||||
public function process(): void
|
||||
{
|
||||
// Validate URL format
|
||||
if (!filter_var($this->url, FILTER_VALIDATE_URL)) {
|
||||
if ($this->isApi) {
|
||||
$this->sendApiResponse([
|
||||
'error' => [
|
||||
'type' => \URLAnalyzer::ERROR_INVALID_URL,
|
||||
'message' => \Language::getMessage('INVALID_URL')['message']
|
||||
]
|
||||
], 400);
|
||||
} else {
|
||||
$this->redirect(SITE_URL, \URLAnalyzer::ERROR_INVALID_URL);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
// Check for redirects in web mode
|
||||
if (!$this->isApi) {
|
||||
$redirectInfo = $this->analyzer->checkStatus($this->url);
|
||||
if ($redirectInfo['hasRedirect'] && $redirectInfo['finalUrl'] !== $this->url) {
|
||||
$this->redirect(SITE_URL . '/p/' . urlencode($redirectInfo['finalUrl']));
|
||||
}
|
||||
}
|
||||
|
||||
// Process the URL
|
||||
$content = $this->analyzer->analyze($this->url);
|
||||
|
||||
if ($this->isApi) {
|
||||
$this->sendApiResponse([
|
||||
'url' => SITE_URL . '/p/' . $this->url
|
||||
]);
|
||||
} else {
|
||||
echo $content;
|
||||
}
|
||||
} catch (\URLAnalyzerException $e) {
|
||||
$errorType = $e->getErrorType();
|
||||
$additionalInfo = $e->getAdditionalInfo();
|
||||
|
||||
if ($this->isApi) {
|
||||
// Add error headers for API responses
|
||||
header('X-Error-Type: ' . $errorType);
|
||||
if ($additionalInfo) {
|
||||
header('X-Error-Info: ' . $additionalInfo);
|
||||
}
|
||||
|
||||
$this->sendApiResponse([
|
||||
'error' => [
|
||||
'type' => $errorType,
|
||||
'message' => $e->getMessage(),
|
||||
'details' => $additionalInfo ?: null
|
||||
]
|
||||
], $e->getCode());
|
||||
} else {
|
||||
// Handle blocked domain with redirect URL for web responses
|
||||
if ($errorType === \URLAnalyzer::ERROR_BLOCKED_DOMAIN && $additionalInfo) {
|
||||
$this->redirect(trim($additionalInfo), $errorType);
|
||||
}
|
||||
$this->redirect(SITE_URL, $errorType);
|
||||
}
|
||||
} catch (\Exception $e) {
|
||||
if ($this->isApi) {
|
||||
$this->sendApiResponse([
|
||||
'error' => [
|
||||
'type' => \URLAnalyzer::ERROR_GENERIC_ERROR,
|
||||
'message' => \Language::getMessage('GENERIC_ERROR')['message']
|
||||
]
|
||||
], 500);
|
||||
} else {
|
||||
$this->redirect(SITE_URL, \URLAnalyzer::ERROR_GENERIC_ERROR);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
119
app/src/api.php
119
app/src/api.php
|
@ -1,119 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* URL Analysis API
|
||||
* API para análise de URLs
|
||||
*
|
||||
* This file implements a REST endpoint that receives URLs via GET
|
||||
* and returns processed results in JSON format.
|
||||
*
|
||||
* Este arquivo implementa um endpoint REST que recebe URLs via GET
|
||||
* e retorna resultados processados em formato JSON.
|
||||
*
|
||||
* Features / Funcionalidades:
|
||||
* - URL validation / Validação de URLs
|
||||
* - Content analysis / Análise de conteúdo
|
||||
* - Error handling / Tratamento de erros
|
||||
* - CORS support / Suporte a CORS
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config.php';
|
||||
require_once __DIR__ . '/../inc/URLAnalyzer.php';
|
||||
require_once __DIR__ . '/../inc/Language.php';
|
||||
|
||||
// Initialize language system with default language
|
||||
// Inicializa o sistema de idiomas com o idioma padrão
|
||||
Language::init(LANGUAGE);
|
||||
|
||||
// Set content type as JSON
|
||||
// Define o tipo de conteúdo como JSON
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Enable CORS (Cross-Origin Resource Sharing)
|
||||
// Habilita CORS (Cross-Origin Resource Sharing)
|
||||
header('Access-Control-Allow-Origin: *');
|
||||
header('Access-Control-Allow-Methods: GET');
|
||||
|
||||
/**
|
||||
* Function to send standardized JSON response
|
||||
* Função para enviar resposta JSON padronizada
|
||||
*
|
||||
* @param array $data Data to be sent in response / Dados a serem enviados na resposta
|
||||
* @param int $statusCode HTTP status code / Código de status HTTP
|
||||
*/
|
||||
function sendResponse($data, $statusCode = 200)
|
||||
{
|
||||
http_response_code($statusCode);
|
||||
$response = [
|
||||
'status' => $statusCode
|
||||
];
|
||||
|
||||
if (isset($data['error'])) {
|
||||
$response['error'] = $data['error'];
|
||||
} else if (isset($data['url'])) {
|
||||
$response['url'] = $data['url'];
|
||||
}
|
||||
|
||||
echo json_encode($response);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Get URL from Router
|
||||
// Obtém a URL do Router
|
||||
$url = isset($_GET['url']) ? urldecode($_GET['url']) : '';
|
||||
|
||||
// Basic URL validation
|
||||
// Validação básica da URL
|
||||
if (!$url || !filter_var($url, FILTER_VALIDATE_URL)) {
|
||||
sendResponse([
|
||||
'error' => [
|
||||
'type' => URLAnalyzer::ERROR_INVALID_URL,
|
||||
'message' => Language::getMessage('INVALID_URL')['message']
|
||||
]
|
||||
], 400);
|
||||
}
|
||||
|
||||
try {
|
||||
// Instantiate URL analyzer
|
||||
// Instancia o analisador de URLs
|
||||
$analyzer = new URLAnalyzer();
|
||||
|
||||
// Try to analyze the provided URL
|
||||
// Tenta analisar a URL fornecida
|
||||
$analyzer->analyze($url);
|
||||
|
||||
// If analysis is successful, return the processed URL
|
||||
// Se a análise for bem-sucedida, retorna a URL processada
|
||||
sendResponse([
|
||||
'url' => SITE_URL . '/p/' . $url
|
||||
], 200);
|
||||
} catch (URLAnalyzerException $e) {
|
||||
// Get error details from the exception
|
||||
// Obtém detalhes do erro da exceção
|
||||
$errorType = $e->getErrorType();
|
||||
$additionalInfo = $e->getAdditionalInfo();
|
||||
|
||||
// Add error header for better client-side handling
|
||||
// Adiciona header de erro para melhor tratamento no cliente
|
||||
header('X-Error-Type: ' . $errorType);
|
||||
if ($additionalInfo) {
|
||||
header('X-Error-Info: ' . $additionalInfo);
|
||||
}
|
||||
|
||||
sendResponse([
|
||||
'error' => [
|
||||
'type' => $errorType,
|
||||
'message' => $e->getMessage(),
|
||||
'details' => $additionalInfo ?: null
|
||||
]
|
||||
], $e->getCode());
|
||||
} catch (Exception $e) {
|
||||
// Handle any other unexpected errors
|
||||
// Trata quaisquer outros erros inesperados
|
||||
sendResponse([
|
||||
'error' => [
|
||||
'type' => URLAnalyzer::ERROR_GENERIC_ERROR,
|
||||
'message' => Language::getMessage('GENERIC_ERROR')['message']
|
||||
]
|
||||
], 500);
|
||||
}
|
|
@ -1,88 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* URL Processor
|
||||
* Processador de URLs
|
||||
*
|
||||
* This file is responsible for:
|
||||
* - Receiving URLs through the /p/ path
|
||||
* - Validating URL format
|
||||
* - Processing content using URLAnalyzer
|
||||
* - Displaying processed content or redirecting in case of error
|
||||
*
|
||||
* Este arquivo é responsável por:
|
||||
* - Receber URLs através do path /p/
|
||||
* - Validar o formato da URL
|
||||
* - Processar o conteúdo usando o URLAnalyzer
|
||||
* - Exibir o conteúdo processado ou redirecionar em caso de erro
|
||||
*
|
||||
* Usage examples / Exemplos de uso:
|
||||
* /p/https://exemplo.com
|
||||
* /p/?url=https://exemplo.com
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../config.php';
|
||||
require_once __DIR__ . '/../inc/URLAnalyzer.php';
|
||||
|
||||
// Get URL from either path parameter or query string
|
||||
// Obtém a URL do parâmetro de path ou query string
|
||||
$url = '';
|
||||
if (isset($_GET['url'])) {
|
||||
$url = urldecode($_GET['url']);
|
||||
}
|
||||
|
||||
// Validate URL format
|
||||
// Valida o formato da URL
|
||||
if (filter_var($url, FILTER_VALIDATE_URL)) {
|
||||
$analyzer = new URLAnalyzer();
|
||||
try {
|
||||
// Check for redirects
|
||||
// Verifica se há redirecionamentos
|
||||
$redirectInfo = $analyzer->checkStatus($url);
|
||||
|
||||
// If there's a redirect and the final URL is different
|
||||
// Se houver redirecionamento e a URL final for diferente
|
||||
if ($redirectInfo['hasRedirect'] && $redirectInfo['finalUrl'] !== $url) {
|
||||
// Redirect to final URL
|
||||
// Redireciona para a URL final
|
||||
header('Location: ' . SITE_URL . '/p/' . urlencode($redirectInfo['finalUrl']));
|
||||
exit;
|
||||
}
|
||||
|
||||
// If there's no redirect or if already at final URL
|
||||
// Se não houver redirecionamento ou se já estiver na URL final
|
||||
// Try to analyze and process the URL
|
||||
// Tenta analisar e processar a URL
|
||||
$content = $analyzer->analyze($url);
|
||||
// Display processed content
|
||||
// Exibe o conteúdo processado
|
||||
echo $content;
|
||||
exit;
|
||||
} catch (URLAnalyzerException $e) {
|
||||
// Get error type and additional info from exception
|
||||
// Obtém o tipo de erro e informações adicionais da exceção
|
||||
$errorType = $e->getErrorType();
|
||||
$additionalInfo = $e->getAdditionalInfo();
|
||||
|
||||
// Handle blocked domain with redirect URL
|
||||
// Trata domínio bloqueado com URL de redirecionamento
|
||||
if ($errorType === URLAnalyzer::ERROR_BLOCKED_DOMAIN && $additionalInfo) {
|
||||
header('Location: ' . trim($additionalInfo) . '?message=' . $errorType);
|
||||
exit;
|
||||
}
|
||||
|
||||
// Redirect to home page with error message
|
||||
// Redireciona para a página inicial com mensagem de erro
|
||||
header('Location: /?message=' . $errorType);
|
||||
exit;
|
||||
} catch (Exception $e) {
|
||||
// Handle any other unexpected errors
|
||||
// Trata quaisquer outros erros inesperados
|
||||
header('Location: /?message=' . URLAnalyzer::ERROR_GENERIC_ERROR);
|
||||
exit;
|
||||
}
|
||||
} else {
|
||||
// Invalid URL / URL inválida
|
||||
header('Location: /?message=' . URLAnalyzer::ERROR_INVALID_URL);
|
||||
exit;
|
||||
}
|
Loading…
Add table
Reference in a new issue