Skip to content

Commit

Permalink
Restructured the config file & other minor tweaks (#99)
Browse files Browse the repository at this point in the history
* Restructured the config file & other minor tweaks

* Fixed the tests
  • Loading branch information
BelleNottelling authored Apr 26, 2024
1 parent cf07696 commit 5db998e
Show file tree
Hide file tree
Showing 17 changed files with 47 additions and 74 deletions.
2 changes: 0 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ jobs:
- name: Install Dependencies
run: composer install --no-interaction --prefer-dist --optimize-autoloader

- run: cp ./tests/Includes/Config.yaml ./src/Config/Config.yaml

- run: php src/Vendor/bin/phpunit tests

PHPStan:
Expand Down
1 change: 1 addition & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
![PHPStan Level](https://img.shields.io/badge/PHPStan-level%205-brightgreen)
[![CI](https://github.com/AntCMS-org/AntCMS/actions/workflows/ci.yml/badge.svg)](https://github.com/AntCMS-org/AntCMS/actions/workflows/ci.yml)
![Supported PHP Versions](https://img.shields.io/badge/PHP%20Versions-8.0%7C8.1%7C8.2%7C8.3-brightgreen)

# AntCMS
Expand Down
2 changes: 1 addition & 1 deletion src/AntCMS/Auth.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ private function requireAuth(): void
setcookie("auth", "valid");

$siteInfo = Config::get('siteInfo');
header('WWW-Authenticate: Basic realm="' . $siteInfo['siteTitle'] . '"');
header('WWW-Authenticate: Basic realm="' . $siteInfo['title'] . '"');
http_response_code(401);
echo 'You must enter a valid username and password to access this page';
exit;
Expand Down
2 changes: 1 addition & 1 deletion src/AntCMS/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class Cache
*/
public function __construct(null|string $mode = null)
{
$mode ??= Config::get('cacheMode') ?? 'auto';
$mode ??= Config::get('performance.cacheMode') ?? 'auto';
if ($mode == 'auto') {
$mode = function_exists('apcu_enabled') && apcu_enabled() ? 'apcu' : 'filesystem';
}
Expand Down
9 changes: 4 additions & 5 deletions src/AntCMS/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ class Config
'performance',
'forceHttps',
'activeTheme',
'cacheMode',
'debug',
'debugLevel',
'baseUrl',
'embed',
];
Expand All @@ -24,17 +23,17 @@ public static function generateConfig(): void
{
$defaultOptions = [
'siteInfo' => [
'siteTitle' => 'AntCMS',
'title' => 'AntCMS',
],
'performance' => [
'doOutputCompression' => true,
'compressTextAssets' => true,
'compressImageAssets' => true,
'cacheMode' => 'auto',
],
'forceHttps' => !Enviroment::isPHPDevServer(),
'activeTheme' => 'Default',
'cacheMode' => 'auto',
'debug' => true,
'debugLevel' => 1, // 0-2 at the moment
'baseUrl' => $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']),
'embed' => [
'allowed_domains' => ['youtube.com', 'twitter.com', 'github.com', 'vimeo.com', 'flickr.com', 'instagram.com', 'facebook.com'],
Expand Down
2 changes: 1 addition & 1 deletion src/AntCMS/Pages.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ private static function generatePageInfo(string $path): array
'title' => $pageHeader['title'],
'realPath' => $path,
'functionalPath' => $functionalPath,
'url' => "//" . Tools::repairURL(baseUrl . $functionalPath),
'url' => "//" . Tools::repairURL(BASE_URL . $functionalPath),
'active' => $functionalPath === self::$currentPage,
'navItem' => $pageHeader['NavItem'] !== 'false',
];
Expand Down
38 changes: 22 additions & 16 deletions src/AntCMS/Tools.php
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ private static function compressImage(string $path, int $quality = 85): string
public static function getAssetCacheKey(string $path): string
{
$encoding = CompressionBuffer::getFirstMethodChoice();
if (compressTextAssets && self::isCompressableTextAsset($path)) {
if (COMPRESS_TEXT_ASSETS && self::isCompressableTextAsset($path)) {
return Cache::createCacheKeyFile($path, "assetCompression-$encoding");
}
return Cache::createCacheKeyFile($path, 'asset');
Expand All @@ -206,7 +206,7 @@ public static function doAssetCompression(string $path): array
$cacheKey = self::getAssetCacheKey($path);
$encoding = 'identity';

if (compressTextAssets && self::isCompressableTextAsset($path)) {
if (COMPRESS_TEXT_ASSETS && self::isCompressableTextAsset($path)) {
CompressionBuffer::enable(); // We will use CompressionBuffer to handle text content
$encoding = CompressionBuffer::getFirstMethodChoice();

Expand All @@ -217,7 +217,7 @@ public static function doAssetCompression(string $path): array
});
}

if (compressImageAssets && self::isCompressableImage($path)) {
if (COMPRESS_IMAGES && self::isCompressableImage($path)) {
$contents = $cache->get($cacheKey, function (ItemInterface $item) use ($path): string {
$item->expiresAfter(604800);
return self::compressImage($path);
Expand Down Expand Up @@ -245,6 +245,10 @@ private static function createDebugLogLine(string $wording, bool|string $value):

public static function buildDebugInfo(): string
{
if (DEBUG_LEVEL === 0) {
return '';
}

$elapsed_time = round((hrtime(true) - START) / 1e+6, 2);
$mem_usage = round(memory_get_peak_usage() / 1e+6, 2);

Expand All @@ -253,21 +257,23 @@ public static function buildDebugInfo(): string
$result .= self::createDebugLogLine('Time to process request', "$elapsed_time ms");
$result .= self::createDebugLogLine('Memory usage', "$mem_usage MB");

// System info
$result .= "<dt>System Info</dt>";
$result .= self::createDebugLogLine('Output compression', doOutputCompression);

if (CompressionBuffer::isEnabled() && doOutputCompression) {
$method = CompressionBuffer::getFirstMethodChoice();
if ($method === 'br') {
$method = 'brotli';
if (DEBUG_LEVEL >= 2) {
// System info
$result .= "<dt>System Info</dt>";
$result .= self::createDebugLogLine('Output compression', COMPRESS_OUTPUT);

if (CompressionBuffer::isEnabled() && COMPRESS_OUTPUT) {
$method = CompressionBuffer::getFirstMethodChoice();
if ($method === 'br') {
$method = 'brotli';
}
$result .= self::createDebugLogLine('This page was compressed with', $method);
}
$result .= self::createDebugLogLine('This page was compressed with', $method);
}

$result .= self::createDebugLogLine('Asset compression', compressTextAssets);
$result .= self::createDebugLogLine('Image compression', compressImageAssets);
$result .= self::createDebugLogLine('PHP version', PHP_VERSION);
$result .= self::createDebugLogLine('Asset compression', COMPRESS_TEXT_ASSETS);
$result .= self::createDebugLogLine('Image compression', COMPRESS_IMAGES);
$result .= self::createDebugLogLine('PHP version', PHP_VERSION);
}

return $result . "</dl>";
}
Expand Down
6 changes: 3 additions & 3 deletions src/AntCMS/Twig.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,13 @@ public static function registerTwig(?Environment $twigEnvironment = null): void
new ArrayLoader(),
]),
[
'cache' => (Config::get('enableCache') !== 'none') ? PATH_CACHE : false,
'debug' => Config::get('debug'),
'cache' => (Config::get('performance.cacheMode') !== 'none') ? PATH_CACHE : false,
'debug' => DEBUG_LEVEL >= 2,
'use_yield' => false,
]
);
$twigEnvironment->addExtension(new TwigFilters());
$twigEnvironment->addGlobal('AntCMSSiteTitle', Config::get('siteInfo')['siteTitle']);
$twigEnvironment->addGlobal('AntCMSSiteTitle', Config::get('siteInfo')['title']);
self::$twigEnvironment = $twigEnvironment;
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/AntCMS/TwigFilters.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public function getFilters(): array

public function absUrl(string $relative): string
{
return '//' . Tools::repairURL(baseUrl . '/' . trim($relative));
return '//' . Tools::repairURL(BASE_URL . '/' . trim($relative));
}

public function markdown(string $content): string
Expand Down
9 changes: 5 additions & 4 deletions src/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@

// Define config-related constants
$config = Config::get();
define('compressTextAssets', $config['performance']['compressTextAssets']);
define('doOutputCompression', $config['performance']['doOutputCompression']);
define('compressImageAssets', $config['performance']['compressImageAssets']);
define('baseUrl', $config['baseUrl']);
define('COMPRESS_TEXT_ASSETS', $config['performance']['compressTextAssets']);
define('COMPRESS_OUTPUT', $config['performance']['doOutputCompression']);
define('COMPRESS_IMAGES', $config['performance']['compressImageAssets']);
define('BASE_URL', $config['baseUrl']);
define('DEBUG_LEVEL', $config['debugLevel']);
2 changes: 1 addition & 1 deletion src/Plugins/Robotstxt/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public function __construct()
Flight::route("GET /robots.txt", function (): void {
$protocol = Config::get('forceHttps') ? 'https' : Flight::request()->scheme;
echo 'User-agent: *' . PHP_EOL;
echo 'Sitemap: ' . $protocol . '://' . Tools::repairURL(baseUrl . '/sitemap.xml' . PHP_EOL);
echo 'Sitemap: ' . $protocol . '://' . Tools::repairURL(BASE_URL . '/sitemap.xml' . PHP_EOL);
Flight::response()->setHeader('Content-Type', 'text/plain');
});
}
Expand Down
2 changes: 1 addition & 1 deletion src/Plugins/Sitemap/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public function __construct()
foreach ($urls as $url) {
$element = $domDocument->createElement('url');

$loc = $domDocument->createElement('loc', $protocol . '://' . Tools::repairURL(baseUrl . $url['url']));
$loc = $domDocument->createElement('loc', $protocol . '://' . Tools::repairURL(BASE_URL . $url['url']));
$element->appendChild($loc);

$lastmod = $domDocument->createElement('lastmod', $url['lastchange']);
Expand Down
5 changes: 2 additions & 3 deletions src/Themes/Default/Templates/default.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,9 @@
</div>
</div>

<footer class="text-center text-lg-start">
<footer class="text-lg-start">
<div class="text-center p-3" style="background-color: rgba(0, 0, 0, 0.2);">
Powered by
<a href="https://antcms.org">AntCMS</a>
<p>Powered by <a href="https://antcms.org">AntCMS</a></p>
<!--AntCMS-Debug-->
</div>
</footer>
Expand Down
11 changes: 3 additions & 8 deletions src/index.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,12 @@

$AntCMS = new AntCMS();

// Add a response body callback to display mem usage and time spent
Flight::response()->addResponseBodyCallback(function ($body) {
if (Config::get('debug')) {
return str_replace('<!--AntCMS-Debug-->', Tools::buildDebugInfo(), $body);
}
return $body;
});
// Add a response body callback to display debug info
Flight::response()->addResponseBodyCallback(fn ($body): string => str_replace('<!--AntCMS-Debug-->', Tools::buildDebugInfo(), $body));

// Setup CompressionBuffer & enable it in Flight
CompressionBuffer::setUp(true, false, [Flight::response(), 'header']);
if (doOutputCompression) {
if (COMPRESS_OUTPUT) {
Flight::response()->addResponseBodyCallback([CompressionBuffer::class, 'handler']);
}

Expand Down
11 changes: 0 additions & 11 deletions tests/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,6 @@

class ConfigTest extends TestCase
{
public function testGetConfig(): void
{
$config = Config::get();

$expectedKeys = ['siteInfo', 'forceHttps', 'activeTheme', 'cacheMode', 'debug', 'baseUrl'];

foreach ($expectedKeys as $expectedKey) {
$this->assertArrayHasKey($expectedKey, $config, "Expected key '{$expectedKey}' not found in config array");
}
}

public function testSaveConfigFailed(): void
{
$Badconfig = [
Expand Down
12 changes: 0 additions & 12 deletions tests/Includes/Config.yaml

This file was deleted.

5 changes: 1 addition & 4 deletions tests/MarkdownTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@ public function testMarkdownIsFast(): void
}

$averageTime = $totalTime / 10;

$callback = new Callback(static fn ($averageTime): bool => $averageTime < 0.015);

$this->assertThat($averageTime, $callback, 'AntMarkdown::renderMarkdown took too long on average!');
$this->assertLessThan(0.015, $averageTime, 'AntMarkdown::renderMarkdown took too long on average!');
}


Expand Down

0 comments on commit 5db998e

Please sign in to comment.