Completed
Push — master ( 4404a1...95a059 )
by Paweł
22s queued 10s
created

getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Core Bundle.
7
 *
8
 * Copyright 2019 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2019 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\Serializer;
18
19
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
20
use JMS\Serializer\EventDispatcher\ObjectEvent;
21
use SWP\Bundle\ContentListBundle\Form\Type\ContentListType;
22
use SWP\Bundle\CoreBundle\Model\ContentList;
23
use SWP\Component\Common\Criteria\Criteria;
24
use SWP\Bundle\CoreBundle\Model\ContentListInterface;
25
use SWP\Component\ContentList\Repository\ContentListItemRepositoryInterface;
26
27
final class ContentListSerializationSubscriber implements EventSubscriberInterface
28
{
29
    private $contentListItemRepository;
30
31
    public function __construct(ContentListItemRepositoryInterface $contentListItemRepository)
32
    {
33
        $this->contentListItemRepository = $contentListItemRepository;
34
    }
35
36
    public static function getSubscribedEvents()
37
    {
38
        return [
39
            [
40
                'event' => 'serializer.pre_serialize',
41
                'class' => ContentList::class,
42
                'method' => 'onPreSerialize',
43
            ],
44
        ];
45
    }
46
47
    public function onPreSerialize(ObjectEvent $event)
48
    {
49
        /** @var ContentListInterface $object */
50
        $object = $event->getObject();
51
        if (!$object instanceof ContentListInterface) {
52
            return;
53
        }
54
55
        $object->setFilters(ContentListType::transformArrayKeys($object->getFilters(), 'snake'));
56
57
        $items = $this->contentListItemRepository->getQueryByCriteria(new Criteria([
58
            'contentList' => $object,
59
        ]), ['createdAt' => 'desc'], 'n')->setMaxResults(5)->getQuery()->getResult();
60
        $object->setItems($items);
61
    }
62
}
63