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

ContentPushController::findExistingPackage()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 12

Duplication

Lines 12
Ratio 100 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 12
loc 12
ccs 0
cts 0
cp 0
rs 9.8666
c 0
b 0
f 0
cc 3
nc 2
nop 1
crap 12
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 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\ContentBundle\Controller;
18
19
use Hoa\Mime\Mime;
20
use SWP\Component\Bridge\Events;
21
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
22
use SWP\Bundle\ContentBundle\Form\Type\MediaFileType;
23
use SWP\Bundle\ContentBundle\Model\ArticleMedia;
24
use SWP\Bundle\ContentBundle\Provider\FileProvider;
25
use SWP\Component\Common\Response\ResponseContext;
26
use SWP\Component\Common\Response\SingleResourceResponse;
27
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
28
use Symfony\Component\EventDispatcher\GenericEvent;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
31
use Symfony\Component\Routing\Annotation\Route;
32
33
class ContentPushController 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...
34
{
35
    /**
36
     * Receives HTTP Push Request's payload.
37
     *
38
     * @ApiDoc(
39
     *     resource=true,
40
     *     description="Adds a new content from HTTP Push",
41
     *     statusCodes={
42
     *         201="Returned on success"
43
     *     }
44
     * )
45
     * @Route("/api/{version}/content/push", methods={"POST"}, options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_content_push")
46
     */
47
    public function pushContentAction(Request $request)
48
    {
49
        $package = $this->container->get('swp_bridge.transformer.json_to_package')->transform($request->getContent());
50 12
        $this->container->get('event_dispatcher')->dispatch(Events::SWP_VALIDATION, new GenericEvent($package));
51
52 12
        $payload = \serialize([
53 12
            'package' => $package,
54
            'tenant' => $this->container->get('swp_multi_tenancy.tenant_context')->getTenant(),
55 12
        ]);
56
        $this->container->get('old_sound_rabbit_mq.content_push_producer')->publish($payload);
57 12
58
        return new SingleResourceResponse(['status' => 'OK'], new ResponseContext(201));
59
    }
60
61
    /**
62
     * Receives HTTP Push Request's assets payload which is then processed and stored.
63
     *
64
     * @ApiDoc(
65
     *     resource=true,
66 12
     *     description="Adds new assets from HTTP Push",
67 12
     *     statusCodes={
68 11
     *         201="Returned on successful post.",
69 11
     *         500="Returned on invalid file.",
70
     *         200="Returned on form errors"
71 11
     *     },
72
     *     input="SWP\Bundle\ContentBundle\Form\Type\MediaFileType"
73
     * )
74
     * @Route("/api/{version}/assets/push", methods={"POST"}, options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_assets_push")
75
     */
76
    public function pushAssetsAction(Request $request)
77
    {
78
        $form = $this->createForm(MediaFileType::class);
79
        $form->handleRequest($request);
80
81
        if ($form->isSubmitted() && $form->isValid()) {
82
            $mediaManager = $this->get('swp_content_bundle.manager.media');
83
            $uploadedFile = $form->getData()['media'];
84
            $mediaId = $request->request->get('media_id');
85
86
            if ($uploadedFile->isValid()) {
87
                $fileProvider = $this->container->get(FileProvider::class);
88
                $file = $fileProvider->getFile(ArticleMedia::handleMediaId($mediaId), $uploadedFile->guessExtension());
89
90
                if (null === $file) {
91
                    $file = $mediaManager->handleUploadedFile($uploadedFile, $mediaId);
92
                    $this->get('swp.object_manager.media')->flush();
93
                }
94
95
                return new SingleResourceResponse(
96
                    [
97
                        'media_id' => $mediaId,
98
                        'URL' => $mediaManager->getMediaPublicUrl($file),
99
                        'media' => base64_encode($mediaManager->getFile($file)),
100
                        'mime_type' => Mime::getMimeFromExtension($file->getFileExtension()),
101
                        'filemeta' => [],
102
                    ], new ResponseContext(201)
103
                );
104
            }
105
106
            throw new \Exception('Uploaded file is not valid:'.$uploadedFile->getErrorMessage());
107
        }
108
109
        return new SingleResourceResponse($form);
110
    }
111
112
    /**
113
     * Checks if media exists in storage.
114
     *
115
     * @ApiDoc(
116
     *     resource=true,
117
     *     description="Gets a single media file",
118
     *     statusCodes={
119
     *         404="Returned when file doesn't exist.",
120
     *         200="Returned on form errors"
121
     *     }
122
     * )
123
     * @Route("/api/{version}/assets/push/{mediaId}.{extension}", methods={"GET"}, options={"expose"=true}, defaults={"version"="v1"}, requirements={"mediaId"=".+"}, name="swp_api_assets_get")
124
     * @Route("/api/{version}/assets/get/{mediaId}.{extension}", methods={"GET"}, options={"expose"=true}, defaults={"version"="v1"}, requirements={"mediaId"=".+"}, name="swp_api_assets_get_1")
125
     */
126
    public function getAssetsAction(string $mediaId, string $extension)
127
    {
128
        $fileProvider = $this->container->get(FileProvider::class);
129
        $file = $fileProvider->getFile(ArticleMedia::handleMediaId($mediaId), $extension);
130
131
        if (null === $file) {
132
            throw new NotFoundHttpException('Media don\'t exist in storage');
133
        }
134
135
        $mediaManager = $this->get('swp_content_bundle.manager.media');
136
137
        return new SingleResourceResponse([
138
            'media_id' => $mediaId,
139
            'URL' => $mediaManager->getMediaPublicUrl($file),
140
            'media' => base64_encode($mediaManager->getFile($file)),
141
            'mime_type' => Mime::getMimeFromExtension($file->getFileExtension()),
142
            'filemeta' => [],
143
        ]);
144
    }
145
146 View Code Duplication
    protected function findExistingPackage(PackageInterface $package)
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...
147
    {
148
        $existingPackage = $this->getPackageRepository()->findOneBy(['guid' => $package->getGuid()]);
149
150
        if (null === $existingPackage && null !== $package->getEvolvedFrom()) {
151
            $existingPackage = $this->getPackageRepository()->findOneBy([
152
                'guid' => $package->getEvolvedFrom(),
153
            ]);
154
        }
155
156
        return $existingPackage;
157
    }
158
159
    protected function getPackageRepository()
160
    {
161
        return $this->get('swp.repository.package');
162 12
    }
163
}
164