Completed
Push — master ( f785fb...b21f25 )
by Rafał
09:51
created

AbstractContentPushHandler::execute()   A

Complexity

Conditions 4
Paths 10

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 23
rs 9.552
c 0
b 0
f 0
cc 4
nc 10
nop 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\Messenger\Handler\MessageHandlerInterface;
37
38
abstract class AbstractContentPushHandler implements MessageHandlerInterface
39
{
40
    protected $logger;
41
42
    protected $packageRepository;
43
44
    protected $eventDispatcher;
45
46
    protected $jsonToPackageTransformer;
47
48
    protected $packageObjectManager;
49
50
    protected $tenantContext;
51
52
    protected $packageHydrator;
53
54
    public function __construct(
55
        LoggerInterface $logger,
56
        PackageRepository $packageRepository,
57
        EventDispatcherInterface $eventDispatcher,
58
        DataTransformerInterface $jsonToPackageTransformer,
59
        EntityManagerInterface $packageObjectManager,
60
        TenantContextInterface $tenantContext,
61
        HubInterface $sentryHub,
62
        PackageHydratorInterface $packageHydrator
63
    ) {
64
        $this->logger = $logger;
65
        $this->packageRepository = $packageRepository;
66
        $this->eventDispatcher = $eventDispatcher;
67
        $this->jsonToPackageTransformer = $jsonToPackageTransformer;
68
        $this->packageObjectManager = $packageObjectManager;
69
        $this->tenantContext = $tenantContext;
70
        $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...
71
        $this->packageHydrator = $packageHydrator;
72
    }
73
74
    public function execute(int $tenantId, PackageInterface $package): void
75
    {
76
        try {
77
            $this->doExecute($tenantId, $package);
78
        } catch (NonUniqueResultException | NotNullConstraintViolationException $e) {
79
            $this->logException($e, $package, 'Unhandled NonUnique or NotNullConstraint exception');
80
81
            $cacheDriver = $this->packageObjectManager->getConfiguration()->getMetadataCacheImpl();
82
            $cacheDriver->flushAll();
83
84
            throw $e;
85
        } 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...
86
            $this->logException($e, $package);
87
88
            throw $e;
89
        } 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...
90
            $this->logException($e, $package);
91
92
            throw $e;
93
        } finally {
94
            $this->reset();
95
        }
96
    }
97
98
    private function doExecute(int $tenantId, PackageInterface $package): void
99
    {
100
        $packageType = $package->getType();
101
        if (ItemInterface::TYPE_TEXT !== $packageType && ItemInterface::TYPE_COMPOSITE !== $packageType) {
102
            return;
103
        }
104
105
        $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...
106
107
        /** @var PackageInterface $existingPackage */
108
        $existingPackage = $this->findExistingPackage($package);
109
        if (null !== $existingPackage) {
110
            $existingPackage = $this->packageHydrator->hydrate($package, $existingPackage);
111
112
            $this->eventDispatcher->dispatch(Events::PACKAGE_PRE_UPDATE, new GenericEvent($existingPackage, ['eventName' => Events::PACKAGE_PRE_UPDATE]));
113
            $this->packageObjectManager->flush();
114
            $this->eventDispatcher->dispatch(Events::PACKAGE_POST_UPDATE, new GenericEvent($existingPackage, ['eventName' => Events::PACKAGE_POST_UPDATE]));
115
            $this->eventDispatcher->dispatch(Events::PACKAGE_PROCESSED, new GenericEvent($existingPackage, ['eventName' => Events::PACKAGE_PROCESSED]));
116
            $this->packageObjectManager->flush();
117
118
            $this->reset();
119
            $this->logger->info(sprintf('Package %s was updated', $existingPackage->getGuid()));
120
121
            return;
122
        }
123
124
        $this->eventDispatcher->dispatch(Events::PACKAGE_PRE_CREATE, new GenericEvent($package, ['eventName' => Events::PACKAGE_PRE_CREATE]));
125
        $this->packageRepository->add($package);
126
        $this->eventDispatcher->dispatch(Events::PACKAGE_POST_CREATE, new GenericEvent($package, ['eventName' => Events::PACKAGE_POST_CREATE]));
127
        $this->eventDispatcher->dispatch(Events::PACKAGE_PROCESSED, new GenericEvent($package, ['eventName' => Events::PACKAGE_PROCESSED]));
128
        $this->packageObjectManager->flush();
129
130
        $this->logger->info(sprintf('Package %s was created', $package->getGuid()));
131
        $this->reset();
132
    }
133
134
    protected function findExistingPackage(PackageInterface $package)
135
    {
136
        $existingPackage = $this->packageRepository->findOneBy(['guid' => $package->getEvolvedFrom() ?? $package->getGuid()]);
137
        if (null === $existingPackage && null !== $package->getEvolvedFrom()) {
138
            $existingPackage = $this->packageRepository->findOneBy(['guid' => $package->getGuid()]);
139
        }
140
141
        if (null === $existingPackage) {
142
            // check for updated items (with evolved from)
143
            $existingPackage = $this->packageRepository->findOneBy(['evolvedFrom' => $package->getGuid()]);
144
        }
145
146
        return $existingPackage;
147
    }
148
149
    protected function reset(): void
150
    {
151
        $this->packageObjectManager->clear();
152
        if ($this->tenantContext instanceof ResettableInterface) {
153
            $this->tenantContext->reset();
154
        }
155
    }
156
157
    protected function logException(\Exception $e, PackageInterface $package, string $defaultMessage = 'Unhandled exception'): void
158
    {
159
        $this->logger->error('' !== $e->getMessage() ? $e->getMessage() : $defaultMessage, ['trace' => $e->getTraceAsString()]);
160
        $this->sentryHub->addBreadcrumb(new Breadcrumb(
161
            Breadcrumb::LEVEL_DEBUG,
162
            Breadcrumb::TYPE_DEFAULT,
163
            'publishing',
164
            'Package',
165
            [
166
                'guid' => $package->getGuid(),
167
                'headline' => $package->getHeadline(),
168
            ]
169
        ));
170
        $this->sentryHub->captureException($e);
171
    }
172
}
173