Skip to content

Commit 7ed88cd

Browse files
authored
Merge pull request #2 from panicdevs/develop
patch: cache issues and filament panel resolver
2 parents 3283a7a + 39558fc commit 7ed88cd

File tree

6 files changed

+133
-61
lines changed

6 files changed

+133
-61
lines changed

config/modulite.php

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@
8585
'auto_register' => env('MODULITE_AUTO_REGISTER_PANELS', true),
8686
'sort_by' => 'priority', // 'priority', 'name', 'none'
8787
'respect_environment' => true,
88-
'validate_before_register' => app()->hasDebugModeEnabled(),
88+
'validate_before_register' => env('MODULITE_VALIDATE_BEFORE_REGISTER', env('APP_DEBUG', false)),
8989
],
9090

9191
/*
@@ -189,7 +189,7 @@
189189
'registration' => [
190190
'auto_register' => env('MODULITE_AUTO_REGISTER_COMPONENTS', true),
191191
'sort_by' => env('MODULITE_SORT_COMPONENTS', 'none'), // 'name', 'priority', 'none'
192-
'validate_before_register' => env('MODULITE_VALIDATE_COMPONENTS', app()->hasDebugModeEnabled()),
192+
'validate_before_register' => env('MODULITE_VALIDATE_COMPONENTS', env('APP_DEBUG', false)),
193193
'group_by_module' => true,
194194
],
195195

@@ -251,7 +251,7 @@
251251
| request. Recommended: true for production, false for development.
252252
|
253253
*/
254-
'enabled' => env('MODULITE_CACHE_ENABLED', !app()->hasDebugModeEnabled()),
254+
'enabled' => env('MODULITE_CACHE_ENABLED', !env('APP_DEBUG', false)),
255255

256256
/*
257257
|--------------------------------------------------------------------------
@@ -275,7 +275,7 @@
275275
| Set to 0 in production for maximum performance (never expires).
276276
|
277277
*/
278-
'ttl' => env('MODULITE_CACHE_TTL', app()->hasDebugModeEnabled() ? 300 : 0),
278+
'ttl' => env('MODULITE_CACHE_TTL', env('APP_DEBUG', false) ? 300 : 0),
279279

280280
/*
281281
|--------------------------------------------------------------------------
@@ -286,7 +286,7 @@
286286
| Only works in development mode for performance reasons.
287287
|
288288
*/
289-
'auto_invalidate' => app()->hasDebugModeEnabled(),
289+
'auto_invalidate' => env('MODULITE_AUTO_INVALIDATE', env('APP_DEBUG', false)),
290290

291291
/*
292292
|--------------------------------------------------------------------------
@@ -312,9 +312,9 @@
312312
*/
313313
'optimizations' => [
314314
'static_caching' => env('MODULITE_STATIC_CACHING', true),
315-
'defer_validation' => env('MODULITE_DEFER_VALIDATION', !app()->hasDebugModeEnabled()),
315+
'defer_validation' => env('MODULITE_DEFER_VALIDATION', !env('APP_DEBUG', false)),
316316
'skip_duplicate_panels' => env('MODULITE_SKIP_DUPLICATE_PANELS', true),
317-
'disable_reflection' => env('MODULITE_DISABLE_REFLECTION', app()->isProduction()),
317+
'disable_reflection' => env('MODULITE_DISABLE_REFLECTION', 'production' === env('APP_ENV')),
318318
],
319319
],
320320

@@ -436,7 +436,7 @@
436436
| Enable/disable logging and configure log channels.
437437
|
438438
*/
439-
'enabled' => env('MODULITE_LOGGING_ENABLED', app()->hasDebugModeEnabled()),
439+
'enabled' => env('MODULITE_LOGGING_ENABLED', env('APP_DEBUG', false)),
440440
'channel' => env('MODULITE_LOG_CHANNEL', 'stack'),
441441
'level' => env('MODULITE_LOG_LEVEL', 'info'),
442442

@@ -448,9 +448,9 @@
448448
| Log performance metrics for optimization and monitoring.
449449
|
450450
*/
451-
'log_discovery_time' => app()->hasDebugModeEnabled(),
452-
'log_cache_hits' => app()->hasDebugModeEnabled(),
453-
'log_scan_stats' => app()->hasDebugModeEnabled(),
451+
'log_discovery_time' => env('MODULITE_LOG_DISCOVERY_TIME', env('APP_DEBUG', false)),
452+
'log_cache_hits' => env('MODULITE_LOG_CACHE_HITS', env('APP_DEBUG', false)),
453+
'log_scan_stats' => env('MODULITE_LOG_SCAN_STATS', env('APP_DEBUG', false)),
454454
],
455455

456456
/*
@@ -470,9 +470,9 @@
470470
| Control whether errors are thrown or handled silently.
471471
|
472472
*/
473-
'fail_silently' => !app()->hasDebugModeEnabled(),
474-
'log_errors' => true,
475-
'max_errors_per_scan' => 10,
473+
'fail_silently' => env('MODULITE_FAIL_SILENTLY', !env('APP_DEBUG', false)),
474+
'log_errors' => env('MODULITE_LOG_ERRORS', true),
475+
'max_errors_per_scan' => env('MODULITE_MAX_ERRORS_PER_SCAN', 10),
476476

477477
/*
478478
|--------------------------------------------------------------------------
@@ -482,7 +482,7 @@
482482
| Configure handling of validation errors during discovery.
483483
|
484484
*/
485-
'throw_on_invalid_class' => app()->hasDebugModeEnabled(),
486-
'throw_on_missing_requirements' => app()->hasDebugModeEnabled(),
485+
'throw_on_invalid_class' => env('MODULITE_THROW_ON_INVALID_CLASS', env('APP_DEBUG', false)),
486+
'throw_on_missing_requirements' => env('MODULITE_THROW_ON_MISSING_REQUIREMENTS', env('APP_DEBUG', false)),
487487
],
488488
];

src/Console/Commands/ModuliteClearCacheCommand.php

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
/**
1212
* Command to clear all Modulite caches.
13+
* This command is automatically called by Laravel's `optimize:clear` command.
1314
*/
1415
class ModuliteClearCacheCommand extends Command
1516
{
@@ -20,12 +21,6 @@ class ModuliteClearCacheCommand extends Command
2021

2122
public function handle(CacheManagerInterface $cacheManager): int
2223
{
23-
if (!$this->option('force') && !$this->confirm('Are you sure you want to clear all Modulite caches?'))
24-
{
25-
$this->info('Cache clear cancelled.');
26-
return self::SUCCESS;
27-
}
28-
2924
$this->info('Clearing Modulite caches...');
3025

3126
try

src/Console/Commands/ModuliteOptimizeCommand.php

Lines changed: 75 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
use PanicDevs\Modulite\Contracts\CacheManagerInterface;
99
use PanicDevs\Modulite\Contracts\PanelScannerInterface;
1010
use PanicDevs\Modulite\Contracts\ComponentScannerInterface;
11+
use PanicDevs\Modulite\Contracts\ModuleResolverInterface;
1112
use Throwable;
1213

1314
/**
@@ -28,7 +29,8 @@ class ModuliteOptimizeCommand extends Command
2829
* @var string
2930
*/
3031
protected $signature = 'modulite:cache
31-
{--force : Force cache regeneration even if cache exists}';
32+
{--force : Force cache regeneration even if cache exists}
33+
{--enable-cache : Temporarily enable caching even in debug mode}';
3234

3335
/**
3436
* The console command description.
@@ -43,12 +45,21 @@ class ModuliteOptimizeCommand extends Command
4345
public function handle(
4446
CacheManagerInterface $cacheManager,
4547
PanelScannerInterface $panelScanner,
46-
ComponentScannerInterface $componentScanner
48+
ComponentScannerInterface $componentScanner,
49+
ModuleResolverInterface $moduleResolver
4750
): int {
4851
$this->info('Optimizing Modulite caches...');
4952

5053
try
5154
{
55+
// Temporarily enable cache if requested
56+
if ($this->option('enable-cache'))
57+
{
58+
$this->info('Temporarily enabling cache for this operation...');
59+
// Enable cache in the manager for this command only
60+
$this->enableCacheForCommand($cacheManager);
61+
}
62+
5263
// Clear existing caches if force flag is used
5364
if ($this->option('force'))
5465
{
@@ -60,6 +71,11 @@ public function handle(
6071
$this->line('• Warming panel discovery cache...');
6172
$panels = $panelScanner->discoverPanels();
6273
$panelCount = count($panels);
74+
75+
// Store panels in cache using the same key as the service provider
76+
$panelCacheKey = $this->generatePanelCacheKey($moduleResolver);
77+
$cacheManager->put($panelCacheKey, $panels);
78+
6379
$this->line(" <fg=green>✓</> Found {$panelCount} panel providers");
6480

6581
// Warm component discovery cache for all discovered panels
@@ -69,9 +85,14 @@ public function handle(
6985
foreach ($panels as $panelClass)
7086
{
7187
// Extract panel ID from class name (e.g., UserPanelProvider -> user)
72-
$panelId = $this->extractPanelIdFromClass($panelClass);
73-
$components = $componentScanner->discoverComponents($panelId);
74-
$totalComponents += array_sum(array_map('count', $components));
88+
$panelId = $this->extractPanelIdFromClass($panelClass);
89+
90+
// Force cache warming by calling discoverComponents which stores in cache
91+
$components = $componentScanner->discoverComponents($panelId);
92+
$componentCount = array_sum(array_map('count', $components));
93+
$totalComponents += $componentCount;
94+
95+
$this->line(" - {$panelId}: {$componentCount} components");
7596
}
7697

7798
$this->line(" <fg=green>✓</> Found {$totalComponents} components");
@@ -119,6 +140,55 @@ protected function extractPanelIdFromClass(string $className): string
119140
return mb_strtolower($panelId);
120141
}
121142

143+
/**
144+
* Temporarily enable cache for this command operation.
145+
*/
146+
protected function enableCacheForCommand(CacheManagerInterface $cacheManager): void
147+
{
148+
// Check if cache manager supports runtime enable (UnifiedCacheManager does)
149+
if (method_exists($cacheManager, 'enableTemporarily'))
150+
{
151+
$cacheManager->enableTemporarily();
152+
} else
153+
{
154+
$this->warn('Cache manager does not support temporary enabling. Use MODULITE_CACHE_ENABLED=true instead.');
155+
}
156+
}
157+
158+
/**
159+
* Generate cache key for panels (same logic as ModuliteServiceProvider).
160+
*/
161+
protected function generatePanelCacheKey(ModuleResolverInterface $moduleResolver): string
162+
{
163+
// Use the module resolver to get enabled modules
164+
$enabledModules = $moduleResolver->getEnabledModules();
165+
166+
// Include module names - use simple array for consistent hashing
167+
$moduleData = $enabledModules->sort()->values()->toArray();
168+
169+
// Include the module resolver approach in cache key
170+
$approach = config('modulite.modules.approach', 'nwidart');
171+
172+
// Include configuration in cache key
173+
$configHash = md5(serialize([
174+
'panels' => config('modulite.panels', []),
175+
'components' => config('modulite.components', []),
176+
'modules' => config('modulite.modules', [])
177+
]));
178+
179+
// Include environment
180+
$environment = config('app.env', 'production');
181+
182+
$keyData = [
183+
'modules' => $moduleData,
184+
'approach' => $approach,
185+
'config' => $configHash,
186+
'environment' => $environment,
187+
];
188+
189+
return 'panels:'.md5(serialize($keyData));
190+
}
191+
122192
/**
123193
* Display cache file information.
124194
*/

src/Providers/ModuliteServiceProvider.php

Lines changed: 27 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,13 @@ public function register(): void
7979
{
8080
$this->registerConfiguration();
8181
$this->registerCoreServices();
82-
$this->app->beforeResolving(self::FILAMENT_NAMESPACE, fn() => $this->registerPanelDiscovery());
82+
if ('nwidart' === config('modulite.modules.approach'))
83+
{
84+
$this->app->beforeResolving('filament', fn() => $this->registerPanelDiscovery());
85+
} else
86+
{
87+
$this->registerPanelDiscovery();
88+
}
8389
$this->registerCacheInvalidationListeners();
8490
}
8591

@@ -96,6 +102,7 @@ public function boot(): void
96102
$this->publishConfiguration();
97103
$this->validateConfiguration();
98104
$this->setupDevelopmentHelpers();
105+
$this->registerCommands();
99106
}
100107

101108
/**
@@ -119,7 +126,7 @@ protected function registerCoreServices(): void
119126
});
120127

121128
// Register ModuleResolver based on configuration
122-
$this->app->singleton(ModuleResolverInterface::class, fn (Application $app) => $this->createModuleResolver($app));
129+
$this->app->singleton(ModuleResolverInterface::class, fn(Application $app) => $this->createModuleResolver($app));
123130

124131
// Register PanelScannerService with dependencies
125132
$this->app->singleton(PanelScannerInterface::class, function (Application $app)
@@ -356,7 +363,7 @@ protected function publishConfiguration(): void
356363
*/
357364
protected function validateConfiguration(): void
358365
{
359-
if (!$this->app->hasDebugModeEnabled())
366+
if (!config('app.debug', false))
360367
{
361368
return;
362369
}
@@ -393,43 +400,34 @@ protected function validateConfiguration(): void
393400
}
394401
}
395402

396-
// Validate cache configuration
397-
if ($config['cache']['enabled'] ?? false)
398-
{
399-
$driver = $config['cache']['driver'] ?? 'file';
400-
if (!in_array($driver, ['file', 'redis', 'memcached', 'array', 'database'], true))
401-
{
402-
Log::channel(config('modulite.logging.channel', 'default'))
403-
->warning("Modulite cache driver '{$driver}' may not be supported");
404-
}
405-
}
403+
// Cache configuration validation removed as we use file-based cache only
406404
}
407405

408406
/**
409407
* Setup development mode helpers.
410408
*/
411409
protected function setupDevelopmentHelpers(): void
412410
{
413-
// Register artisan commands if available
414-
if ($this->app->runningInConsole())
415-
{
416-
$this->registerConsoleCommands();
417-
}
411+
// Development helpers are now registered in registerCommands()
418412
}
419413

420414
/**
421-
* Register console commands for development.
415+
* Register console commands.
422416
*/
423-
protected function registerConsoleCommands(): void
417+
protected function registerCommands(): void
424418
{
425-
$this->commands([
426-
ModuliteClearCacheCommand::class,
427-
ModuliteStatusCommand::class,
428-
ModuliteOptimizeCommand::class,
429-
]);
430-
431-
// Note: Laravel optimize integration removed to prevent circular dependencies
432-
// Users should manually run: php artisan modulite:cache
419+
// Only register commands in console environment
420+
if ($this->app->runningInConsole())
421+
{
422+
$this->commands([
423+
ModuliteClearCacheCommand::class,
424+
ModuliteStatusCommand::class,
425+
ModuliteOptimizeCommand::class,
426+
]);
427+
428+
// Register optimization commands with Laravel's optimize system
429+
$this->optimizes('modulite:cache', clear: 'modulite:clear');
430+
}
433431
}
434432

435433
/**
@@ -444,7 +442,7 @@ protected function shouldPerformDiscovery(): bool
444442
}
445443

446444
// In production, always perform discovery to ensure routes are cached properly
447-
if ($this->app->isProduction())
445+
if ('production' === config('app.env'))
448446
{
449447
return true;
450448
}

src/Services/ComponentDiscoveryService.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,13 +71,13 @@ public function discoverComponents(string $panelName): array
7171
}
7272

7373
// Only measure time in development
74-
$startTime = app()->hasDebugModeEnabled() ? microtime(true) : 0;
74+
$startTime = config('app.debug', false) ? microtime(true) : 0;
7575

7676
// Discover components efficiently
7777
$components = $this->performOptimizedDiscovery($panelName);
7878

7979
// Update stats only in development
80-
if (app()->hasDebugModeEnabled())
80+
if (config('app.debug', false))
8181
{
8282
$this->stats['scan_time'] = microtime(true) - $startTime;
8383
}

0 commit comments

Comments
 (0)