Skip to content

Commit 98e9e7c

Browse files
committed
refactor: improve logging factories and extend test coverage
- Refactored LoggerProcessorFactory and LoggerHandlerFactory to handle missing or empty processor/handler configurations gracefully without throwing exceptions. - Enhanced configurability and flexibility by improving initialization methods for logging components. - Added new unit tests for QueryLogger, MetricsProcessor, AnonymizerProcessor, and EncryptionProcessor, increasing overall test coverage. - Removed obsolete LoggerHandlerFactory test under Formatter namespace. - Updated mock expectations and assertions in existing tests for handlers and processors to ensure accurate and consistent behavior. - Cleaned up unnecessary dependencies and ensured better isolation in test cases.
1 parent fa62914 commit 98e9e7c

22 files changed

+534
-119
lines changed

src/Handler/LoggerHandlerFactory.php

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

77
use KaririCode\Contract\Logging\LogHandler;
88
use KaririCode\Logging\Contract\LoggerConfigurableFactory;
9-
use KaririCode\Logging\Exception\LoggingException;
109
use KaririCode\Logging\LoggerConfiguration;
1110
use KaririCode\Logging\LogLevel;
1211
use KaririCode\Logging\Util\ReflectionFactoryTrait;
@@ -20,12 +19,7 @@ class LoggerHandlerFactory implements LoggerConfigurableFactory
2019

2120
public function initializeFromConfiguration(LoggerConfiguration $config): void
2221
{
23-
$this->handlerMap = $config->get('handlers', [
24-
'file' => FileHandler::class,
25-
'console' => ConsoleHandler::class,
26-
'slack' => SlackHandler::class,
27-
'syslog' => SyslogUdpHandler::class,
28-
]);
22+
$this->handlerMap = $config->get('handlers', []);
2923

3024
$this->config = $config;
3125
}
@@ -34,10 +28,6 @@ public function createHandlers(string $handlerName): array
3428
{
3529
$handlersConfig = $this->getHandlersConfig($handlerName);
3630

37-
if (empty($handlersConfig)) {
38-
throw new LoggingException("No handlers configured for channel: $handlerName");
39-
}
40-
4131
$handlers = [];
4232
foreach ($handlersConfig as $key => $value) {
4333
[$handlerName, $handlerOptions] = $this->extractMergedConfig($key, $value);

src/Processor/LoggerProcessorFactory.php

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -18,14 +18,7 @@ class LoggerProcessorFactory implements LoggerConfigurableFactory
1818

1919
public function initializeFromConfiguration(LoggerConfiguration $config): void
2020
{
21-
$this->processorMap = $config->get('processors', [
22-
'introspection' => IntrospectionProcessor::class,
23-
'memory_usage_processor' => Metric\MemoryUsageProcessor::class,
24-
'execution_time_processor' => Metric\ExecutionTimeProcessor::class,
25-
'cpu_usage_processor' => Metric\CpuUsageProcessor::class,
26-
'metrics_processor' => MetricsProcessor::class,
27-
'web_processor' => WebProcessor::class,
28-
]);
21+
$this->processorMap = $config->get('processors', []);
2922

3023
$this->config = $config;
3124
}
@@ -47,14 +40,14 @@ private function getProcessorsConfig(string $channelName): array
4740
$channelProcessorConfig = $this->getChannelProcessorsConfig($channelName);
4841
$optionalProcessorConfig = $this->getOptionalProcessorsConfig($channelName);
4942

50-
return array_merge($channelProcessorConfig ?? [], $optionalProcessorConfig ?? []);
43+
return array_merge($channelProcessorConfig, $optionalProcessorConfig);
5144
}
5245

53-
private function getChannelProcessorsConfig(string $channelName): ?array
46+
private function getChannelProcessorsConfig(string $channelName): array
5447
{
5548
$channelConfigs = $this->config->get('channels', []);
5649

57-
return $channelConfigs[$channelName]['processors'] ?? null;
50+
return $channelConfigs[$channelName]['processors'] ?? [];
5851
}
5952

6053
private function getOptionalProcessorsConfig(string $channelName): ?array
@@ -89,4 +82,9 @@ private function getProcessorConfig(string $processorName, array $channelConfig)
8982

9083
return array_merge($defaultConfig, $channelConfig);
9184
}
85+
86+
public function getProcessorMap(): array
87+
{
88+
return $this->processorMap;
89+
}
9290
}

src/Util/CurlClient.php

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,10 @@ public function post(string $url, array $data, array $headers = []): array
3535
*/
3636
private function setPostOptions(\CurlHandle $ch, array $data, array $headers): void
3737
{
38-
try {
39-
$payload = json_encode($data, JSON_THROW_ON_ERROR);
40-
} catch (\JsonException $e) {
41-
throw new \JsonException('Failed to encode data: ' . $e->getMessage(), $e->getCode(), $e);
42-
}
38+
$payload = json_encode($data, JSON_THROW_ON_ERROR);
39+
40+
$defaultHeaders = ['Content-Type: application/json'];
41+
$headers = array_merge($defaultHeaders, $headers);
4342

4443
curl_setopt_array($ch, [
4544
CURLOPT_POST => true,

tests/Handler/AbstractHandlerTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
declare(strict_types=1);
44

5-
namespace KaririCode\Logging\Tests\KaririCode\Logging\Handler;
5+
namespace KaririCode\Logging\KaririCode\Logging\Tests\Logging\Handler;
66

77
use KaririCode\Contract\ImmutableValue;
88
use KaririCode\Contract\Logging\LogFormatter;

tests/Handler/ConsoleHandlerTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
declare(strict_types=1);
44

5-
namespace KaririCode\Logging\Tests\KaririCode\Logging\Handler;
5+
namespace KaririCode\Logging\KaririCode\Logging\Tests\Logging\Handler;
66

77
use KaririCode\Contract\Logging\LogFormatter;
88
use KaririCode\Logging\Formatter\ConsoleColorFormatter;

tests/Formatter/LoggerHandlerFactoryTest.php renamed to tests/Handler/LoggerHandlerFactoryTest.php

Lines changed: 5 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,8 @@
22

33
declare(strict_types=1);
44

5-
namespace Tests\KaririCode\Logging\Handler;
5+
namespace KaririCode\Logging\Tests\Handler;
66

7-
use KaririCode\Logging\Exception\LoggingException;
87
use KaririCode\Logging\Handler\ConsoleHandler;
98
use KaririCode\Logging\Handler\FileHandler;
109
use KaririCode\Logging\Handler\LoggerHandlerFactory;
@@ -13,7 +12,7 @@
1312
use KaririCode\Logging\Util\SlackClient;
1413
use PHPUnit\Framework\TestCase;
1514

16-
class LoggerHandlerFactoryTest extends TestCase
15+
final class LoggerHandlerFactoryTest extends TestCase
1716
{
1817
private LoggerHandlerFactory $loggerHandlerFactory;
1918
private LoggerConfiguration $config;
@@ -107,32 +106,8 @@ public function testCreateHandlersForSlackChannel(): void
107106

108107
public function testCreateHandlersForNonExistingChannel(): void
109108
{
110-
$this->expectException(LoggingException::class);
111-
$this->expectExceptionMessage('No handlers configured for channel: non_existing');
112-
113-
$config = new LoggerConfiguration();
114-
$config->set('channels', [
115-
'existing_channel' => [
116-
'handlers' => ['file'],
117-
],
118-
]);
119-
120-
$loggerHandlerFactory = new LoggerHandlerFactory();
121-
$loggerHandlerFactory->initializeFromConfiguration($config);
122-
123-
$loggerHandlerFactory->createHandlers('non_existing');
124-
}
125-
126-
public function testCreateHandlersWithInvalidHandler(): void
127-
{
128-
$this->config->set('handlers', [
129-
'invalid' => 'NonExistentHandlerClass',
130-
]);
131-
$this->loggerHandlerFactory->initializeFromConfiguration($this->config);
132-
133-
$this->expectException(LoggingException::class);
134-
$this->expectExceptionMessage('No handlers configured for channel: invalid');
135-
136-
$this->loggerHandlerFactory->createHandlers('invalid');
109+
$handlers = $this->loggerHandlerFactory->createHandlers('non_existing');
110+
$this->assertIsArray($handlers);
111+
$this->assertEmpty($handlers); // Verifica se o array está vazio
137112
}
138113
}

tests/Handler/SlackHandlerTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
declare(strict_types=1);
44

5-
namespace Tests\KaririCode\Logging\Handler;
5+
namespace KaririCode\Logging\Tests\Logging\Handler;
66

77
use KaririCode\Contract\Logging\LogFormatter;
88
use KaririCode\Logging\Handler\SlackHandler;

tests/Handler/SyslogUdpHandlerTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
declare(strict_types=1);
66

7-
namespace KaririCode\Logging\Tests\KaririCode\Logging\Handler;
7+
namespace KaririCode\Logging\KaririCode\Logging\Tests\Logging\Handler;
88

99
use KaririCode\Contract\Logging\LogFormatter;
1010
use KaririCode\Logging\Handler\SyslogUdpHandler;

tests/Logger/LoggerFactoryTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
declare(strict_types=1);
44

5-
namespace Tests\KaririCode\Logging;
5+
namespace KaririCode\Logging\Tests\Logging;
66

77
use KaririCode\Contract\Logging\Logger;
88
use KaririCode\Logging\Decorator\AsyncLogger;

tests/Logger/QueryLoggerTest.php

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
<?php
2+
3+
namespace KaririCode\Logging\Tests;
4+
5+
use KaririCode\Contract\Logging\Logger;
6+
use KaririCode\Logging\QueryLogger;
7+
use PHPUnit\Framework\MockObject\MockObject;
8+
use PHPUnit\Framework\TestCase;
9+
10+
final class QueryLoggerTest extends TestCase
11+
{
12+
private QueryLogger $queryLogger;
13+
private Logger|MockObject $logger;
14+
15+
protected function setUp(): void
16+
{
17+
/** @var Logger */
18+
$this->logger = $this->createMock(Logger::class);
19+
$this->queryLogger = new QueryLogger($this->logger, 100);
20+
}
21+
22+
public function testLogSlowQuery(): void
23+
{
24+
$query = 'SELECT * FROM users WHERE id = ?';
25+
$bindings = [1];
26+
$executionTime = 150.0;
27+
28+
$this->logger->expects($this->once())
29+
->method('warning')
30+
->with(
31+
'Slow query detected',
32+
[
33+
'query' => $query,
34+
'bindings' => $bindings,
35+
'time' => $executionTime,
36+
]
37+
);
38+
39+
$this->queryLogger->log($query, $bindings, $executionTime);
40+
}
41+
42+
public function testLogFastQuery(): void
43+
{
44+
$query = 'SELECT * FROM users WHERE id = ?';
45+
$bindings = [1];
46+
$executionTime = 50.0;
47+
48+
$this->logger->expects($this->once())
49+
->method('debug')
50+
->with(
51+
'Query executed',
52+
[
53+
'query' => $query,
54+
'bindings' => $bindings,
55+
'time' => $executionTime,
56+
]
57+
);
58+
59+
$this->queryLogger->log($query, $bindings, $executionTime);
60+
}
61+
}

tests/Processor/AbstractProcessorTest.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
declare(strict_types=1);
44

5-
namespace KaririCode\Logging\Tests\KaririCode\Logging\Processor;
5+
namespace KaririCode\Logging\KaririCode\Logging\Tests\Logging\Processor;
66

77
use KaririCode\Contract\ImmutableValue;
88
use KaririCode\Contract\Logging\LogProcessor;
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
use KaririCode\Logging\LogLevel;
6+
use KaririCode\Logging\LogRecord;
7+
use KaririCode\Logging\Processor\AnonymizerProcessor;
8+
use KaririCode\Logging\Security\Anonymizer;
9+
use PHPUnit\Framework\MockObject\MockObject;
10+
use PHPUnit\Framework\TestCase;
11+
12+
class AnonymizerProcessorTest extends TestCase
13+
{
14+
private Anonymizer|MockObject $anonymizer;
15+
private AnonymizerProcessor $processor;
16+
17+
protected function setUp(): void
18+
{
19+
/** @var Anonymizer */
20+
$this->anonymizer = $this->createMock(Anonymizer::class);
21+
$this->processor = new AnonymizerProcessor($this->anonymizer);
22+
}
23+
24+
public function testProcessAnonymizesEmail(): void
25+
{
26+
// Setup
27+
$message = 'Sensitive information: user@example.com';
28+
$anonymizedMessage = 'Sensitive information: us****@example.com';
29+
30+
$this->anonymizer->expects($this->once())
31+
->method('anonymize')
32+
->with($message)
33+
->willReturn($anonymizedMessage);
34+
35+
$record = new LogRecord(
36+
LogLevel::INFO,
37+
$message,
38+
[],
39+
new DateTimeImmutable()
40+
);
41+
42+
$result = $this->processor->process($record);
43+
44+
$this->assertInstanceOf(LogRecord::class, $result);
45+
$this->assertEquals($anonymizedMessage, $result->message);
46+
}
47+
48+
public function testProcessAnonymizesIp(): void
49+
{
50+
$message = 'Sensitive information: 192.168.0.1';
51+
$anonymizedMessage = 'Sensitive information: ***.***.***.***';
52+
53+
$this->anonymizer->expects($this->once())
54+
->method('anonymize')
55+
->with($message)
56+
->willReturn($anonymizedMessage);
57+
58+
$record = new LogRecord(
59+
LogLevel::INFO,
60+
$message,
61+
[],
62+
new DateTimeImmutable()
63+
);
64+
65+
$result = $this->processor->process($record);
66+
67+
$this->assertEquals($anonymizedMessage, $result->message);
68+
}
69+
70+
public function testProcessAnonymizesCreditCard(): void
71+
{
72+
$message = 'Sensitive information: 4111 1111 1111 1111';
73+
$anonymizedMessage = 'Sensitive information: **** **** **** 1111';
74+
75+
$this->anonymizer->expects($this->once())
76+
->method('anonymize')
77+
->with($message)
78+
->willReturn($anonymizedMessage);
79+
80+
$record = new LogRecord(
81+
LogLevel::INFO,
82+
$message,
83+
[],
84+
new DateTimeImmutable()
85+
);
86+
87+
$result = $this->processor->process($record);
88+
89+
$this->assertEquals($anonymizedMessage, $result->message);
90+
}
91+
92+
public function testProcessDoesNotChangeContextOrDateTime(): void
93+
{
94+
$message = 'Sensitive information';
95+
$anonymizedMessage = 'Anonymized information';
96+
97+
$this->anonymizer->expects($this->once())
98+
->method('anonymize')
99+
->with($message)
100+
->willReturn($anonymizedMessage);
101+
102+
$context = ['some_key' => 'some_value'];
103+
$datetime = new DateTimeImmutable();
104+
$record = new LogRecord(
105+
LogLevel::INFO,
106+
$message,
107+
$context,
108+
$datetime
109+
);
110+
111+
$result = $this->processor->process($record);
112+
113+
$this->assertEquals($context, $result->context);
114+
$this->assertEquals($datetime, $result->datetime);
115+
}
116+
}

0 commit comments

Comments
 (0)