From 818e2d5fc60709575b9a5ef02f97c4892d48af5f Mon Sep 17 00:00:00 2001 From: Frugan Date: Sat, 6 Sep 2025 17:10:08 +0200 Subject: [PATCH] feat: replace plugin_name arg w/ component_name --- README.md | 26 +++++----- src/Logger.php | 114 +++++++++++++++++++++---------------------- tests/HooksTest.php | 38 +++++++-------- tests/LoggerTest.php | 84 +++++++++++++++---------------- 4 files changed, 131 insertions(+), 131 deletions(-) diff --git a/README.md b/README.md index 0e366bb..eeaba2a 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,7 @@ use WpSpaghetti\WpLogger\Logger; // Initialize with minimal configuration $logger = new Logger([ - 'plugin_name' => 'my-awesome-plugin' + 'component_name' => 'my-awesome-plugin' ]); // Standard PSR-3 logging methods @@ -104,7 +104,7 @@ use WpSpaghetti\WpLogger\Logger; // Configuration can come from environment variables via WP Env $logger = new Logger([ - 'plugin_name' => 'my-plugin', + 'component_name' => 'my-plugin', 'log_retention_days' => 60, // Can be overridden by LOGGER_RETENTION_DAYS env var 'min_log_level' => 'info', // Can be overridden by LOGGER_MIN_LEVEL env var ]); @@ -132,7 +132,7 @@ class MyPlugin public function __construct() { $this->logger = new Logger([ - 'plugin_name' => 'my-plugin', + 'component_name' => 'my-plugin', 'log_retention_days' => 30 ]); @@ -172,7 +172,7 @@ WP Logger v2.0 supports multiple configuration sources with intelligent priority ```php $config = [ // Required: Unique identifier for your plugin/theme - 'plugin_name' => 'my-plugin', + 'component_name' => 'my-plugin', // Optional: Days to keep log files (default: 30) 'log_retention_days' => 60, @@ -184,11 +184,11 @@ $config = [ 'wonolog_namespace' => 'MyApp\Wonolog', // Optional: WordPress constant to disable logging - // (default: auto-generated from plugin_name) + // (default: auto-generated from component_name) 'disable_logging_constant' => 'MY_PLUGIN_DISABLE_LOGGING', // Optional: WordPress constant for retention days - // (default: auto-generated from plugin_name) + // (default: auto-generated from component_name) 'log_retention_constant' => 'MY_PLUGIN_LOG_RETENTION_DAYS' ]; ``` @@ -197,7 +197,7 @@ $config = [ ```bash # Global logger settings -LOGGER_PLUGIN_NAME=my-plugin # Plugin identifier +LOGGER_COMPONENT_NAME=my-plugin # Plugin/Theme identifier LOGGER_RETENTION_DAYS=30 # Log retention period LOGGER_MIN_LEVEL=info # Minimum log level LOGGER_DISABLED=false # Disable all logging @@ -317,7 +317,7 @@ class MyAwesomePlugin public function __construct() { $this->logger = new Logger([ - 'plugin_name' => 'my-awesome-plugin', + 'component_name' => 'my-awesome-plugin', 'log_retention_days' => 30 ]); @@ -359,7 +359,7 @@ new MyAwesomePlugin(); use WpSpaghetti\WpLogger\Logger; $theme_logger = new Logger([ - 'plugin_name' => get_template(), + 'component_name' => get_template(), 'log_retention_days' => 14 ]); @@ -393,7 +393,7 @@ class ErrorHandler public function __construct() { - $this->logger = new Logger(['plugin_name' => 'error-handler']); + $this->logger = new Logger(['component_name' => 'error-handler']); // Hook into WordPress error handling add_action('wp_die_handler', [$this, 'handle_wp_die']); @@ -541,7 +541,7 @@ add_filter('wp_logger_wonolog_action', function($action, $level, $message, $cont ```php // React to all log entries -add_action('wp_logger_logged', function($level, $message, $context, $plugin_name) { +add_action('wp_logger_logged', function($level, $message, $context, $component_name) { // Send critical errors to external monitoring if ($level === 'critical') { send_to_monitoring_service($message, $context); @@ -549,12 +549,12 @@ add_action('wp_logger_logged', function($level, $message, $context, $plugin_name }, 10, 4); // Handle fallback logging -add_action('wp_logger_fallback', function($level, $message, $context, $plugin_name) { +add_action('wp_logger_fallback', function($level, $message, $context, $component_name) { // Custom fallback when Wonolog is not available }, 10, 4); // Hook into specific log levels during fallback -add_action('wp_logger_fallback_error', function($message, $context, $plugin_name) { +add_action('wp_logger_fallback_error', function($message, $context, $component_name) { // Handle error-level logs specifically }, 10, 3); ``` diff --git a/src/Logger.php b/src/Logger.php index f7f3e92..ad1c0a5 100644 --- a/src/Logger.php +++ b/src/Logger.php @@ -57,7 +57,7 @@ class Logger implements LoggerInterface * @var array */ private const DEFAULT_CONFIG = [ - 'plugin_name' => null, // Required - can come from environment + 'component_name' => null, // Required - can come from environment 'log_retention_days' => self::DEFAULT_LOG_RETENTION_DAYS, 'wonolog_namespace' => 'Inpsyde\Wonolog', 'min_log_level' => LogLevel::DEBUG, @@ -107,26 +107,26 @@ class Logger implements LoggerInterface * Initialize logger with configuration and environment integration. * * @param array $config Configuration array with the following options: - * - plugin_name: string - Unique identifier (can come from LOGGER_PLUGIN_NAME env var) + * - component_name: string - Unique identifier (can come from LOGGER_COMPONENT_NAME env var) * - log_retention_days: int (default: 30) - Days to keep log files * - wonolog_namespace: string (default: 'Inpsyde\Wonolog') - Wonolog namespace * - min_log_level: string (default: 'debug') - Minimum log level to record * - disable_logging_constant: string - WordPress constant name to disable logging * - log_retention_constant: string - WordPress constant name for retention days * - * @throws \InvalidArgumentException When plugin_name is missing from both config and environment + * @throws \InvalidArgumentException When component_name is missing from both config and environment */ public function __construct(array $config = []) { - // Get plugin name from config or environment - $pluginName = $config['plugin_name'] ?? Environment::get('LOGGER_PLUGIN_NAME'); + // Get component name from config or environment + $componentName = $config['component_name'] ?? Environment::get('LOGGER_COMPONENT_NAME'); - if (!$pluginName || !\is_string($pluginName) || '' === trim($pluginName)) { - throw new \InvalidArgumentException('plugin_name is required in configuration or LOGGER_PLUGIN_NAME environment variable'); + if (!$componentName || !\is_string($componentName) || '' === trim($componentName)) { + throw new \InvalidArgumentException('component_name is required in configuration or LOGGER_COMPONENT_NAME environment variable'); } // Build configuration with priority: Plugin-specific env > Global env > Constants > Config array > Defaults - $this->config = $this->buildConfiguration($pluginName, $config); + $this->config = $this->buildConfiguration($componentName, $config); } /** @@ -195,7 +195,7 @@ public function log($level, $message, array $context = []): void // Allow third-party plugins to hook into all logging if (\function_exists('do_action')) { - do_action('wp_logger_logged', $level, $message, $context, $this->config['plugin_name']); + do_action('wp_logger_logged', $level, $message, $context, $this->config['component_name']); } } @@ -319,7 +319,7 @@ public function getDebugInfo(): array return [ // Basic configuration - 'plugin_name' => $this->config['plugin_name'], + 'component_name' => $this->config['component_name'], 'min_log_level' => $this->config['min_log_level'], 'log_retention_days' => $retentionDays, 'disable_constant' => $this->config['disable_logging_constant'], @@ -362,20 +362,20 @@ public function getDebugInfo(): array * * @return array */ - private function buildConfiguration(string $pluginName, array $config): array + private function buildConfiguration(string $componentName, array $config): array { // Start with defaults $finalConfig = self::DEFAULT_CONFIG; - $finalConfig['plugin_name'] = $pluginName; + $finalConfig['component_name'] = $componentName; // Merge configuration array $finalConfig = array_merge($finalConfig, $config); // Apply environment-based overrides - $this->applyEnvironmentOverrides($finalConfig, $pluginName); + $this->applyEnvironmentOverrides($finalConfig, $componentName); // Auto-generate constant names if not provided - $this->generateMissingConstants($finalConfig, $pluginName); + $this->generateMissingConstants($finalConfig, $componentName); return $finalConfig; } @@ -385,10 +385,10 @@ private function buildConfiguration(string $pluginName, array $config): array * * @param array $config */ - private function applyEnvironmentOverrides(array &$config, string $pluginName): void + private function applyEnvironmentOverrides(array &$config, string $componentName): void { // WordPress constants - $retentionConstant = $this->generateConstantName($pluginName, 'LOG_RETENTION_DAYS'); + $retentionConstant = $this->generateConstantName($componentName, 'LOG_RETENTION_DAYS'); if (\defined($retentionConstant)) { $days = \constant($retentionConstant); if (\is_int($days) && $days > 0) { @@ -413,14 +413,14 @@ private function applyEnvironmentOverrides(array &$config, string $pluginName): } // Plugin-specific environment variables (highest priority) - $pluginRetention = Environment::getInt($this->generateEnvKey($pluginName, 'LOG_RETENTION_DAYS')); - if ($pluginRetention > 0) { - $config['log_retention_days'] = $pluginRetention; + $componentRetention = Environment::getInt($this->generateEnvKey($componentName, 'LOG_RETENTION_DAYS')); + if ($componentRetention > 0) { + $config['log_retention_days'] = $componentRetention; } - $pluginMinLevel = Environment::get($this->generateEnvKey($pluginName, 'MIN_LEVEL')); - if ($pluginMinLevel) { - $config['min_log_level'] = $pluginMinLevel; + $componentMinLevel = Environment::get($this->generateEnvKey($componentName, 'MIN_LEVEL')); + if ($componentMinLevel) { + $config['min_log_level'] = $componentMinLevel; } } @@ -429,14 +429,14 @@ private function applyEnvironmentOverrides(array &$config, string $pluginName): * * @param array $config */ - private function generateMissingConstants(array &$config, string $pluginName): void + private function generateMissingConstants(array &$config, string $componentName): void { if (!$config['disable_logging_constant']) { - $config['disable_logging_constant'] = $this->generateConstantName($pluginName, 'DISABLE_LOGGING'); + $config['disable_logging_constant'] = $this->generateConstantName($componentName, 'DISABLE_LOGGING'); } if (!$config['log_retention_constant']) { - $config['log_retention_constant'] = $this->generateConstantName($pluginName, 'LOG_RETENTION_DAYS'); + $config['log_retention_constant'] = $this->generateConstantName($componentName, 'LOG_RETENTION_DAYS'); } } @@ -452,24 +452,24 @@ private function shouldLog(string $level): bool } /** - * Generate plugin-specific environment variable key. + * Generate component-specific environment variable key. */ - private function generateEnvKey(string $pluginName, string $key): string + private function generateEnvKey(string $componentName, string $key): string { - $pluginPrefix = strtoupper(preg_replace('/[^a-zA-Z0-9]/', '_', $pluginName) ?? $pluginName); + $componentPrefix = strtoupper(preg_replace('/[^a-zA-Z0-9]/', '_', $componentName) ?? $componentName); - return \sprintf('%s_%s', $pluginPrefix, $key); + return \sprintf('%s_%s', $componentPrefix, $key); } /** - * Generate properly formatted constant name from plugin name. + * Generate properly formatted constant name from component name. */ - private function generateConstantName(string $pluginName, string $suffix): string + private function generateConstantName(string $componentName, string $suffix): string { - // Convert plugin name to uppercase and replace non-alphanumeric chars with underscores - $constantBase = preg_replace('/[^a-zA-Z0-9]/', '_', $pluginName); + // Convert component name to uppercase and replace non-alphanumeric chars with underscores + $constantBase = preg_replace('/[^a-zA-Z0-9]/', '_', $componentName); if (null === $constantBase) { - $constantBase = $pluginName; + $constantBase = $componentName; } return strtoupper($constantBase).'_'.$suffix; @@ -566,8 +566,8 @@ private function logViaFallback(string $level, mixed $message, array $context): { // Allow third-party plugins to handle logging when Wonolog is not available if (\function_exists('do_action')) { - do_action('wp_logger_fallback', $level, $message, $context, $this->config['plugin_name']); - do_action('wp_logger_fallback_'.$level, $message, $context, $this->config['plugin_name']); + do_action('wp_logger_fallback', $level, $message, $context, $this->config['component_name']); + do_action('wp_logger_fallback_'.$level, $message, $context, $this->config['component_name']); } // If debug is enabled, always use error_log (developer environment) @@ -596,9 +596,9 @@ private function isLoggingDisabled(): bool return true; } - // Check plugin-specific environment variable - $pluginEnvKey = $this->generateEnvKey($this->config['plugin_name'], 'DISABLED'); - if (Environment::getBool($pluginEnvKey)) { + // Check component-specific environment variable + $componentEnvKey = $this->generateEnvKey($this->config['component_name'], 'LOGGER_DISABLED'); + if (Environment::getBool($componentEnvKey)) { return true; } @@ -670,7 +670,7 @@ private function getLogDirectory(): string $this->logDirectoryCache = ''; } else { $uploadDir = wp_upload_dir(); - $this->logDirectoryCache = $uploadDir['basedir'].'/'.$this->config['plugin_name'].'/logs'; + $this->logDirectoryCache = $uploadDir['basedir'].'/'.$this->config['component_name'].'/logs'; } } @@ -709,13 +709,13 @@ private function logToFile(string $level, mixed $message, array $context): void */ private function createLogDirectoryStructure(string $logDir): void { - $pluginDir = \dirname($logDir); + $componentDir = \dirname($logDir); if (!wp_mkdir_p($logDir)) { return; } - $this->createProtectionFiles($pluginDir, $logDir); + $this->createProtectionFiles($componentDir, $logDir); } /** @@ -764,7 +764,7 @@ private function writeLogEntry(string $logDir, string $logEntry): void private function getLogFilePath(string $logDir): string { $datePrefix = gmdate('Y-m-d'); - $hash = substr(md5($this->config['plugin_name']), 0, self::LOG_FILE_HASH_LENGTH); + $hash = substr(md5($this->config['component_name']), 0, self::LOG_FILE_HASH_LENGTH); return $logDir.'/'.$datePrefix.'_'.$hash.'.dat'; } @@ -792,7 +792,7 @@ private function logToErrorLog(string $level, mixed $message, array $context): v $logEntry = \sprintf( '%s [%s] [%s] %s', $environmentInfo, - $this->config['plugin_name'], + $this->config['component_name'], strtoupper($level), $this->formatMessage($message) ); @@ -859,9 +859,9 @@ private function formatMessage(mixed $message): string /** * Create protection files for multiple web servers. */ - private function createProtectionFiles(string $pluginDir, string $logDir): void + private function createProtectionFiles(string $componentDir, string $logDir): void { - $pluginFolder = basename($pluginDir); + $componentFolder = basename($componentDir); // Apache protection (.htaccess) $htaccessContent = "# WordPress.org compliant log protection\n"; @@ -878,7 +878,7 @@ private function createProtectionFiles(string $pluginDir, string $logDir): void $indexContent .= "// Prevents directory browsing and direct file access\n"; $indexContent .= "http_response_code(403);\n"; $indexContent .= "exit('Access denied');\n"; - file_put_contents($pluginDir.'/index.php', $indexContent); + file_put_contents($componentDir.'/index.php', $indexContent); file_put_contents($logDir.'/index.php', $indexContent); // IIS Web.config @@ -893,28 +893,28 @@ private function createProtectionFiles(string $pluginDir, string $logDir): void file_put_contents($logDir.'/web.config', $webconfigContent); // Server configuration guide with environment info - $serverConfig = $this->generateReadme($pluginFolder); + $serverConfig = $this->generateReadme($componentFolder); file_put_contents($logDir.'/README', $serverConfig); } /** * Generate complete server configuration guide with environment information. */ - private function generateReadme(string $pluginFolder): string + private function generateReadme(string $componentFolder): string { $retentionDays = $this->getLogRetentionDays(); $disableConstant = $this->config['disable_logging_constant']; $retentionConstant = $this->config['log_retention_constant']; - $pluginEnvPrefix = $this->generateEnvKey($this->config['plugin_name'], ''); + $componentEnvPrefix = $this->generateEnvKey($this->config['component_name'], ''); $config = "# LOG DIRECTORY PROTECTION CONFIGURATION\n"; $config .= "# ========================================\n\n"; - $config .= "This directory contains plugin log files and should be protected from direct access.\n"; + $config .= "This directory contains plugin/theme log files and should be protected from direct access.\n"; $config .= "The following configurations provide protection for different web servers:\n\n"; // Add server-specific configurations... $config .= "## NGINX\n"; - $config .= "location ~* /wp-content/uploads/{$pluginFolder}/logs/ {\n"; + $config .= "location ~* /wp-content/uploads/{$componentFolder}/logs/ {\n"; $config .= " deny all;\n"; $config .= " return 403;\n"; $config .= "}\n\n"; @@ -923,7 +923,7 @@ private function generateReadme(string $pluginFolder): string $config .= "# Already protected via .htaccess file (automatic)\n\n"; $config .= "## LOGGING CONTROL\n"; - $config .= "You can control plugin logging behavior via environment variables or wp-config.php:\n\n"; + $config .= "You can control plugin/theme logging behavior via environment variables or wp-config.php:\n\n"; $config .= "# Environment Variables (recommended):\n"; $config .= "# Global logger settings:\n"; @@ -932,20 +932,20 @@ private function generateReadme(string $pluginFolder): string $config .= "LOGGER_MIN_LEVEL=info\n\n"; $config .= "# Plugin-specific settings (higher priority):\n"; - $config .= $pluginEnvPrefix.'DISABLED=false'.PHP_EOL; - $config .= "{$pluginEnvPrefix}LOG_RETENTION_DAYS={$retentionDays}\n\n"; + $config .= $componentEnvPrefix.'DISABLED=false'.PHP_EOL; + $config .= "{$componentEnvPrefix}LOG_RETENTION_DAYS={$retentionDays}\n\n"; $config .= "# WordPress Constants (wp-config.php):\n"; $config .= "# Enable debug logging (uses error_log):\n"; $config .= "define('WP_DEBUG', true);\n"; $config .= "define('WP_ENVIRONMENT_TYPE', 'development'); // or 'staging', 'production'\n\n"; - $config .= "# Disable all plugin logging:\n"; + $config .= "# Disable all plugin/theme logging:\n"; $config .= "define('{$disableConstant}', true);\n\n"; $config .= "# Customize log retention period:\n"; $config .= "define('{$retentionConstant}', {$retentionDays});\n\n"; $config .= 'Generated: '.gmdate('Y-m-d H:i:s')." UTC\n"; - $config .= 'Plugin: '.$this->config['plugin_name']."\n"; + $config .= 'Plugin: '.$this->config['component_name']."\n"; $config .= 'Environment: '.Environment::getEnvironment()."\n"; $config .= "Log retention: {$retentionDays} days\n"; diff --git a/tests/HooksTest.php b/tests/HooksTest.php index b34659f..d90ca6f 100644 --- a/tests/HooksTest.php +++ b/tests/HooksTest.php @@ -44,7 +44,7 @@ public function testWonologNamespaceHookWithEnvironment(): void // Set environment namespace set_mock_env_var('LOGGER_WONOLOG_NAMESPACE', 'CustomApp\Logger'); - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); // This will trigger the hook internally when debug info is requested $logger->getDebugInfo(); @@ -88,7 +88,7 @@ class Configurator { // Mock Wonolog as active set_did_action_result($setupAction, 1); - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); // Force cache refresh $logger->refreshWonologCache(); @@ -139,7 +139,7 @@ class Configurator { set_did_action_result($setupAction, 1); $logger = new Logger([ - 'plugin_name' => 'test-plugin', + 'component_name' => 'test-plugin', 'wonolog_namespace' => $namespace, ]); @@ -177,7 +177,7 @@ public function testOverrideLogHookWithEnvironmentContext(): void set_mock_env_var('WP_ENVIRONMENT_TYPE', 'staging'); set_mock_env_var('LOGGER_MIN_LEVEL', 'warning'); - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); // Override should be called before any logging $logger->warning('This should be overridden'); @@ -208,7 +208,7 @@ public function testOverrideLogHookWithEnvironmentContext(): void public function testOverrideLogPreventsDefaultLogging(): void { - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); // Set up override to return true (prevent default logging) get_applied_filters(); @@ -243,7 +243,7 @@ public function testLoggedActionTriggeredWithEnvironmentInfo(): void // Set environment set_mock_env_var('WP_ENVIRONMENT_TYPE', 'production'); - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); $logger->notice('Test notice', ['key' => 'value']); $actions = get_triggered_actions(); @@ -255,7 +255,7 @@ public function testLoggedActionTriggeredWithEnvironmentInfo(): void $loggedActionTriggered = true; self::assertSame('notice', $action['args'][0]); // level self::assertSame(['key' => 'value'], $action['args'][2]); // context - self::assertSame('test-plugin', $action['args'][3]); // plugin_name + self::assertSame('test-plugin', $action['args'][3]); // component_name break; } @@ -270,7 +270,7 @@ public function testFallbackActionsTriggeredInDifferentEnvironments(): void set_mock_env_var('WP_ENVIRONMENT_TYPE', 'production'); set_mock_env_var('WP_DEBUG', 'false'); // Force fallback behavior - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); $logger->critical('Critical error in production'); $actions = get_triggered_actions(); @@ -303,7 +303,7 @@ public function testEnvironmentBasedHookBehaviorInFallback(): void set_mock_env_var('WP_ENVIRONMENT_TYPE', 'staging'); set_mock_env_var('LOGGER_MIN_LEVEL', 'info'); - $logger = new Logger(['plugin_name' => 'staging-test']); + $logger = new Logger(['component_name' => 'staging-test']); // Debug messages should be filtered out due to min level, not environment $logger->debug('Debug message'); // Should be filtered by min level @@ -349,7 +349,7 @@ public function testHookParameterConsistencyWithEnvironment(): void set_mock_env_var('WP_ENVIRONMENT_TYPE', 'production'); set_mock_env_var('LOGGER_WONOLOG_NAMESPACE', 'Production\Logger'); - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); $context = ['user' => 'admin', 'ip' => '192.168.1.1']; $logger->alert('Test alert message', $context); @@ -393,7 +393,7 @@ public function testHookParameterConsistencyWithEnvironment(): void self::assertSame('alert', $loggedAction['args'][0]); // level self::assertSame('Test alert message', $loggedAction['args'][1]); // message self::assertSame($context, $loggedAction['args'][2]); // context - self::assertSame('test-plugin', $loggedAction['args'][3]); // plugin_name + self::assertSame('test-plugin', $loggedAction['args'][3]); // component_name } public function testCustomWonologNamespaceFromEnvironment(): void @@ -401,7 +401,7 @@ public function testCustomWonologNamespaceFromEnvironment(): void // Set custom namespace via environment set_mock_env_var('LOGGER_WONOLOG_NAMESPACE', 'MyCustomApp\LoggerSystem'); - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); $debugInfo = $logger->getDebugInfo(); @@ -437,7 +437,7 @@ public function testHookExecutionInDifferentEnvironments(): void set_mock_env_var('WP_ENVIRONMENT_TYPE', 'production'); set_mock_env_var('WP_DEBUG', 'false'); - $logger = new Logger(['plugin_name' => 'env-test-plugin']); + $logger = new Logger(['component_name' => 'env-test-plugin']); $logger->error('Error in '.$environment); @@ -455,22 +455,22 @@ public function testHookExecutionInDifferentEnvironments(): void public function testPluginSpecificEnvironmentHooks(): void { - // Set plugin-specific environment variables - set_mock_env_var('MY_SPECIAL_PLUGIN_DISABLED', 'false'); + // Set component-specific environment variables + set_mock_env_var('MY_SPECIAL_PLUGIN_LOGGER_DISABLED', 'false'); set_mock_env_var('MY_SPECIAL_PLUGIN_LOG_RETENTION_DAYS', '14'); - $logger = new Logger(['plugin_name' => 'my-special-plugin']); + $logger = new Logger(['component_name' => 'my-special-plugin']); // Trigger logging to test environment-based configuration $logger->warning('Plugin-specific configuration test'); $debugInfo = $logger->getDebugInfo(); - // Should use plugin-specific retention from environment + // Should use component-specific retention from environment self::assertSame(14, $debugInfo['log_retention_days']); self::assertFalse($debugInfo['logging_disabled']); - // Verify hook was called with plugin-specific configuration + // Verify hook was called with component-specific configuration $actions = get_triggered_actions(); $loggedActions = array_filter($actions, static fn (array $action): bool => 'wp_logger_logged' === $action['hook']); @@ -482,7 +482,7 @@ public function testMinimumLogLevelFilteringInHooks(): void // Set minimum log level via environment set_mock_env_var('LOGGER_MIN_LEVEL', 'error'); - $logger = new Logger(['plugin_name' => 'min-level-test']); + $logger = new Logger(['component_name' => 'min-level-test']); // Try logging at different levels $logger->debug('Debug message'); // Should be filtered diff --git a/tests/LoggerTest.php b/tests/LoggerTest.php index f168d56..aca2108 100644 --- a/tests/LoggerTest.php +++ b/tests/LoggerTest.php @@ -57,13 +57,13 @@ protected function tearDown(): void public function testBasicConfiguration(): void { $logger = new Logger([ - 'plugin_name' => 'test-plugin', + 'component_name' => 'test-plugin', 'log_retention_days' => 60, ]); $config = $logger->getConfig(); - self::assertSame('test-plugin', $config['plugin_name']); + self::assertSame('test-plugin', $config['component_name']); self::assertSame(60, $config['log_retention_days']); self::assertSame('TEST_PLUGIN_DISABLE_LOGGING', $config['disable_logging_constant']); self::assertSame('TEST_PLUGIN_LOG_RETENTION_DAYS', $config['log_retention_constant']); @@ -72,7 +72,7 @@ public function testBasicConfiguration(): void public function testEnvironmentBasedConfiguration(): void { // Set environment variables - set_mock_env_var('LOGGER_PLUGIN_NAME', 'env-plugin'); + set_mock_env_var('LOGGER_COMPONENT_NAME', 'env-plugin'); set_mock_env_var('LOGGER_RETENTION_DAYS', '45'); set_mock_env_var('LOGGER_MIN_LEVEL', 'warning'); set_mock_env_var('LOGGER_WONOLOG_NAMESPACE', 'Custom\Logger'); @@ -81,7 +81,7 @@ public function testEnvironmentBasedConfiguration(): void $config = $logger->getConfig(); - self::assertSame('env-plugin', $config['plugin_name']); + self::assertSame('env-plugin', $config['component_name']); self::assertSame(45, $config['log_retention_days']); self::assertSame('warning', $config['min_log_level']); self::assertSame('Custom\Logger', $config['wonolog_namespace']); @@ -89,17 +89,17 @@ public function testEnvironmentBasedConfiguration(): void public function testPluginSpecificEnvironmentVariables(): void { - // Set plugin-specific environment variables (should override global ones) + // Set component-specific environment variables (should override global ones) set_mock_env_var('LOGGER_RETENTION_DAYS', '30'); // Global set_mock_env_var('MY_PLUGIN_LOG_RETENTION_DAYS', '90'); // Plugin-specific $logger = new Logger([ - 'plugin_name' => 'my-plugin', + 'component_name' => 'my-plugin', ]); $config = $logger->getConfig(); - // Should use plugin-specific value + // Should use component-specific value self::assertSame(90, $config['log_retention_days']); } @@ -110,7 +110,7 @@ public function testConfigurationPriority(): void \define('TEST_PLUGIN_LOG_RETENTION_DAYS', 60); // WordPress constant $logger = new Logger([ - 'plugin_name' => 'test-plugin', + 'component_name' => 'test-plugin', 'log_retention_days' => 90, // Config array ]); @@ -121,11 +121,11 @@ public function testConfigurationPriority(): void public function testDefaultConfiguration(): void { - $logger = new Logger(['plugin_name' => 'test']); + $logger = new Logger(['component_name' => 'test']); $config = $logger->getConfig(); - self::assertSame('test', $config['plugin_name']); + self::assertSame('test', $config['component_name']); self::assertSame(30, $config['log_retention_days']); // Default value self::assertSame('Inpsyde\Wonolog', $config['wonolog_namespace']); self::assertSame('debug', $config['min_log_level']); @@ -134,42 +134,42 @@ public function testDefaultConfiguration(): void public function testRequiredPluginNameValidation(): void { $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('plugin_name is required in configuration or LOGGER_PLUGIN_NAME environment variable'); + $this->expectExceptionMessage('component_name is required in configuration or LOGGER_COMPONENT_NAME environment variable'); new Logger([]); } public function testPluginNameFromEnvironment(): void { - set_mock_env_var('LOGGER_PLUGIN_NAME', 'env-test-plugin'); + set_mock_env_var('LOGGER_COMPONENT_NAME', 'env-test-plugin'); $logger = new Logger(); $config = $logger->getConfig(); - self::assertSame('env-test-plugin', $config['plugin_name']); + self::assertSame('env-test-plugin', $config['component_name']); } public function testEmptyPluginNameValidation(): void { $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('plugin_name is required in configuration or LOGGER_PLUGIN_NAME environment variable'); + $this->expectExceptionMessage('component_name is required in configuration or LOGGER_COMPONENT_NAME environment variable'); - new Logger(['plugin_name' => '']); + new Logger(['component_name' => '']); } public function testWhitespacePluginNameValidation(): void { $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('plugin_name is required in configuration or LOGGER_PLUGIN_NAME environment variable'); + $this->expectExceptionMessage('component_name is required in configuration or LOGGER_COMPONENT_NAME environment variable'); - new Logger(['plugin_name' => ' ']); + new Logger(['component_name' => ' ']); } public function testMinimumLogLevelFiltering(): void { // Set minimum level to warning $logger = new Logger([ - 'plugin_name' => 'test-plugin', + 'component_name' => 'test-plugin', 'min_log_level' => 'warning', ]); @@ -188,7 +188,7 @@ public function testMinimumLogLevelFiltering(): void public function testLoggingBehaviorWithAndWithoutWonolog(): void { - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); // Without Wonolog (fallback mode) $logger->info('Test message without Wonolog'); @@ -204,7 +204,7 @@ public function testLoggingBehaviorWithAndWithoutWonolog(): void public function testBasicLogging(): void { - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); // Test all PSR-3 log levels $logger->emergency('Emergency message'); @@ -229,7 +229,7 @@ public function testBasicLogging(): void public function testLoggingWithContext(): void { - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); $context = ['user_id' => 123, 'action' => 'login']; $logger->info('User logged in', $context); @@ -257,7 +257,7 @@ public function testFileLoggingWithEnvironmentInfo(): void // Set environment for testing set_mock_env_var('WP_ENVIRONMENT_TYPE', 'development'); - $logger = new Logger(['plugin_name' => 'file-logging-test']); + $logger = new Logger(['component_name' => 'file-logging-test']); // Verify test environment setup $uploadDir = wp_upload_dir(); @@ -290,7 +290,7 @@ public function testLoggingDisabledViaEnvironment(): void // Disable logging via environment variable set_mock_env_var('LOGGER_DISABLED', 'true'); - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); // Verify logging is disabled $debugInfo = $logger->getDebugInfo(); @@ -305,10 +305,10 @@ public function testLoggingDisabledViaEnvironment(): void public function testPluginSpecificLoggingDisabled(): void { - // Disable logging for specific plugin - set_mock_env_var('TEST_PLUGIN_DISABLED', 'true'); + // Disable logging for specific component + set_mock_env_var('TEST_PLUGIN_LOGGER_DISABLED', 'true'); - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); // Verify logging is disabled $debugInfo = $logger->getDebugInfo(); @@ -321,14 +321,14 @@ public function testEnhancedDebugInfo(): void set_mock_env_var('LOGGER_MIN_LEVEL', 'warning'); $logger = new Logger([ - 'plugin_name' => 'debug-test', + 'component_name' => 'debug-test', 'log_retention_days' => 45, ]); $debugInfo = $logger->getDebugInfo(); // Test basic configuration - self::assertArrayHasKey('plugin_name', $debugInfo); + self::assertArrayHasKey('component_name', $debugInfo); self::assertArrayHasKey('min_log_level', $debugInfo); self::assertArrayHasKey('log_retention_days', $debugInfo); @@ -346,7 +346,7 @@ public function testEnhancedDebugInfo(): void self::assertArrayHasKey('wp_multisite', $debugInfo); // Test values - self::assertSame('debug-test', $debugInfo['plugin_name']); + self::assertSame('debug-test', $debugInfo['component_name']); self::assertSame('warning', $debugInfo['min_log_level']); self::assertSame('staging', $debugInfo['environment_type']); self::assertTrue($debugInfo['is_staging']); @@ -359,12 +359,12 @@ public function testProtectionFilesWithEnvironmentInfo(): void set_mock_env_var('WP_ENVIRONMENT_TYPE', 'production'); set_mock_env_var('WP_DEBUG', 'false'); - $logger = new Logger(['plugin_name' => 'protection-files-test']); + $logger = new Logger(['component_name' => 'protection-files-test']); $logger->info('Create protection files'); - $pluginDir = $this->testLogDir.'/protection-files-test'; - $logDir = $pluginDir.'/logs'; + $componentDir = $this->testLogDir.'/protection-files-test'; + $logDir = $componentDir.'/logs'; // Check that directory exists first self::assertDirectoryExists($logDir, 'Log directory should be created'); @@ -373,7 +373,7 @@ public function testProtectionFilesWithEnvironmentInfo(): void self::assertFileExists($logDir.'/.htaccess'); self::assertFileExists($logDir.'/web.config'); self::assertFileExists($logDir.'/index.php'); - self::assertFileExists($pluginDir.'/index.php'); + self::assertFileExists($componentDir.'/index.php'); self::assertFileExists($logDir.'/README'); // Check README includes environment information @@ -387,7 +387,7 @@ public function testProtectionFilesWithEnvironmentInfo(): void public function testWonologNotActiveByDefault(): void { - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); $debugInfo = $logger->getDebugInfo(); @@ -397,7 +397,7 @@ public function testWonologNotActiveByDefault(): void public function testWonologCacheRefresh(): void { - $logger = new Logger(['plugin_name' => 'test-plugin']); + $logger = new Logger(['component_name' => 'test-plugin']); // Initial state self::assertFalse($logger->getDebugInfo()['wonolog_active']); @@ -421,7 +421,7 @@ public function testCustomRetentionDays(): void // Define custom retention via environment set_mock_env_var('TEST_PLUGIN_LOG_RETENTION_DAYS', '90'); - $logger = new Logger(['plugin_name' => 'test_plugin']); + $logger = new Logger(['component_name' => 'test_plugin']); $debugInfo = $logger->getDebugInfo(); self::assertSame(90, $debugInfo['log_retention_days']); @@ -429,7 +429,7 @@ public function testCustomRetentionDays(): void public function testConstantNameGeneration(): void { - // Test with various plugin name formats + // Test with various component name formats $testCases = [ 'simple' => 'SIMPLE_DISABLE_LOGGING', 'with-dashes' => 'WITH_DASHES_DISABLE_LOGGING', @@ -438,8 +438,8 @@ public function testConstantNameGeneration(): void 'numbers123' => 'NUMBERS123_DISABLE_LOGGING', ]; - foreach ($testCases as $pluginName => $expectedConstant) { - $logger = new Logger(['plugin_name' => $pluginName]); + foreach ($testCases as $componentName => $expectedConstant) { + $logger = new Logger(['component_name' => $componentName]); $config = $logger->getConfig(); self::assertSame($expectedConstant, $config['disable_logging_constant']); @@ -452,7 +452,7 @@ public function testLogCleanupWithEnvironmentRetention(): void set_mock_env_var('CLEANUP_TEST_LOG_RETENTION_DAYS', '1'); // 1 day retention set_wp_rand_result(1); // Force cleanup to run - $logger = new Logger(['plugin_name' => 'cleanup-test']); + $logger = new Logger(['component_name' => 'cleanup-test']); // Create old log file $logDir = $this->testLogDir.'/cleanup-test/logs'; @@ -476,7 +476,7 @@ public function testFallbackLoggingBehaviorInDifferentEnvironments(): void // Test debug environment (should use error_log) set_mock_env_var('WP_DEBUG', 'true'); - $debugLogger = new Logger(['plugin_name' => 'debug-test']); + $debugLogger = new Logger(['component_name' => 'debug-test']); // Verify it's in debug mode $debugInfo = $debugLogger->getDebugInfo(); @@ -486,7 +486,7 @@ public function testFallbackLoggingBehaviorInDifferentEnvironments(): void set_mock_env_var('WP_DEBUG', 'false'); set_mock_env_var('WP_ENVIRONMENT_TYPE', 'production'); - $prodLogger = new Logger(['plugin_name' => 'prod-test']); + $prodLogger = new Logger(['component_name' => 'prod-test']); $debugInfo = $prodLogger->getDebugInfo(); self::assertTrue($debugInfo['is_production']);