Test Failed
Pull Request — master (#1102)
by Aleksei
11:23
created

LoggerInjector::createInjection()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 5
c 1
b 0
f 0
dl 0
loc 12
rs 10
cc 3
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Spiral\Logger;
6
7
use Psr\Log\LoggerInterface;
8
use Spiral\Core\Container\InjectorInterface;
9
use Spiral\Logger\Attribute\LoggerChannel;
10
11
/**
12
 * Container injector for {@see LoggerInterface}.
13
 * Supports {@see LoggerChannel} attribute.
14
 *
15
 * @implements InjectorInterface<LoggerInterface>
16
 */
17
final class LoggerInjector implements InjectorInterface
18
{
19
    public const DEFAULT_CHANNEL = 'default';
20
21
    public function __construct(
22
        private readonly LogsInterface $factory,
23
    ) {
24
    }
25
26
    /**
27
     * @param \ReflectionParameter|string|null $context may use extended context if possible.
28
     */
29
    public function createInjection(
30
        \ReflectionClass $class,
31
        \ReflectionParameter|null|string $context = null,
32
    ): LoggerInterface {
33
        $channel = \is_object($context) ? $this->extractChannelAttribute($context) : null;
34
35
        // Check that null argument is available
36
        $channel ??= (new \ReflectionMethod($this->factory, 'getLogger'))->getParameters()[0]->allowsNull()
37
            ? null
38
            : self::DEFAULT_CHANNEL;
39
40
        return $this->factory->getLogger($channel);
0 ignored issues
show
Bug introduced by
It seems like $channel can also be of type null; however, parameter $channel of Spiral\Logger\LogsInterface::getLogger() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

40
        return $this->factory->getLogger(/** @scrutinizer ignore-type */ $channel);
Loading history...
41
    }
42
43
    /**
44
     * @return non-empty-string|null
0 ignored issues
show
Documentation Bug introduced by
The doc comment non-empty-string|null at position 0 could not be parsed: Unknown type name 'non-empty-string' at position 0 in non-empty-string|null.
Loading history...
45
     */
46
    private function extractChannelAttribute(\ReflectionParameter $parameter): ?string
47
    {
48
        /** @var \ReflectionAttribute<LoggerChannel>[] $attributes */
49
        $attributes = $parameter->getAttributes(LoggerChannel::class);
50
51
        return $attributes[0]?->newInstance()->name;
52
    }
53
}
54