Passed
Push — main ( b15a24...935ae5 )
by Axel
04:15
created

getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula - https://ziku.la/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Zikula\ProfileBundle\EventSubscriber;
15
16
use Doctrine\Common\EventSubscriber;
17
use Doctrine\ORM\Events;
18
use Doctrine\Persistence\Event\LifecycleEventArgs;
19
use Symfony\Component\DependencyInjection\Attribute\Autowire;
20
use Zikula\ProfileBundle\Entity\Property;
21
use Zikula\UsersBundle\Entity\UserAttribute;
22
23
class AttributeNameTranslationSubscriber implements EventSubscriber
24
{
25
    private array $translations = [];
26
27
    private string $prefix;
28
29
    public function __construct(
30
        #[Autowire('%kernel.default_locale%')]
31
        private readonly string $locale,
32
        #[Autowire('%zikula_profile_module.property_prefix%')]
33
        string $prefix
34
    ) {
35
        $this->prefix = $prefix . ':';
36
    }
37
38
    public function getSubscribedEvents(): array
39
    {
40
        return [
41
            Events::postLoad,
42
        ];
43
    }
44
45
    public function postLoad(LifecycleEventArgs $args): void
46
    {
47
        $entity = $args->getObject();
48
        $entityManager = $args->getObjectManager();
49
50
        if ($entity instanceof UserAttribute) {
51
            $name = $entity->getName();
52
            if (!isset($this->translations[$this->locale][$name])) {
53
                $this->translations[$this->locale][$name] = $name;
54
                if (0 === mb_strpos($name, $this->prefix)) {
55
                    try {
56
                        $property = $entityManager->find(Property::class, mb_substr($name, mb_strlen($this->prefix)));
57
                        $this->translations[$this->locale][$name] = isset($property) ? $property->getLabel($this->locale) : $name;
58
                    } catch (\Exception $exception) {
59
                        // subscriber fails during upgrade. silently fail
60
                    }
61
                }
62
            }
63
            $entity->setExtra($this->translations[$this->locale][$name]);
64
        }
65
    }
66
}
67