Skip to content
Open
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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@
/test/behaviour/project/*/vendor
/test/phpunit/.phpunit.cache
.phpunit*.cache

config.*.ini
33 changes: 33 additions & 0 deletions config.default.ini
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,23 @@ component_directory=page/_component
partial_directory=page/_partial

[logger]
; Opt-in DEBUG diagnostics (also require level=debug for the destination).
; HTML component expansion and optional PHP logic files.
debug_html_components=false
; Partial expansion and missing partial directories.
debug_html_partials=false
; Request start, redirects, completion and error handling.
debug_requests=false
; Path normalisation, route selection and matched view/logic files.
debug_routing=false
; Logic lifecycle phases and completed function calls.
debug_logic=false
; View preparation and streaming.
debug_views=false
; CSRF verification decisions (never token values).
debug_csrf=false
; Service loader selection and fallback.
debug_services=false
log_all_requests=true
log_static_requests=false
log_404_to_error_log=false
Expand Down Expand Up @@ -90,3 +107,19 @@ csrf_max_tokens=100
csrf_token_length=32
;Generate tokens once "per-form" or once "per-page"
csrf_token_sharing=per-form

[deploy]
; Deployment server; HTTPS is assumed when no scheme is supplied.
server=deploy.php.gt
; Deployment transport; currently only tar-http is supported.
transport=tar-http
; Private token and its issuing server, saved by gt deploy in config.dev.ini.
token=
token_server=

[deployment]
; Private environment tokens, generated in config.dev.ini by gt deploy.
staging_token=
staging_token_server=
production_token=
production_token_server=
10 changes: 10 additions & 0 deletions src/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use GT\Http\ResponseStatusException\ClientError\ClientErrorException;
use GT\Http\ResponseStatusException\ResponseStatusException;
use GT\Logger\Log;
use GT\WebEngine\Debug\DebugLogger;
use GT\Logger\LogConfig;
use GT\Logger\LogHandler\StdErrHandler;
use GT\Logger\LogLevel;
Expand Down Expand Up @@ -45,6 +46,7 @@
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
class Application {
private DebugLogger $debugLogger;
private const string REDACTED_LOG_VALUE = "[redacted]";

private Redirect $redirect;
Expand Down Expand Up @@ -80,6 +82,7 @@ public function __construct(
?Protection $globalProtection = null,
) {
$this->initConfig($config);
$this->debugLogger = new DebugLogger($this->config);
$this->configureLoggerStreams();
$this->redirect = $this->createRedirect($redirect);
$application = $this;
Expand Down Expand Up @@ -111,9 +114,11 @@ public function __construct(
public function start():void {
// Before we start, we check if the current URI should be redirected. If it
// should, we won't go any further into the lifecycle.
$this->debugLogger->log("requests", "Request lifecycle started");
$requestedPath = $this->getRequestedPath();
$redirectUri = $this->redirect->execute($requestedPath);
if($redirectUri) {
$this->debugLogger->log("requests", "Redirect rule matched", ["status" => $redirectUri->code]);
$this->logRedirect($redirectUri, $requestedPath);
return;
}
Expand Down Expand Up @@ -193,6 +198,7 @@ private function createRedirect(?Redirect $redirect = null):Redirect {
}

private function handleThrowable(Throwable $throwable):?Response {
$this->debugLogger->log("requests", "Handling request exception", ["exception" => get_class($throwable)]);
$this->sentryReporter?->report($throwable);
if ($errorScript = $this->config->getString('app.error_script')) {
$this->restoreGlobals();
Expand Down Expand Up @@ -270,6 +276,10 @@ private function finish(

$this->timer->stop();
$this->timer->logDelta();
$this->debugLogger->log("requests", "Request lifecycle completed", [
"status" => $response->getStatusCode(),
"seconds" => $this->timer->getDelta(),
]);
$this->sentryLogHandler?->flush();
}

Expand Down
17 changes: 17 additions & 0 deletions src/Debug/DebugLogger.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php
namespace GT\WebEngine\Debug;

use GT\Config\Config;
use GT\Logger\Log;

/** Opt-in diagnostics; the destination's minimum level still applies. */
class DebugLogger {
public function __construct(private readonly ?Config $config = null) {}

/** @param array<string, mixed> $context */
public function log(string $category, string $message, array $context = []):void {
if(filter_var($this->config?->getString("logger.debug_" . $category), FILTER_VALIDATE_BOOLEAN)) {
Log::debug($message, $context);
}
}
}
24 changes: 24 additions & 0 deletions src/Dispatch/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
use GT\Input\InputData\InputData;
use GT\Json\Schema\JSONDocument;
use GT\Logger\Log;
use GT\WebEngine\Debug\DebugLogger;
use GT\Routing\Assembly;
use GT\Routing\BaseRouter;
use GT\Routing\Path\DynamicPath;
Expand Down Expand Up @@ -56,6 +57,7 @@
* @SuppressWarnings("PHPMD.ExcessiveClassComplexity")
*/
class Dispatcher {
private DebugLogger $debugLogger;
private const LOGIC_EXECUTION_HEADER = "X-Logic-Execution";
private const COMPONENT_INPUT_NAME = "__component";

Expand Down Expand Up @@ -117,6 +119,7 @@ public function __construct(
// Set the first Dispatcher dependencies - these are required to be passed from
// the Application, so come first as non-nullable:
$this->config = $config;
$this->debugLogger = new DebugLogger($this->config);
$this->request = $request;
$this->globals = $globals;
$this->finishCallback = $finishCallback;
Expand Down Expand Up @@ -159,10 +162,12 @@ public function __construct(
$this->globals["_FILES"],
$this->globals["_SERVER"],
);
$this->debugLogger->log("routing", "Request path normalisation completed");
$this->input = $requestInit->getInput();
$this->serviceContainer->set($this->input);
$this->serviceContainer->set($requestInit->getServerInfo());
if($this->isRedirectPrepared()) {
$this->debugLogger->log("routing", "Path normalisation prepared a redirect");
$this->redirectPrepared = true;
return;
}
Expand Down Expand Up @@ -191,6 +196,12 @@ public function __construct(
$this->serviceContainer->set($dynamicPath);
$this->viewAssembly = $routerInit->getViewAssembly();
$this->logicAssembly = $routerInit->getLogicAssembly();
$this->debugLogger->log("routing", "Route selected", [
"router" => get_class($this->router),
"view" => get_class($this->view),
"view_files" => iterator_to_array(clone $this->viewAssembly),
"logic_files" => iterator_to_array(clone $this->logicAssembly),
]);

$sessionInit = $sessionInit ?? new SessionInit(
$this->config->getString("session.name"),
Expand All @@ -215,6 +226,7 @@ public function __construct(
$this->viewModel,
$this->config->getString("view.component_directory"),
$this->config->getString("view.partial_directory"),
$this->debugLogger,
);
$this->viewModelProcessor = $viewModelInit->getViewModelProcessor();
$this->viewInitCb = $this->viewModel instanceof HTMLDocument
Expand All @@ -238,6 +250,7 @@ public function __construct(
$this->logicExecutor = $logicExecutor ?? new LogicExecutor(
$appNamespace,
$this->injector,
$this->debugLogger,
);
$this->viewStreamer = $viewStreamer ?? new ViewStreamer();
$this->headerManager = $headerManager ?? new HeaderManager();
Expand All @@ -256,6 +269,7 @@ public function generateResponse():Response {
// step individually to ensure proper error handling throughout the process.
if(!$this->viewAssembly->containsDistinctFile() && !$this->logicAssembly->containsDistinctFile()) {
$this->response = $this->response->withStatus(StatusCode::NOT_FOUND);
$this->debugLogger->log("routing", "No distinct view or logic file matched");
throw new HttpNotFound();
}

Expand Down Expand Up @@ -517,7 +531,9 @@ private function setupJsonDocumentErrorCallback():void {
);
}

$this->debugLogger->log("views", "Streaming prepared view", ["view" => get_class($this->view)]);
$this->viewStreamer->stream($this->view, $this->viewModel);
$this->debugLogger->log("views", "View streaming completed");
($this->finishCallback)($this->response);

if($this->interruptResponse) {
Expand All @@ -531,6 +547,7 @@ private function handleLogicExecution(
Input $input,
?Element $component = null,
):void {
$this->debugLogger->log("logic", "Starting logic lifecycle", ["component" => $component?->tagName]);
$extraArgs = [];

if($component) {
Expand Down Expand Up @@ -668,10 +685,13 @@ public function processResponse(
$this->applyResponseHeaders();
$this->prepareViewModelForStreaming();

$this->debugLogger->log("views", "Streaming prepared view", ["view" => get_class($this->view)]);
$this->viewStreamer->stream($this->view, $this->viewModel);
$this->debugLogger->log("views", "View streaming completed");
$this->consumeCsrfToken($csrfToken);
}
catch(ResponseInterrupt) {
$this->debugLogger->log("logic", "Response interrupted by logic");
$this->consumeCsrfToken($csrfToken);
return;
}
Expand Down Expand Up @@ -716,6 +736,7 @@ private function prepareViewModelForStreaming():void {

private function recordLogicExecution(string $functionReference):void {
$refWithoutAttributes = explode("#", $functionReference, 2)[0];
$this->debugLogger->log("logic", "Logic function completed", ["function" => $refWithoutAttributes]);
$separatorPosition = strrpos($refWithoutAttributes, "::");
if($separatorPosition === false) {
return;
Expand Down Expand Up @@ -750,10 +771,12 @@ private function normaliseLogicExecutionFile(string $file):string {

private function verifyCsrfRequest(string $method, InputData $inputData):?string {
if(!($this->viewModel instanceof HTMLDocument)) {
$this->debugLogger->log("csrf", "CSRF verification skipped for non-HTML response");
return null;
}

if($method !== "POST" || $this->isIgnoredCsrfPath()) {
$this->debugLogger->log("csrf", "CSRF verification skipped for method or ignored path");
return null;
}

Expand All @@ -771,6 +794,7 @@ private function verifyCsrfRequest(string $method, InputData $inputData):?string

$token = $postData[HTMLDocumentProtector::TOKEN_NAME];
$tokenStore->verifyToken($token);
$this->debugLogger->log("csrf", "CSRF verification succeeded");
return $token;
}
catch(CsrfException $exception) {
Expand Down
3 changes: 3 additions & 0 deletions src/Init/ViewModelInit.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
namespace GT\WebEngine\Init;

use GT\Dom\HTMLDocument;
use GT\WebEngine\Debug\DebugLogger;
use GT\DomTemplate\BindableCache;
use GT\DomTemplate\DocumentBinder;
use GT\DomTemplate\ElementBinder;
Expand All @@ -23,11 +24,13 @@ public function __construct(
HTMLDocument|JSONDocument $model,
string $componentDirectory,
string $partialDirectory,
?DebugLogger $debugLogger = null,
) {
if($model instanceof HTMLDocument) {
$this->viewModelProcessor = new HTMLDocumentProcessor(
$componentDirectory,
$partialDirectory,
$debugLogger,
);
}
// TODO: Handle other view model types.
Expand Down
18 changes: 14 additions & 4 deletions src/Logic/HTMLDocumentProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use GT\DomTemplate\PartialContent;
use GT\DomTemplate\PartialContentDirectoryNotFoundException;
use GT\DomTemplate\PartialExpander;
use GT\Logger\Log;
use GT\Routing\Assembly;
use GT\Routing\Path\DynamicPath;
use GT\WebEngine\View\HeaderFooterPartialConflictException;
Expand Down Expand Up @@ -63,8 +62,13 @@ function processPartialContent(
$partial,
);
$partialExpander->expand();
$this->debugLogger->log("html_partials", "HTML partial expansion completed");
}
catch(PartialContentDirectoryNotFoundException) {
$this->debugLogger->log("html_partials", "HTML partial directory not found", [
"directory" => $this->partialDirectory,
]);
}
catch(PartialContentDirectoryNotFoundException) {}

try {
// TODO: Handle other model types in sub-functions.
Expand All @@ -84,7 +88,8 @@ function processPartialContent(
$filePath .= ".php";

if(!is_file($filePath)) {
Log::debug(
$this->debugLogger->log(
"html_components",
"Component detected without matching logic file",
[
"component" => strtolower($componentElement->tagName),
Expand All @@ -94,6 +99,7 @@ function processPartialContent(
continue;
}

$this->debugLogger->log("html_components", "Component logic file found", ["logic_file" => $filePath]);
$componentAssembly = new Assembly();
$componentAssembly->add($filePath);
$componentList->addAssemblyComponent(
Expand All @@ -102,7 +108,11 @@ function processPartialContent(
);
}
}
catch(PartialContentDirectoryNotFoundException) {}
catch(PartialContentDirectoryNotFoundException) {
$this->debugLogger->log("html_components", "HTML component directory not found", [
"directory" => $this->componentDirectory,
]);
}

return $componentList;
}
Expand Down
5 changes: 5 additions & 0 deletions src/Logic/LogicExecutor.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
namespace GT\WebEngine\Logic;

use Generator;
use GT\WebEngine\Debug\DebugLogger;
use GT\Routing\Assembly;
use GT\Routing\LogicStream\LogicStreamNamespace;
use GT\Routing\LogicStream\LogicStreamWrapper;
Expand All @@ -12,6 +13,7 @@ class LogicExecutor {
public function __construct(
private string $appNamespace,
private Injector $injector,
private ?DebugLogger $debugLogger = null,
) {
}

Expand All @@ -23,6 +25,7 @@ public function __construct(
// phpcs:disable Generic.Metrics.NestingLevel.TooHigh
public function invoke(Assembly $logicAssembly, string $name, array $extraArgs = []):Generator {
foreach($logicAssembly as $file) {
$this->debugLogger?->log("logic", "Loading logic file", ["file" => $file]);
$this->loadLogicFile($file);
}

Expand All @@ -43,6 +46,7 @@ public function invoke(Assembly $logicAssembly, string $name, array $extraArgs =

if($instance) {
if(method_exists($instance, $name)) {
$this->debugLogger?->log("logic", "Invoking logic method", ["file" => $file, "method" => $name]);
$this->injector->invoke(
$instance,
$name,
Expand All @@ -61,6 +65,7 @@ public function invoke(Assembly $logicAssembly, string $name, array $extraArgs =

foreach($fnReferenceArray as $fnReference) {
if(function_exists($fnReference)) {
$this->debugLogger?->log("logic", "Invoking logic function", ["file" => $file, "function" => $name]);
$refFunction = new ReflectionFunction($fnReference);
foreach($refFunction->getAttributes() as $refAttr) {
$functionReference .= "#";
Expand Down
7 changes: 6 additions & 1 deletion src/Logic/ViewModelProcessor.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@
namespace GT\WebEngine\Logic;

use GT\Dom\HTMLDocument;
use GT\WebEngine\Debug\DebugLogger;
use GT\Routing\Assembly;
use GT\Routing\Path\DynamicPath;

abstract class ViewModelProcessor {
protected DebugLogger $debugLogger;
public function __construct(
protected string $componentDirectory,
protected string $partialDirectory,
) {}
?DebugLogger $debugLogger = null,
) {
$this->debugLogger = $debugLogger ?? new DebugLogger();
}

abstract function processDynamicPath(
HTMLDocument $model,
Expand Down
Loading