Skip to content

Commit ddeea93

Browse files
committed
feat: integrate logging library and enhance settings validation
1 parent 728920c commit ddeea93

File tree

5 files changed

+150
-386
lines changed

5 files changed

+150
-386
lines changed

src/IconManager.php

Lines changed: 20 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
use lindemannrock\iconmanager\services\IconSetsService;
3131
use lindemannrock\iconmanager\utilities\ClearIconCache;
3232
use lindemannrock\iconmanager\variables\IconManagerVariable;
33+
use lindemannrock\logginglibrary\LoggingLibrary;
3334
use yii\base\Event;
3435
use craft\console\Application as ConsoleApplication;
3536
use craft\services\Utilities;
@@ -171,12 +172,15 @@ public function getCpNavItem(): ?array
171172
],
172173
];
173174

174-
if (Craft::$app->getUser()->checkPermission('accessPlugin-icon-manager')) {
175-
$item['subnav']['logs'] = [
176-
'label' => Craft::t('icon-manager', 'Logs'),
177-
'url' => 'icon-manager/logs',
178-
];
175+
// Add logs section using the logging library (only if installed)
176+
if (Craft::$app->getPlugins()->isPluginInstalled('logging-library') &&
177+
Craft::$app->getPlugins()->isPluginEnabled('logging-library')) {
178+
$item = LoggingLibrary::addLogsNav($item, $this->handle, [
179+
'accessPlugin-icon-manager'
180+
]);
181+
}
179182

183+
if (Craft::$app->getUser()->checkPermission('accessPlugin-icon-manager')) {
180184
$item['subnav']['settings'] = [
181185
'label' => Craft::t('icon-manager', 'Settings'),
182186
'url' => 'icon-manager/settings',
@@ -203,8 +207,8 @@ function(RegisterUrlRulesEvent $event) {
203207
'icon-manager/icon-sets/<iconSetId:\d+>' => 'icon-manager/icon-sets/edit',
204208
'icon-manager/icon-sets/delete' => 'icon-manager/icon-sets/delete',
205209
'icon-manager/icon-sets/refresh-icons' => 'icon-manager/icon-sets/refresh-icons',
206-
'icon-manager/logs' => 'icon-manager/logs/index',
207-
'icon-manager/logs/download' => 'icon-manager/logs/download',
210+
'icon-manager/logs' => 'logging-library/logs/index',
211+
'icon-manager/logs/download' => 'logging-library/logs/download',
208212
'icon-manager/settings' => 'icon-manager/settings/index',
209213
'icon-manager/settings/save' => 'icon-manager/settings/save',
210214
'icon-manager/icons/render' => 'icon-manager/icons/render',
@@ -353,54 +357,16 @@ private function _clearIconCache(): void
353357
*/
354358
private function _registerLogTarget(): void
355359
{
356-
// Skip if already configured
357-
if (isset(Craft::$app->getLog()->targets['icon-manager'])) {
358-
return;
359-
}
360-
361-
// Get base logs path
362-
$logsPath = Craft::$app->getPath()->getLogPath();
363-
364-
// Use date-based log file naming
365-
$date = date('Y-m-d');
366-
$logFile = $logsPath . "/icon-manager-{$date}.log";
367-
368-
// Get log level from settings with fallback
369-
$logLevel = $this->getSettings()->logLevel ?? 'error';
370-
371-
// Map log level to array of levels to include
372-
$levels = match ($logLevel) {
373-
'trace' => ['error', 'warning', 'info', 'trace'],
374-
'info' => ['error', 'warning', 'info'],
375-
'warning' => ['error', 'warning'],
376-
'error' => ['error'],
377-
default => ['error', 'warning', 'info']
378-
};
379-
380-
// Create a new log target instance
381-
$target = new \yii\log\FileTarget([
382-
'logFile' => $logFile,
383-
'categories' => ['icon-manager'],
384-
'logVars' => [],
385-
'levels' => $levels,
386-
'maxFileSize' => 10240, // 10MB
387-
'maxLogFiles' => 30, // Keep 30 days
388-
'prefix' => function ($message) {
389-
$user = Craft::$app->has('user', true) ? Craft::$app->getUser() : null;
390-
$userId = $user && !$user->getIsGuest() ? $user->getId() : '-';
391-
return "[user:{$userId}]";
392-
},
393-
'rotateByCopy' => false
360+
// Configure logging using the new logging library
361+
$settings = $this->getSettings();
362+
363+
LoggingLibrary::configure([
364+
'pluginHandle' => $this->handle,
365+
'pluginName' => $this->name,
366+
'logLevel' => $settings->logLevel,
367+
'enableLogViewer' => true,
368+
'permissions' => ['iconManager:viewLogs'],
394369
]);
395-
396-
// Add the target to the log dispatcher and ensure it's available immediately
397-
Craft::$app->getLog()->targets['icon-manager'] = $target;
398-
399-
// Initialize the target immediately
400-
$target->init();
401-
402-
// Mark as registered
403-
self::$_logTargetRegistered = true;
404370
}
405371

406372
}

src/controllers/SettingsController.php

Lines changed: 0 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,6 @@ public function actionSave(): ?Response
5151
// Get settings from request (nested under 'settings' key)
5252
$postedSettings = $request->getBodyParam('settings', []);
5353

54-
// Debug logging
55-
Craft::info('Posted settings: ' . json_encode($postedSettings), 'icon-manager');
56-
Craft::info('Current overridden settings: ' . json_encode($settings->getOverriddenSettings()), 'icon-manager');
57-
Craft::info('Current overridden icon types: ' . json_encode($settings->getOverriddenIconTypes()), 'icon-manager');
5854

5955
// Only update non-overridden settings
6056
if (!$settings->isOverridden('pluginName')) {
@@ -92,10 +88,6 @@ public function actionSave(): ?Response
9288

9389
$settings->enabledIconTypes = $currentIconTypes;
9490

95-
// Before saving, log the current values
96-
Craft::info('Settings before save - showLabels: ' . ($settings->showLabels ? 'true' : 'false'), 'icon-manager');
97-
Craft::info('Settings before save - iconSize: ' . $settings->iconSize, 'icon-manager');
98-
Craft::info('Settings before save - material-icons: ' . ($settings->enabledIconTypes['material-icons'] ? 'true' : 'false'), 'icon-manager');
9991

10092
// Validate
10193
if (!$settings->validate()) {

src/models/Settings.php

Lines changed: 103 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -91,10 +91,41 @@ protected function defineRules(): array
9191
[['enableCache'], 'boolean'],
9292
[['cacheDuration'], 'integer', 'min' => 1],
9393
[['enabledIconTypes'], 'safe'],
94-
[['logLevel'], 'in', 'range' => ['trace', 'info', 'warning', 'error']],
94+
[['logLevel'], 'in', 'range' => ['debug', 'info', 'warning', 'error']],
95+
[['logLevel'], 'validateLogLevel'],
9596
];
9697
}
9798

99+
/**
100+
* Validate log level - debug requires devMode
101+
*/
102+
public function validateLogLevel($attribute, $params, $validator)
103+
{
104+
$logLevel = $this->$attribute;
105+
106+
// Reset session warning when devMode is true - allows warning to show again if devMode changes
107+
if (Craft::$app->getConfig()->getGeneral()->devMode) {
108+
Craft::$app->getSession()->remove('im_debug_config_warning');
109+
}
110+
111+
// Debug level is only allowed when devMode is enabled - auto-fallback to info
112+
if ($logLevel === 'debug' && !Craft::$app->getConfig()->getGeneral()->devMode) {
113+
$this->$attribute = 'info';
114+
115+
// Only log warning once per session for config overrides
116+
if ($this->isOverriddenByConfig('logLevel')) {
117+
if (Craft::$app->getSession()->get('im_debug_config_warning') === null) {
118+
Craft::warning('Log level "debug" from config file changed to "info" because devMode is disabled. Please update your config/icon-manager.php file.', 'icon-manager');
119+
Craft::$app->getSession()->set('im_debug_config_warning', true);
120+
}
121+
} else {
122+
// Database setting - save the correction
123+
Craft::warning('Log level automatically changed from "debug" to "info" because devMode is disabled. This setting has been saved.', 'icon-manager');
124+
$this->saveToDatabase();
125+
}
126+
}
127+
}
128+
98129
/**
99130
* Get the resolved icon sets path
100131
*/
@@ -183,7 +214,7 @@ public static function loadFromDatabase(?Settings $settings = null): self
183214
if ($setting === 'enabledIconTypes' && is_array($value)) {
184215
// Track which specific icon types are overridden
185216
$settings->_overriddenIconTypes = array_keys($value);
186-
217+
187218
// Only override the icon types that are in the config
188219
// Keep database values for non-specified icon types
189220
foreach ($value as $iconType => $enabled) {
@@ -197,7 +228,13 @@ public static function loadFromDatabase(?Settings $settings = null): self
197228
}
198229
}
199230
}
200-
231+
232+
// IMPORTANT: Validate settings after config overrides are applied
233+
// This will trigger validateLogLevel and other validation methods
234+
if (!$settings->validate()) {
235+
Craft::error('Icon Manager settings validation failed: ' . print_r($settings->getErrors(), true), 'icon-manager');
236+
}
237+
201238
return $settings;
202239
}
203240

@@ -281,4 +318,67 @@ public function getOverriddenIconTypes(): array
281318
{
282319
return $this->_overriddenIconTypes;
283320
}
321+
322+
/**
323+
* Check if a setting is being overridden by config file
324+
*
325+
* @param string $attribute The setting attribute name
326+
* @return bool
327+
*/
328+
public function isOverriddenByConfig(string $attribute): bool
329+
{
330+
// Get the config file path
331+
$configPath = \Craft::$app->getPath()->getConfigPath() . '/icon-manager.php';
332+
333+
if (!file_exists($configPath)) {
334+
return false;
335+
}
336+
337+
// Load the raw config file
338+
$rawConfig = require $configPath;
339+
340+
// Check if this attribute is set in the config file (root level or environment level)
341+
$hasRootConfig = array_key_exists($attribute, $rawConfig);
342+
$env = \Craft::$app->getConfig()->getGeneral()->env ?? '*';
343+
$hasEnvConfig = isset($rawConfig[$env]) && is_array($rawConfig[$env]) && array_key_exists($attribute, $rawConfig[$env]);
344+
345+
if (!$hasRootConfig && !$hasEnvConfig) {
346+
return false;
347+
}
348+
349+
350+
return true;
351+
}
352+
353+
/**
354+
* Get the raw config value (for display in settings form)
355+
*
356+
* @param string $attribute The setting attribute name
357+
* @return mixed|null
358+
*/
359+
public function getRawConfigValue(string $attribute)
360+
{
361+
// Get the config file path
362+
$configPath = \Craft::$app->getPath()->getConfigPath() . '/icon-manager.php';
363+
364+
if (!file_exists($configPath)) {
365+
return null;
366+
}
367+
368+
// Load the raw config file
369+
$rawConfig = require $configPath;
370+
371+
// Check environment-specific settings first (highest priority)
372+
$env = \Craft::$app->getConfig()->getGeneral()->env ?? '*';
373+
if (isset($rawConfig[$env]) && is_array($rawConfig[$env]) && array_key_exists($attribute, $rawConfig[$env])) {
374+
return $rawConfig[$env][$attribute];
375+
}
376+
377+
// Check root level
378+
if (array_key_exists($attribute, $rawConfig)) {
379+
return $rawConfig[$attribute];
380+
}
381+
382+
return null;
383+
}
284384
}

0 commit comments

Comments
 (0)