Completed
Push — master ( 61044a...94728c )
by Rafał
24:26 queued 10:49
created

RelatedArticleOrganizationController::getRelated()   B

Complexity

Conditions 8
Paths 6

Size

Total Lines 39

Duplication

Lines 3
Ratio 7.69 %

Importance

Changes 0
Metric Value
dl 3
loc 39
rs 8.0515
c 0
b 0
f 0
cc 8
nc 6
nop 1
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 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\CoreBundle\Controller;
18
19
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
20
use SWP\Bundle\CoreBundle\Model\PackageInterface;
21
use SWP\Bundle\CoreBundle\Model\RelatedArticleList;
22
use SWP\Bundle\CoreBundle\Model\RelatedArticleListItem;
23
use SWP\Bundle\MultiTenancyBundle\MultiTenancyEvents;
24
use SWP\Component\Bridge\Model\GroupInterface;
25
use SWP\Component\Common\Exception\NotFoundHttpException;
26
use SWP\Component\Common\Response\SingleResourceResponse;
27
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
28
use Symfony\Component\HttpFoundation\Request;
29
use Symfony\Component\Routing\Annotation\Route;
30
31
class RelatedArticleOrganizationController extends Controller
0 ignored issues
show
Deprecated Code introduced by
The class Symfony\Bundle\Framework...e\Controller\Controller has been deprecated with message: since Symfony 4.2, use {@see AbstractController} instead.

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
32
{
33
    /**
34
     * @ApiDoc(
35
     *     resource=true,
36
     *     description="Returns a list of related articles",
37
     *     statusCodes={
38
     *         200="Returned on success"
39
     *     }
40
     * )
41
     * @Route("/api/{version}/organization/articles/related/", methods={"POST"}, options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_core_organization_related_articles")
42
     */
43
    public function postAction(Request $request)
44
    {
45
        $content = $request->getContent();
46
        $package = $this->get('swp_bridge.transformer.json_to_package')->transform($content);
47
48
        $relatedArticlesList = $this->getRelated($package);
49
50
        return new SingleResourceResponse($relatedArticlesList);
51
    }
52
53
    /**
54
     * @ApiDoc(
55
     *     resource=true,
56
     *     description="Returns a list of related articles",
57
     *     statusCodes={
58
     *         200="Returned on success"
59
     *     }
60
     * )
61
     * @Route("/api/{version}/packages/{id}/related/", methods={"GET"}, options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_core_packages_related_articles", requirements={"id"="\d+"})
62
     */
63
    public function getRelatedAction(string $id)
64
    {
65
        $package = $this->findOr404((int) $id);
66
67
        $relatedArticlesList = $this->getRelated($package);
68
69
        return new SingleResourceResponse($relatedArticlesList);
70
    }
71
72
    private function getRelated(PackageInterface $package): RelatedArticleList
73
    {
74
        $relatedItemsGroups = $package->getGroups()->filter(function ($group) {
75
            return GroupInterface::TYPE_RELATED === $group->getType();
76
        });
77
78
        $relatedArticlesList = new RelatedArticleList();
79
80 View Code Duplication
        if (null === $package || (null !== $package && 0 === \count($relatedItemsGroups))) {
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...
81
            return $relatedArticlesList;
82
        }
83
84
        $this->get('event_dispatcher')->dispatch(MultiTenancyEvents::TENANTABLE_DISABLE);
85
        $articleRepository = $this->get('swp.repository.article');
86
87
        foreach ($relatedItemsGroups as $relatedItemsGroup) {
88
            foreach ($relatedItemsGroup->getItems() as $item) {
89
                if (null === ($existingArticles = $articleRepository->findBy(['code' => $item->getGuid()]))) {
90
                    continue;
91
                }
92
93
                $tenants = [];
94
                foreach ($existingArticles as $existingArticle) {
95
                    $tenantCode = $existingArticle->getTenantCode();
96
                    $tenant = $this->get('swp.repository.tenant')->findOneByCode($tenantCode);
97
98
                    $tenants[] = $tenant;
99
                }
100
101
                $relatedArticleListItem = new RelatedArticleListItem();
102
                $relatedArticleListItem->setTenants($tenants);
103
                $relatedArticleListItem->setTitle($item->getHeadline());
104
105
                $relatedArticlesList->addRelatedArticleItem($relatedArticleListItem);
106
            }
107
        }
108
109
        return $relatedArticlesList;
110
    }
111
112 View Code Duplication
    private function findOr404(int $id): PackageInterface
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
113
    {
114
        $this->get('event_dispatcher')->dispatch(MultiTenancyEvents::TENANTABLE_DISABLE);
115
        $tenantContext = $this->get('swp_multi_tenancy.tenant_context');
116
        if (null === $package = $this->get('swp.repository.package')->findOneBy(['id' => $id, 'organization' => $tenantContext->getTenant()->getOrganization()])) {
117
            throw new NotFoundHttpException('Package was not found.');
118
        }
119
120
        return $package;
121
    }
122
}
123