Completed
Push — master ( d01ad3...6b97e6 )
by Paweł
21s queued 10s
created

ContentListSerializationSubscriber::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
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 JMS\Serializer\JsonSerializationVisitor;
22
use JMS\Serializer\Metadata\StaticPropertyMetadata;
23
use SWP\Bundle\ContentListBundle\Form\Type\ContentListType;
24
use SWP\Bundle\CoreBundle\Model\ContentList;
25
use SWP\Bundle\CoreBundle\Model\ContentListItemInterface;
26
use SWP\Bundle\CoreBundle\Model\ContentListInterface;
27
use SWP\Component\ContentList\Repository\ContentListItemRepositoryInterface;
28
29
final class ContentListSerializationSubscriber implements EventSubscriberInterface
30
{
31
    private $contentListItemRepository;
32
33
    public function __construct(ContentListItemRepositoryInterface $contentListItemRepository)
34
    {
35
        $this->contentListItemRepository = $contentListItemRepository;
36
    }
37
38 View Code Duplication
    public static function getSubscribedEvents()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
39
    {
40
        return [
41
            [
42
                'event' => 'serializer.pre_serialize',
43
                'class' => ContentList::class,
44
                'method' => 'onPreSerialize',
45
            ],
46
            [
47
                'event' => 'serializer.post_serialize',
48
                'class' => ContentList::class,
49
                'method' => 'onPostSerialize',
50
            ],
51
        ];
52
    }
53
54
    public function onPreSerialize(ObjectEvent $event)
55
    {
56
        /** @var ContentListInterface $object */
57
        $object = $event->getObject();
58
        if (!$object instanceof ContentListInterface) {
59
            return;
60
        }
61
62
        $object->setFilters(ContentListType::transformArrayKeys($object->getFilters(), 'snake'));
63
    }
64
65
    public function onPostSerialize(ObjectEvent $event): void
66
    {
67
        $object = $event->getObject();
68
        /** @var JsonSerializationVisitor $visitor */
69
        $visitor = $event->getVisitor();
70
        if (!$object instanceof ContentListInterface) {
71
            return;
72
        }
73
74
        $data = [];
75
        $items = $this->contentListItemRepository->getItemsTitlesByList($object);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface SWP\Component\ContentLis...ItemRepositoryInterface as the method getItemsTitlesByList() does only exist in the following implementations of said interface: SWP\Bundle\CoreBundle\Re...ntentListItemRepository.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
76
77
        /** @var ContentListItemInterface $item */
78
        foreach ($items as $item) {
79
            $data[] = [
80
                'content' => [
81
                    'id' => $item['id'],
82
                    'title' => $item['title'],
83
                ],
84
            ];
85
        }
86
87
        $visitor->visitProperty(new StaticPropertyMetadata('', 'latest_items', null), $data);
88
    }
89
}
90