Completed
Push — master ( e1f264...8e4abf )
by Rafał
09:21 queued 11s
created

AbstractContentPushHandler   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 150
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
wmc 19
lcom 1
cbo 12
dl 0
loc 150
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 21 1
A execute() 0 29 5
A generateLockId() 0 4 1
A doExecute() 0 35 4
A findExistingPackage() 0 14 4
A reset() 0 7 2
A logException() 0 15 2
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 2020 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 2020 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\MessageHandler;
18
19
use Doctrine\DBAL\Exception\NotNullConstraintViolationException;
20
use Doctrine\ORM\EntityManagerInterface;
21
use Doctrine\ORM\NonUniqueResultException;
22
use Psr\Log\LoggerInterface;
23
use Sentry\Breadcrumb;
24
use Sentry\State\HubInterface;
25
use SWP\Bundle\BridgeBundle\Doctrine\ORM\PackageRepository;
26
use SWP\Bundle\CoreBundle\Hydrator\PackageHydratorInterface;
27
use SWP\Bundle\CoreBundle\Model\PackageInterface;
28
use SWP\Bundle\CoreBundle\Model\Tenant;
29
use SWP\Component\Bridge\Events;
30
use SWP\Component\Bridge\Model\ItemInterface;
31
use SWP\Component\Bridge\Transformer\DataTransformerInterface;
32
use SWP\Component\MultiTenancy\Context\TenantContextInterface;
33
use Symfony\Component\Cache\ResettableInterface;
34
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
35
use Symfony\Component\EventDispatcher\GenericEvent;
36
use Symfony\Component\Lock\LockFactory;
37
use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
38
39
abstract class AbstractContentPushHandler implements MessageHandlerInterface
40
{
41
    protected $logger;
42
43
    protected $packageRepository;
44
45
    protected $eventDispatcher;
46
47
    protected $jsonToPackageTransformer;
48
49
    protected $packageObjectManager;
50
51
    protected $tenantContext;
52
53
    protected $packageHydrator;
54
55
    protected $lockFactory;
56
57
    public function __construct(
58
        LoggerInterface $logger,
59
        PackageRepository $packageRepository,
60
        EventDispatcherInterface $eventDispatcher,
61
        DataTransformerInterface $jsonToPackageTransformer,
62
        EntityManagerInterface $packageObjectManager,
63
        TenantContextInterface $tenantContext,
64
        HubInterface $sentryHub,
65
        PackageHydratorInterface $packageHydrator,
66
        LockFactory $lockFactory
67
    ) {
68
        $this->logger = $logger;
69
        $this->packageRepository = $packageRepository;
70
        $this->eventDispatcher = $eventDispatcher;
71
        $this->jsonToPackageTransformer = $jsonToPackageTransformer;
72
        $this->packageObjectManager = $packageObjectManager;
73
        $this->tenantContext = $tenantContext;
74
        $this->sentryHub = $sentryHub;
0 ignored issues
show
Bug introduced by
The property sentryHub does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
75
        $this->packageHydrator = $packageHydrator;
76
        $this->lockFactory = $lockFactory;
77
    }
78
79
    public function execute(int $tenantId, PackageInterface $package): void
80
    {
81
        $lock = $this->lockFactory->createLock($this->generateLockId($package->getGuid()), 120);
82
83
        try {
84
            if (!$lock->acquire()) {
85
                throw new LockConflictedException();
86
            }
87
88
            $this->doExecute($tenantId, $package);
89
        } catch (NonUniqueResultException | NotNullConstraintViolationException $e) {
90
            $this->logException($e, $package, 'Unhandled NonUnique or NotNullConstraint exception');
91
92
            $cacheDriver = $this->packageObjectManager->getConfiguration()->getMetadataCacheImpl();
93
            $cacheDriver->flushAll();
94
95
            throw $e;
96
        } catch (DBALException | ORMException $e) {
0 ignored issues
show
Bug introduced by
The class SWP\Bundle\CoreBundle\MessageHandler\ORMException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
97
            $this->logException($e, $package);
98
99
            throw $e;
100
        } catch (Exception $e) {
0 ignored issues
show
Bug introduced by
The class SWP\Bundle\CoreBundle\MessageHandler\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
101
            $this->logException($e, $package);
102
103
            throw $e;
104
        } finally {
105
            $this->reset();
106
        }
107
    }
108
109
    private function generateLockId(string $guid): string
110
    {
111
        return md5(json_encode(['type' => 'package', 'guid' => $guid]));
112
    }
113
114
    private function doExecute(int $tenantId, PackageInterface $package): void
115
    {
116
        $packageType = $package->getType();
117
        if (ItemInterface::TYPE_TEXT !== $packageType && ItemInterface::TYPE_COMPOSITE !== $packageType) {
118
            return;
119
        }
120
121
        $this->tenantContext->setTenant($this->packageObjectManager->find(Tenant::class, $tenantId));
0 ignored issues
show
Documentation introduced by
$this->packageObjectMana...nant::class, $tenantId) is of type object|null, but the function expects a object<SWP\Component\Mul...\Model\TenantInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
122
123
        /** @var PackageInterface $existingPackage */
124
        $existingPackage = $this->findExistingPackage($package);
125
        if (null !== $existingPackage) {
126
            $existingPackage = $this->packageHydrator->hydrate($package, $existingPackage);
127
128
            $this->eventDispatcher->dispatch(Events::PACKAGE_PRE_UPDATE, new GenericEvent($existingPackage, ['eventName' => Events::PACKAGE_PRE_UPDATE]));
129
            $this->packageObjectManager->flush();
130
            $this->eventDispatcher->dispatch(Events::PACKAGE_POST_UPDATE, new GenericEvent($existingPackage, ['eventName' => Events::PACKAGE_POST_UPDATE]));
131
            $this->eventDispatcher->dispatch(Events::PACKAGE_PROCESSED, new GenericEvent($existingPackage, ['eventName' => Events::PACKAGE_PROCESSED]));
132
            $this->packageObjectManager->flush();
133
134
            $this->reset();
135
            $this->logger->info(sprintf('Package %s was updated', $existingPackage->getGuid()));
136
137
            return;
138
        }
139
140
        $this->eventDispatcher->dispatch(Events::PACKAGE_PRE_CREATE, new GenericEvent($package, ['eventName' => Events::PACKAGE_PRE_CREATE]));
141
        $this->packageRepository->add($package);
142
        $this->eventDispatcher->dispatch(Events::PACKAGE_POST_CREATE, new GenericEvent($package, ['eventName' => Events::PACKAGE_POST_CREATE]));
143
        $this->eventDispatcher->dispatch(Events::PACKAGE_PROCESSED, new GenericEvent($package, ['eventName' => Events::PACKAGE_PROCESSED]));
144
        $this->packageObjectManager->flush();
145
146
        $this->logger->info(sprintf('Package %s was created', $package->getGuid()));
147
        $this->reset();
148
    }
149
150
    protected function findExistingPackage(PackageInterface $package)
151
    {
152
        $existingPackage = $this->packageRepository->findOneBy(['guid' => $package->getEvolvedFrom() ?? $package->getGuid()]);
153
        if (null === $existingPackage && null !== $package->getEvolvedFrom()) {
154
            $existingPackage = $this->packageRepository->findOneBy(['guid' => $package->getGuid()]);
155
        }
156
157
        if (null === $existingPackage) {
158
            // check for updated items (with evolved from)
159
            $existingPackage = $this->packageRepository->findOneBy(['evolvedFrom' => $package->getGuid()]);
160
        }
161
162
        return $existingPackage;
163
    }
164
165
    protected function reset(): void
166
    {
167
        $this->packageObjectManager->clear();
168
        if ($this->tenantContext instanceof ResettableInterface) {
169
            $this->tenantContext->reset();
170
        }
171
    }
172
173
    protected function logException(\Exception $e, PackageInterface $package, string $defaultMessage = 'Unhandled exception'): void
174
    {
175
        $this->logger->error('' !== $e->getMessage() ? $e->getMessage() : $defaultMessage, ['trace' => $e->getTraceAsString()]);
176
        $this->sentryHub->addBreadcrumb(new Breadcrumb(
177
            Breadcrumb::LEVEL_DEBUG,
178
            Breadcrumb::TYPE_DEFAULT,
179
            'publishing',
180
            'Package',
181
            [
182
                'guid' => $package->getGuid(),
183
                'headline' => $package->getHeadline(),
184
            ]
185
        ));
186
        $this->sentryHub->captureException($e);
187
    }
188
}
189