Skip to content

Commit 412f564

Browse files
committed
Add callable support to loggers map
1 parent 25c5895 commit 412f564

File tree

4 files changed

+8
-3
lines changed

4 files changed

+8
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/).
1010
- Implicitly marking parameters as nullable is deprecated, the explicit nullable type must be used instead
1111

1212
### Added
13+
- Loggers map callable members
1314
- PHP 8.4 mainline support
1415
- PHP 8.5 experimental support
1516

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,9 +65,9 @@ return [
6565
],
6666
'loggers' => [
6767
// For suitable logger injections use map, where keys are your services, that implement LoggerAwareInterface
68-
// and value is logger instances
68+
// and value is logger instances or callable with logic for instantiate it.
6969
LoggerAwareClass::class => $logger,
70-
AnotherLoggerAwareClass::class => $anotherLogger,
70+
AnotherLoggerAwareClass::class => fn(\Psr\Container\ContainerInterface $container) => new \Psr\Log\NullLogger(),
7171
],
7272
];
7373
```

src/Injector.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,9 @@ public function createInstance($class): object
8787
if ($this->isLoggerInjectionRequired($instance)) {
8888
if(array_key_exists($class, $this->loggersMap)) {
8989
$logger = $this->loggersMap[$class];
90+
if(!$logger instanceof LoggerInterface && is_callable($logger)) {
91+
$logger = $logger($this);
92+
}
9093
} else {
9194
$logger = $this->getService(LoggerInterface::class);
9295
}

tests/InjectorTest.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,13 +232,14 @@ public function testLoggerMap()
232232
{
233233
$logger = new NullLogger();
234234
$anotherLogger = new NullLogger();
235+
$anotherLoggerCallable = fn() => $anotherLogger;
235236

236237
$injector = new Injector();
237238
$injector->allowInstantiateNotRegisteredTypes(true);
238239
$injector->enableLoggerAwareInjection();
239240
$injector->setLoggersMap([
240241
LoggerAwareClass::class => $logger,
241-
AnotherLoggerAwareClass::class => $anotherLogger,
242+
AnotherLoggerAwareClass::class => $anotherLoggerCallable,
242243
]);
243244

244245
/** @var LoggerAwareClass $loggerAwareInstance */

0 commit comments

Comments
 (0)