Skip to content

Commit

Permalink
refactor, add test cases
Browse files Browse the repository at this point in the history
  • Loading branch information
warcooft committed Jul 30, 2024
1 parent 229f3db commit 084d215
Show file tree
Hide file tree
Showing 2 changed files with 173 additions and 39 deletions.
113 changes: 74 additions & 39 deletions system/Commands/Utilities/Optimize.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@
use CodeIgniter\Autoloader\FileLocatorCached;
use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Publisher\Publisher;
use CodeIgniter\Exceptions\RuntimeException;
use CodeIgniter\Publisher\Publisher;

/**
* Optimize for production.
Expand Down Expand Up @@ -60,11 +60,19 @@ final class Optimize extends BaseCommand
* @var array<string, string>
*/
protected $options = [
'c' => 'Enable config caching.',
'l' => 'Enable locator caching.',
'c' => 'Enable only config caching.',
'l' => 'Enable only locator caching.',
'd' => 'Disable config and locator caching.',
];

private const CONFIG_CACHE = '$configCacheEnabled';

private const LOCATOR_CACHE = '$locatorCacheEnabled';

private const CONFIG_PATH = APPPATH . 'Config/Optimize.php';

private const CACHE_PATH = WRITEPATH . 'cache/FactoriesCache_config';

/**
* {@inheritDoc}
*/
Expand All @@ -76,7 +84,7 @@ public function run(array $params)
$disable = CLI::getOption('d');

try {
$this->enableCaching($enableConfigCache, $enableLocatorCache, $disable);
$this->runCaching($enableConfigCache, $enableLocatorCache, $disable);
$this->clearCache();
$this->removeDevPackages();
} catch (RuntimeException) {
Expand All @@ -94,8 +102,7 @@ private function clearCache(): void
$locator->deleteCache();
CLI::write('Removed FileLocatorCache.', 'green');

$cache = WRITEPATH . 'cache/FactoriesCache_config';
$this->removeFile($cache);
$this->removeFile(self::CACHE_PATH);
}

private function removeFile(string $cache): void
Expand All @@ -115,75 +122,103 @@ private function removeFile(string $cache): void
}
}

private function enableCaching(?bool $enableConfigCache, ?bool $enableLocatorCache, ?bool $disable): void
private function runCaching(?bool $enableConfigCache, ?bool $enableLocatorCache, ?bool $disable): void
{
$publisher = new Publisher(APPPATH, APPPATH);

$config = APPPATH . 'Config/Optimize.php';

// Prepare search and replace mappings
$searchReplace = [];

if ($disable === true) {
$searchReplace = [
'public bool $configCacheEnabled = true;' => 'public bool $configCacheEnabled = false;',
'public bool $locatorCacheEnabled = true;' => 'public bool $locatorCacheEnabled = false;',
];
$searchReplace = $this->disableCaching();
} else {
if ($enableConfigCache === true) {
$searchReplace['public bool $configCacheEnabled = false;'] = 'public bool $configCacheEnabled = true;';
}

if ($enableLocatorCache === true) {
$searchReplace['public bool $locatorCacheEnabled = false;'] = 'public bool $locatorCacheEnabled = true;';
}

// If no options provided, update both
if ($enableConfigCache === null && $enableLocatorCache === null) {
$searchReplace = [
'public bool $configCacheEnabled = false;' => 'public bool $configCacheEnabled = true;',
'public bool $locatorCacheEnabled = false;' => 'public bool $locatorCacheEnabled = true;',
];
}
$searchReplace = $this->enableCaching(['config' => $enableConfigCache, 'locator' => $enableLocatorCache]);
}

// Apply replacements if necessary
if ($searchReplace !== []) {
$result = $publisher->replace($config, $searchReplace);
$publisher = new Publisher(APPPATH, APPPATH);

$result = $publisher->replace(self::CONFIG_PATH, $searchReplace);

if ($result === true) {
$messages = [];

if (in_array('public bool $configCacheEnabled = true;', $searchReplace, true)) {
if (in_array('public bool ' . self::CONFIG_CACHE . ' = true;', $searchReplace, true)) {
$messages[] = 'Config Caching is enabled in "app/Config/Optimize.php".';
}

if (in_array('public bool $locatorCacheEnabled = true;', $searchReplace, true)) {
if (in_array('public bool ' . self::LOCATOR_CACHE .' = true;', $searchReplace, true)) {
$messages[] = 'FileLocator Caching is enabled in "app/Config/Optimize.php".';
}

if (in_array('public bool $configCacheEnabled = false;', $searchReplace, true)) {
if (in_array('public bool ' . self::CONFIG_CACHE . ' = false;', $searchReplace, true)) {
$messages[] = 'Config Caching is disabled in "app/Config/Optimize.php".';
}

if (in_array('public bool $locatorCacheEnabled = false;', $searchReplace, true)) {
if (in_array('public bool ' . self::LOCATOR_CACHE .' = false;', $searchReplace, true)) {
$messages[] = 'FileLocator Caching is disabled in "app/Config/Optimize.php".';
}

foreach ($messages as $message) {
CLI::write($message, 'green');
CLI::newLine();
}

CLI::write(implode("\n\n", $messages), 'green');
CLI::write();
CLI::newLine();

return;
}

CLI::error('Error in updating file: ' . clean_path($config));
CLI::error('Error in updating file: ' . clean_path(self::CONFIG_PATH));

throw new RuntimeException(__METHOD__);
}

CLI::write('No changes to caching settings.', 'yellow');
}

/**
* Disable Caching
*
* @return array
*/
private function disableCaching(): array
{
return [
'public bool ' . self::CONFIG_CACHE . ' = true;' => 'public bool ' . self::CONFIG_CACHE . ' = false;',
'public bool ' . self::LOCATOR_CACHE .' = true;' => 'public bool ' . self::LOCATOR_CACHE .' = false;',
];
}

/**
* Enable Caching
*
* @param array<string, bool|null> $options
*
* @return array
*/
private function enableCaching(array $options): array
{
$searchReplace = [];

if ($options['config'] === true) {
$searchReplace['public bool ' . self::CONFIG_CACHE . ' = false;'] = 'public bool ' . self::CONFIG_CACHE . ' = true;';
}

if ($options['locator'] === true) {
$searchReplace['public bool ' . self::LOCATOR_CACHE .' = false;'] = 'public bool ' . self::LOCATOR_CACHE .' = true;';
}

// If no options provided, update both
if ($options['config'] === null && $options['locator'] === null) {
$searchReplace = [
'public bool ' . self::CONFIG_CACHE . ' = false;' => 'public bool ' . self::CONFIG_CACHE . ' = true;',
'public bool ' . self::LOCATOR_CACHE .' = false;' => 'public bool ' . self::LOCATOR_CACHE .' = true;',
];
}

return $searchReplace;
}

private function removeDevPackages(): void
{
if (! defined('VENDORPATH')) {
Expand All @@ -203,4 +238,4 @@ private function removeDevPackages(): void

throw new RuntimeException(__METHOD__);
}
}
}
99 changes: 99 additions & 0 deletions tests/system/Commands/Utilities/OptimizeTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php

declare(strict_types=1);

/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/

namespace CodeIgniter\Commands\Utilities;

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\StreamFilterTrait;
use PHPUnit\Framework\Attributes\Group;

/**
* @internal
*/
#[Group('Others')]
final class OptimizeTest extends CIUnitTestCase
{
use StreamFilterTrait;

protected function setUp(): void
{
$this->resetServices();

parent::setUp();
}

protected function getBuffer(): string
{
return $this->getStreamFilterBuffer();
}

public function testEnableConfigCaching(): void
{
$command = new Optimize(service('logger'), service('commands'));

$enableCaching = $this->getPrivateMethodInvoker($command, 'enableCaching');

// private function enableCaching(?bool $enableConfigCache, ?bool $enableLocatorCache, ?bool $disable): void
$enableCaching(true, null, null);

// Check if config caching is enabled
$this->assertFileContains('public bool $configCacheEnabled = true;', APPPATH . 'Config/Optimize.php');
}

public function testEnableLocatorCaching(): void
{
$command = new Optimize(service('logger'), service('commands'));

$enableCaching = $this->getPrivateMethodInvoker($command, 'enableCaching');

// private function enableCaching(?bool $enableConfigCache, ?bool $enableLocatorCache, ?bool $disable): void
$enableCaching(null, true, null);

// Check if locator caching is enabled
$this->assertFileContains('public bool $locatorCacheEnabled = true;', APPPATH . 'Config/Optimize.php');
}

public function testDisableCaching(): void
{
$command = new Optimize(service('logger'), service('commands'));

$enableCaching = $this->getPrivateMethodInvoker($command, 'enableCaching');

// private function enableCaching(?bool $enableConfigCache, ?bool $enableLocatorCache, ?bool $disable): void
$enableCaching(null, null, true);

// Check if both caches are disabled
$this->assertFileContains('public bool $configCacheEnabled = false;', APPPATH . 'Config/Optimize.php');
$this->assertFileContains('public bool $locatorCacheEnabled = false;', APPPATH . 'Config/Optimize.php');
}

public function testWithoutOptions(): void
{
$command = new Optimize(service('logger'), service('commands'));

$enableCaching = $this->getPrivateMethodInvoker($command, 'enableCaching');

// private function enableCaching(?bool $enableConfigCache, ?bool $enableLocatorCache, ?bool $disable): void
$enableCaching(null, null, null);

// Check if both caches are disabled
$this->assertFileContains('public bool $configCacheEnabled = true;', APPPATH . 'Config/Optimize.php');
$this->assertFileContains('public bool $locatorCacheEnabled = true;', APPPATH . 'Config/Optimize.php');
}

protected function assertFileContains(string $needle, string $filePath): void
{
$this->assertFileExists($filePath);
$this->assertStringContainsString($needle, file_get_contents($filePath));
}
}

0 comments on commit 084d215

Please sign in to comment.