Completed
Push — 2.1 ( e2f06b...be7244 )
by Rafał
16:30 queued 06:19
created

onArticlePublish()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.8666
c 0
b 0
f 0
cc 4
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Content Bundle.
7
 *
8
 * Copyright 2019 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 2019 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\ContentBundle\EventListener;
18
19
use SWP\Bundle\ContentBundle\Event\ArticleEvent;
20
use SWP\Bundle\ContentBundle\Model\RouteInterface;
21
use SWP\Bundle\ContentBundle\Model\RouteRepositoryInterface;
22
use SWP\Bundle\CoreBundle\Model\ArticleInterface;
23
24
class AttachArticleToContentRouteListener
25
{
26
    /** @var RouteRepositoryInterface */
27
    private $routeRepository;
28
29
    public function __construct(RouteRepositoryInterface $routeRepository)
30
    {
31
        $this->routeRepository = $routeRepository;
32
    }
33
34
    public function onArticlePublish(ArticleEvent $articleEvent): void
35
    {
36
        /** @var ArticleInterface $article */
37
        $article = $articleEvent->getArticle();
38
        $route = $article->getRoute();
39
        $alreadyAttachedRoute = $this->routeRepository->findOneBy(['content' => $article]);
40
41
        if (null !== $route && !$alreadyAttachedRoute && RouteInterface::TYPE_CONTENT === $route->getType()) {
42
            $route->setContent($article);
43
            $this->routeRepository->flush();
44
        }
45
    }
46
47
    public function onArticleUnpublish(ArticleEvent $articleEvent): void
48
    {
49
        $route = $articleEvent->getArticle()->getRoute();
50
51
        if ($route && RouteInterface::TYPE_CONTENT === $route->getType()) {
52
            $route->setContent(null);
53
            $this->routeRepository->flush();
54
        }
55
    }
56
}
57