LogIdentifierExtractor   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 19
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 19
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A getIdentifierValue() 0 13 3
1
<?php
2
3
namespace Locastic\Loggastic\Identifier;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use Doctrine\Persistence\Mapping\MappingException;
7
use Symfony\Component\Messenger\Exception\HandlerFailedException;
8
9
// Used for setting collection keys in activity logs data
10
final class LogIdentifierExtractor implements LogIdentifierExtractorInterface
11
{
12
    public function __construct(private readonly EntityManagerInterface $entityManager)
13
    {
14
    }
15
16
    public function getIdentifierValue(object $object): int|string|null
17
    {
18
        try {
19
            $metadata = $this->entityManager->getClassMetadata(get_class($object));
20
            $entityClass = $metadata->getName();
21
22
            $identifier = $this->entityManager->getClassMetadata($entityClass)->getSingleIdentifierFieldName();
23
            $identifierGetter = 'get' . $identifier;
24
25
            return $object->$identifierGetter();
26
        } catch (MappingException|HandlerFailedException) {
27
            // object not mapped to doctrine, try with getId method or return null
28
            return method_exists($object, 'getId') ? $object->getId() : null;
29
        }
30
    }
31
}
32