Passed
Push — develop ( ac7415...37495e )
by BENARD
04:27
created

getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 2
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
1
<?php
2
namespace VideoGamesRecords\CoreBundle\EventSubscriber;
3
4
use ApiPlatform\Symfony\EventListener\EventPriorities as EventPrioritiesAlias;
5
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
6
use Symfony\Component\HttpFoundation\Request;
7
use Symfony\Component\HttpKernel\Event\RequestEvent;
8
use Symfony\Component\HttpKernel\KernelEvents;
9
use Symfony\Contracts\Translation\TranslatorInterface;
10
use VideoGamesRecords\CoreBundle\Contracts\BadgeInterface;
11
use VideoGamesRecords\CoreBundle\Entity\PlayerBadge;
12
13
final class PlayerBadgeSetTitleSubscriber implements EventSubscriberInterface, BadgeInterface
14
{
15
    private TranslatorInterface $translator;
16
17
    public function __construct(TranslatorInterface $translator)
18
    {
19
        $this->translator = $translator;
20
    }
21
22
    public static function getSubscribedEvents(): array
23
    {
24
        return [
25
            KernelEvents::REQUEST => ['setTitle', EventPrioritiesAlias::POST_READ],
26
        ];
27
    }
28
29
    /**
30
     * @param RequestEvent $event
31
     */
32
    public function setTitle(RequestEvent $event)
33
    {
34
        //dd($event->getRequest()->attributes->get('data'));
35
        $data = $event->getRequest()->attributes->get('data');
36
        $method = $event->getRequest()->getMethod();
37
38
        if ($method == Request::METHOD_GET && is_array($data) && $data[0] instanceof PlayerBadge) {
39
            foreach($data as $playerBadge) {
40
                $playerBadge->setTitle($this->getTitle($playerBadge));
41
            }
42
        }
43
    }
44
45
    /**
46
     * @param PlayerBadge $playerBadge
47
     * @return string
48
     */
49
    private function getTitle(PlayerBadge $playerBadge): string
50
    {
51
        $badge = $playerBadge->getBadge();
52
        $titleType = $this->translator->trans('badge.title.' . $badge->getType());
53
        $title = match (self::TITLES[$badge->getType()]) {
54
            self::TITLE_PLATFORM => $badge->getPlatform()
55
                ->getLibPlatform(),
56
            self::TITLE_GAME => $badge->getGame()
57
                ->getName(),
58
            self::TITLE_COUNTRY => $badge->getCountry()
59
                ->getName(),
60
            self::TITLE_TYPE_VALUE => $titleType . ' ' . $badge->getValue(),
61
            self::TITLE_VALUE_TYPE => $badge->getValue() . ' ' . $titleType,
62
            default => $badge->getType(),
63
        };
64
65
        $title .= ' ' . $this->translator->trans('badge.earnedOn') . ' ' . $playerBadge->getCreatedAt()->format('Y-m-d');
66
67
        return $title;
68
    }
69
}
70