Skip to content

Commit

Permalink
Expanded hooks a little bit
Browse files Browse the repository at this point in the history
  • Loading branch information
BelleNottelling committed Oct 10, 2024
1 parent b9a70d1 commit 619026a
Show file tree
Hide file tree
Showing 9 changed files with 66 additions and 14 deletions.
2 changes: 1 addition & 1 deletion src/AntCMS/ApiController.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ private function getApiCallData(string $plugin, string $method): array
{
// Some needed variable setup
$url = rtrim(Flight::request()->url, '/');
if($_GET !== []) {
if ($_GET !== []) {
$query = '?' . http_build_query($_GET);
$url = str_replace($query, '', $url);
}
Expand Down
38 changes: 36 additions & 2 deletions src/AntCMS/Event.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@ class Event
private int $paramUpdateCount = 0;
private int $paramReadCount = 0;
private int $lastCallback = 0;
private bool $defaultPrevented = false;

/**
* @param string $associatedHook The hook that this event is associated with. Hook must exist.
*
* @param mixed[] $parameters
*/
public function __construct(string $associatedHook, private array $parameters, private readonly int $totalCallbacks)
public function __construct(string $associatedHook, private array $parameters, private readonly int $totalCallbacks, private readonly bool $preventable)
{
if (!HookController::isRegistered($associatedHook)) {
throw new \Exception("Hook $associatedHook is not registered!");
Expand Down Expand Up @@ -127,7 +128,7 @@ public function setParameters(array $parameters): Event
}

/**
* Returns the number of times the event parameters were read from
* Returns the number of times the event parameters were read from.
*/
public function getReadCount(): int
{
Expand All @@ -141,4 +142,37 @@ public function getUpdateCount(): int
{
return $this->paramUpdateCount;
}

/**
* Indicates if the default behavior for an event is preventable.
*/
public function isDefaultPreventable(): bool
{
return $this->preventable;
}

/**
* Indicates if the default behavior for an event is prevented.
*/
public function isDefaultPrevented(): bool
{
return $this->defaultPrevented;
}

/**
* Sets a flag for the default behavior of this event to be prevented.
* Not all events can be prevented. Triggers a non-fatal error if the event's default behavior is not preventable.
*
* @return Event
*/
public function preventDefault(): Event
{
if (!$this->isDefaultPreventable()) {
trigger_error("The default behavior for the `$this->associatedHook` hook cannot be prevented.");
} else {
$this->defaultPrevented = true;
}

return $this;
}
}
5 changes: 3 additions & 2 deletions src/AntCMS/Hook.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,9 @@ class Hook
*
* @param string $name The name of the hook
* @param string $description A description of this hook
* @param bool $isDefaultPreventable Marks if the default behavior for a hook can be prevented.
*/
public function __construct(string $name, public string $description)
public function __construct(string $name, public string $description, private readonly bool $isDefaultPreventable = false)
{
if (preg_match('/^\w+$/', $name) === 0 || preg_match('/^\w+$/', $name) === false) {
throw new \Exception("The hook name '$name' is invalid. Only a-z A-Z, 0-9, and _ are allowed to be in the hook name.");
Expand All @@ -40,7 +41,7 @@ public function fire(array $params): Event
$this->timesFired++;

// Create the new event object with the originally provided parameters
$event = new Event($this->name, $params, $this->registeredCallbacks);
$event = new Event($this->name, $params, $this->registeredCallbacks, $this->isDefaultPreventable);

// Then fire each of the callbacks and update the event instance from each one.
foreach ($this->callbacks as $callback) {
Expand Down
8 changes: 4 additions & 4 deletions src/AntCMS/HookController.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public static function isRegistered(string $name): bool
return array_key_exists($name, self::$hooks);
}

public static function registerHook(string $name, string $description = ''): bool
public static function registerHook(string $name, string $description = '', bool $isDefaultPreventable = false): bool
{
if (self::isRegistered($name)) {
if ($description !== '') {
Expand All @@ -29,7 +29,7 @@ public static function registerHook(string $name, string $description = ''): boo
return true;
}

self::$hooks[$name] = new Hook($name, $description);
self::$hooks[$name] = new Hook($name, $description, $isDefaultPreventable);
return true;
}

Expand All @@ -42,9 +42,9 @@ public static function registerCallback(string $name, callable $callback): void
}

/**
* @param mixed[] $params
* @param mixed[] $params (Optional)
*/
public static function fire(string $name, array $params): Event
public static function fire(string $name, array $params = []): Event
{
if (self::isRegistered($name)) {
return self::$hooks[$name]->fire($params);
Expand Down
4 changes: 2 additions & 2 deletions src/AntCMS/Pages.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,10 @@ private static function buildList(string $path = PATH_CONTENT): array
if (isset($directoryMeta['pageOrder'][$a]) && isset($directoryMeta['pageOrder'][$b])) {
return $directoryMeta['pageOrder'][$a] > $directoryMeta['pageOrder'][$b] ? 1 : -1;
}
if(isset($directoryMeta['pageOrder'][$a]) && !isset($directoryMeta['pageOrder'][$b])) {
if (isset($directoryMeta['pageOrder'][$a]) && !isset($directoryMeta['pageOrder'][$b])) {
return -1;
}
if(!isset($directoryMeta['pageOrder'][$a]) && isset($directoryMeta['pageOrder'][$b])) {
if (!isset($directoryMeta['pageOrder'][$a]) && isset($directoryMeta['pageOrder'][$b])) {
return 1;
}
// Ensure index items come first
Expand Down
2 changes: 2 additions & 0 deletions src/AntCMS/PluginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ public static function init(): void
Twig::addLoaderPath($templateDir);
}
}

HookController::fire('onAfterPluginsInit');
}

/**
Expand Down
1 change: 0 additions & 1 deletion src/Plugins/Robotstxt/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
use AntCMS\Config;
use AntCMS\PluginController;
use AntCMS\Tools;

use Flight;

class Controller extends AbstractPlugin
Expand Down
13 changes: 13 additions & 0 deletions src/Plugins/System/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace AntCMS\Plugins\System;

use AntCMS\AbstractPlugin;
use AntCMS\AntCMS;
use AntCMS\HookController;

class Controller extends AbstractPlugin
Expand All @@ -18,6 +19,8 @@ class Controller extends AbstractPlugin
'onHookFireComplete' => 'This event is fired when others have completed. The data provided will include the hook name, timing data, and parameter read / update statistics.',
'onBeforeMarkdownParsed' => 'This event is fired before markdown is converted, allowing for pre-processing before the markdown is run through the parser',
'onAfterMarkdownParsed' => 'This is fired after markdown is converted, allowing you to modify generated markdown content',
'onAfterPluginsInit' => 'This event is fired after all plugins have been initialized.',
'onBeforeOutputFinalized' => 'This event is fired right before the generated response is finalized (compressed) and sent to the browser. No later chances to modify the output buffer exist.',
];

public function __construct()
Expand All @@ -27,6 +30,16 @@ public function __construct()
HookController::registerHook($name, $description);
}

HookController::registerCallback('onBeforeOutputFinalized', $this->appendDebugInfo(...));

$this->addDisallow('/api/*');
}

private function appendDebugInfo(\AntCMS\Event $event): \AntCMS\Event
{
$params = $event->getParameters();
$params['output'] = str_replace('<!--AntCMS-Debug-->', \AntCMS\Tools::buildDebugInfo(), $params['output'] ?? '');
$event->setParameters($params);
return $event;
}
}
7 changes: 5 additions & 2 deletions src/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@

$AntCMS = new AntCMS();

// Add a response body callback to display debug info
Flight::response()->addResponseBodyCallback(fn ($body): string => str_replace('<!--AntCMS-Debug-->', Tools::buildDebugInfo(), $body));
// Use hooks to perform any final changes to the output buffer before compressing and sending it
Flight::response()->addResponseBodyCallback(function (string $body): string {
$event = HookController::fire('onBeforeOutputFinalized', ['output' => $body]);
return $event->getParameters()['output'];
});

// Setup CompressionBuffer & enable it in Flight
CompressionBuffer::setUp(true, false, [Flight::response(), 'header']);
Expand Down

0 comments on commit 619026a

Please sign in to comment.