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

TenantHandler::onPostSerialize()   C

Complexity

Conditions 11
Paths 24

Size

Total Lines 62

Duplication

Lines 14
Ratio 22.58 %

Importance

Changes 0
Metric Value
dl 14
loc 62
rs 6.6824
c 0
b 0
f 0
cc 11
nc 24
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Events;
20
use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
21
use JMS\Serializer\EventDispatcher\ObjectEvent;
22
use JMS\Serializer\GraphNavigatorInterface;
23
use JMS\Serializer\Handler\SubscribingHandlerInterface;
24
use JMS\Serializer\JsonSerializationVisitor;
25
use JMS\Serializer\Metadata\StaticPropertyMetadata;
26
use JMS\Serializer\Context;
27
use JMS\Serializer\SerializationContext;
28
use JMS\Serializer\SerializerInterface;
29
use SWP\Bundle\ContentBundle\Model\RouteRepositoryInterface;
30
use SWP\Bundle\CoreBundle\Context\ScopeContext;
31
use SWP\Bundle\CoreBundle\Model\Tenant;
32
use SWP\Bundle\CoreBundle\Model\TenantInterface;
33
use SWP\Bundle\SettingsBundle\Manager\SettingsManagerInterface;
34
use SWP\Component\Common\Criteria\Criteria;
35
use SWP\Component\ContentList\Repository\ContentListRepositoryInterface;
36
use SWP\Component\MultiTenancy\Context\TenantContextInterface;
37
use SWP\Component\MultiTenancy\Provider\TenantProviderInterface;
38
use Symfony\Component\HttpFoundation\RequestStack;
39
40
final class TenantHandler implements EventSubscriberInterface, SubscribingHandlerInterface
41
{
42
    private $settingsManager;
43
44
    private $requestStack;
45
46
    private $routeRepository;
47
48
    private $contentListRepository;
49
50
    private $tenantContext;
51
52
    private $internalCache = [];
53
54
    private $serializer;
55
56
    private $tenantProvider;
57
58
    public function __construct(
59
        SettingsManagerInterface $settingsManager,
60
        RequestStack $requestStack,
61
        RouteRepositoryInterface $routeRepository,
62
        ContentListRepositoryInterface $contentListRepository,
63
        TenantContextInterface $tenantContext,
64
        TenantProviderInterface $tenantProvider,
65
        SerializerInterface $serializer
66
    ) {
67
        $this->settingsManager = $settingsManager;
68
        $this->requestStack = $requestStack;
69
        $this->routeRepository = $routeRepository;
70
        $this->contentListRepository = $contentListRepository;
71
        $this->tenantContext = $tenantContext;
72
        $this->serializer = $serializer;
73
        $this->tenantProvider = $tenantProvider;
74
    }
75
76
    public static function getSubscribedEvents(): array
77
    {
78
        return [
79
            [
80
                'event' => Events::POST_SERIALIZE,
81
                'class' => Tenant::class,
82
                'method' => 'onPostSerialize',
83
            ],
84
        ];
85
    }
86
87
    public static function getSubscribingMethods(): array
88
    {
89
        return [
90
            [
91
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
92
                'format' => 'json',
93
                'type' => TenantInterface::class,
94
                'method' => 'serializeToJson',
95
            ],
96
        ];
97
    }
98
99
    public function onPostSerialize(ObjectEvent $event): void
100
    {
101
        /** @var TenantInterface $tenant */
102
        $tenant = $event->getObject();
103
        /** @var JsonSerializationVisitor $visitor */
104
        $visitor = $event->getVisitor();
105
106
        if (isset($this->internalCache[$tenant->getCode()])) {
107
            $cachedData = $this->internalCache[$tenant->getCode()];
108
            $visitor->visitProperty(new StaticPropertyMetadata('', 'fbia_enabled', null), $cachedData['settings']['fbiaEnabled']);
109
            $visitor->visitProperty(new StaticPropertyMetadata('', 'paywall_enabled', null), $cachedData['settings']['paywallEnabled']);
110
            if (isset($cachedData['routes'])) {
111
                $visitor->visitProperty(
112
                    new StaticPropertyMetadata('', 'routes', null, ['api_routes_list']),
113
                    $cachedData['routes']
114
                );
115
            }
116
            if (isset($cachedData['contentLists'])) {
117
                $visitor->visitProperty(new StaticPropertyMetadata('', 'content_lists', null), $cachedData['contentLists']);
118
            }
119
120
            return;
121
        }
122
123
        $originalTenant = $this->tenantContext->getTenant();
124
        if ($originalTenant->getCode() !== $tenant->getCode()) {
125
            $this->tenantContext->setTenant($tenant);
126
        }
127
128
        $fbiaEnabled = $this->settingsManager->get('fbia_enabled', ScopeContext::SCOPE_TENANT, $tenant, false);
129
        $paywallEnabled = $this->settingsManager->get('paywall_enabled', ScopeContext::SCOPE_TENANT, $tenant, false);
130
        $this->internalCache[$tenant->getCode()]['settings'] = [
131
            'fbiaEnabled' => $fbiaEnabled,
132
            'paywallEnabled' => $paywallEnabled,
133
        ];
134
135
        $visitor->visitProperty(new StaticPropertyMetadata('', 'fbia_enabled', null), $fbiaEnabled);
136
        $visitor->visitProperty(new StaticPropertyMetadata('', 'paywall_enabled', null), $paywallEnabled);
137
138
        $masterRequest = $this->requestStack->getMasterRequest();
139
        if (null !== $masterRequest && (null !== $masterRequest->get('withRoutes') || null !== $masterRequest->get('withContentLists'))) {
140 View Code Duplication
            if (null !== $masterRequest->get('withRoutes')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
141
                $routes = $this->routeRepository->getQueryByCriteria(new Criteria(['maxResults' => 9999]), [], 'r')->getQuery()->getResult();
142
                $routesArray = $this->serializer->toArray($routes, SerializationContext::create()->setGroups(['Default', 'api_routes_list']));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface JMS\Serializer\SerializerInterface as the method toArray() does only exist in the following implementations of said interface: JMS\Serializer\Serializer.

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...
143
                $this->internalCache[$tenant->getCode()]['routes'] = $routesArray;
144
145
                $visitor->visitProperty(new StaticPropertyMetadata('', 'routes', null, ['api_routes_list']), $routesArray);
146
            }
147
148 View Code Duplication
            if (null !== $masterRequest->get('withContentLists')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
149
                $contentLists = $this->contentListRepository->getQueryByCriteria(new Criteria(['maxResults' => 9999]), [], 'cl')->getQuery()->getResult();
150
                $contentListsArray = $this->serializer->toArray($contentLists, SerializationContext::create()->setGroups(['Default', 'api']));
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface JMS\Serializer\SerializerInterface as the method toArray() does only exist in the following implementations of said interface: JMS\Serializer\Serializer.

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...
151
                $this->internalCache[$tenant->getCode()]['contentLists'] = $contentListsArray;
152
153
                $visitor->visitProperty(new StaticPropertyMetadata('', 'content_lists', null), $contentListsArray);
154
            }
155
        }
156
157
        if ($originalTenant->getCode() !== $tenant->getCode()) {
158
            $this->tenantContext->setTenant($originalTenant);
159
        }
160
    }
161
162
    public function serializeToJson(
163
        JsonSerializationVisitor $visitor,
0 ignored issues
show
Unused Code introduced by
The parameter $visitor is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
164
        string $tenantCode,
165
        array $type,
0 ignored issues
show
Unused Code introduced by
The parameter $type is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
166
        Context $context
167
    ) {
168
        $tenant = $this->tenantProvider->findOneByCode($tenantCode);
169
        if (null === $tenant) {
170
            return;
171
        }
172
173
        $data = $context->getNavigator()->accept($tenant);
174
        unset($data['articles_count'], $data['created_at'], $data['enabled'], $data['organization'],$data['theme_name'], $data['updated_at']);
175
176
        return $data;
177
    }
178
}
179