Completed
Pull Request — master (#32)
by
unknown
29:38
created

CommentSerializerEventSubscriber   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 6
dl 0
loc 55
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getSubscribedEvents() 0 10 1
A onPostSerialize() 0 25 4
1
<?php
2
3
/*
4
 * This file is part of Sulu.
5
 *
6
 * (c) Sulu GmbH
7
 *
8
 * This source file is subject to the MIT license that is bundled
9
 * with this source code in the file LICENSE.
10
 */
11
12
namespace Sulu\Bundle\CommentBundle\EventSubscriber;
13
14
use JMS\Serializer\EventDispatcher\Events;
15
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
16
use JMS\Serializer\EventDispatcher\ObjectEvent;
17
use Sulu\Bundle\AudienceTargetingBundle\Entity\TargetGroupRuleInterface;
18
use Sulu\Bundle\MediaBundle\Media\Manager\MediaManagerInterface;
19
use Sulu\Bundle\CommentBundle\Entity\Comment;
20
use Symfony\Component\HttpFoundation\RequestStack;
21
22
class CommentSerializerEventSubscriber implements EventSubscriberInterface
23
{
24
    /**
25
     * @var MediaManagerInterface
26
     */
27
    private $mediaManager;
28
29
    /**
30
     * @var RequestStack
31
     */
32
    private $requestStack;
33
34
    public function __construct(MediaManagerInterface $mediaManager, RequestStack $requestStack)
35
    {
36
        $this->mediaManager = $mediaManager;
37
        $this->requestStack = $requestStack;
38
    }
39
40
    public static function getSubscribedEvents()
41
    {
42
        return [
43
            [
44
                'event' => Events::POST_SERIALIZE,
45
                'format' => 'json',
46
                'method' => 'onPostSerialize',
47
            ],
48
        ];
49
    }
50
51
    public function onPostSerialize(ObjectEvent $event)
52
    {
53
        /** @var Comment $comment */
54
        $comment = $event->getObject();
55
        if (!$comment instanceof Comment || !$creator = $comment->getCreator()) {
56
            return;
57
        }
58
59
        $contact = $creator->getContact();
60
        if (!$avatar = $contact->getAvatar()) {
61
            return;
62
        }
63
64
        $avatar = $this->mediaManager->getById($avatar->getId(), $this->requestStack->getCurrentRequest()->getLocale());
65
66
        $event->getVisitor()->addData('creatorAvatar', $event->getContext()->accept([
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface JMS\Serializer\VisitorInterface as the method addData() does only exist in the following implementations of said interface: JMS\Serializer\GenericSerializationVisitor, JMS\Serializer\JsonSerializationVisitor, Sulu\Component\Serialize...raySerializationVisitor.

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...
Deprecated Code introduced by
The method JMS\Serializer\Context::accept() has been deprecated with message: Will be removed in 2.0, Use getNavigator()->accept() instead

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
67
            'id' => $avatar->getId(),
68
            'title' => $avatar->getTitle(),
69
            'description' => $avatar->getDescription(),
70
            'credits' => $avatar->getCredits(),
71
            'name' => $avatar->getName(),
72
            'formats' => $avatar->getFormats(),
73
            'url' => $avatar->getUrl(),
74
        ]));
75
    }
76
}
77