Completed
Push — master ( e2110b...10470b )
by Paweł
14s
created

getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
rs 9.4285
cc 1
eloc 5
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 2017 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 2017 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\CoreBundle\Theme\Model\Theme;
22
use SWP\Component\Common\Serializer\SerializerInterface;
23
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
24
use Symfony\Component\Routing\RouterInterface;
25
26
final class ThemeSerializationSubscriber implements EventSubscriberInterface
27
{
28
    /**
29
     * @var RouterInterface
30
     */
31
    private $router;
32
33
    /**
34
     * @var SerializerInterface
35
     */
36
    private $serializer;
37
38
    /**
39
     * ThemeHandler constructor.
40
     *
41
     * @param RouterInterface     $router
42
     * @param SerializerInterface $serializer
43
     */
44
    public function __construct(RouterInterface $router, SerializerInterface $serializer)
45
    {
46
        $this->router = $router;
47
        $this->serializer = $serializer;
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53
    public static function getSubscribedEvents()
54
    {
55
        return [
56
            [
57
                'event' => 'serializer.post_serialize',
58
                'class' => Theme::class,
59
                'method' => 'onPostSerialize',
60
            ],
61
        ];
62
    }
63
64
    /**
65
     * @param ObjectEvent $event
66
     */
67
    public function onPostSerialize(ObjectEvent $event)
68
    {
69
        $data = $event->getObject();
70
71
        if (0 !== count($screenshots = $data->getScreenshots())) {
72
            $urlAwareScreenshots = [];
73
            foreach ($screenshots as $screenshot) {
74
                $themeName = $data->getName();
75
                if (false !== ($pos = strpos($themeName, '@'))) {
76
                    $themeName = $themeName = substr($themeName, 0, $pos);
77
                }
78
                $themeName = str_replace('/', '__', $themeName);
79
                $url = $this->router->generate(
80
                    'static_theme_screenshots',
81
                    [
82
                        'type' => 'organization',
83
                        'themeName' => $themeName,
84
                        'fileName' => str_replace('screenshots/', '', $screenshot->getPath()),
85
                    ],
86
                    UrlGeneratorInterface::ABSOLUTE_URL
87
                );
88
89
                $urlAwareScreenshot = [];
90
                $urlAwareScreenshot['url'] = $url;
91
                $urlAwareScreenshot['path'] = $screenshot->getPath();
92
                $urlAwareScreenshot['title'] = $screenshot->getTitle();
93
                $urlAwareScreenshot['description'] = $screenshot->getDescription();
94
                $urlAwareScreenshots[] = $urlAwareScreenshot;
95
            }
96
            $event->getVisitor()->setData('screenshots', $urlAwareScreenshots);
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 setData() does only exist in the following implementations of said interface: JMS\Serializer\GenericSerializationVisitor, JMS\Serializer\JsonSerializationVisitor.

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...
97
        }
98
    }
99
}
100