Completed
Push — master ( 3ef484...ea5778 )
by Paweł
08:46
created

ContentPushController::handlePackage()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
ccs 2
cts 2
cp 1
cc 2
eloc 10
nc 2
nop 1
crap 2

1 Method

Rating   Name   Duplication   Size   Complexity  
A ContentPushController::getPackageRepository() 0 4 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 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 Nelmio\ApiDocBundle\Annotation\ApiDoc;
21
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
22
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
23
use SWP\Bundle\ContentBundle\Form\Type\MediaFileType;
24
use SWP\Bundle\ContentBundle\Model\ArticleMedia;
25
use SWP\Component\Bridge\Events;
26
use SWP\Component\Bridge\Model\PackageInterface;
27
use SWP\Component\Common\Response\ResponseContext;
28
use SWP\Component\Common\Response\SingleResourceResponse;
29
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
30
use Symfony\Component\EventDispatcher\GenericEvent;
31
use Symfony\Component\HttpFoundation\Request;
32
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
33
34
class ContentPushController extends Controller
35
{
36
    /**
37
     * Receives HTTP Push Request's payload.
38
     *
39
     * @ApiDoc(
40
     *     resource=true,
41
     *     description="Adds a new content from HTTP Push",
42
     *     statusCodes={
43
     *         201="Returned on success"
44
     *     }
45
     * )
46
     * @Route("/api/{version}/content/push", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_content_push")
47
     * @Method("POST")
48
     */
49
    public function pushContentAction(Request $request)
50
    {
51 11
        $content = $request->getContent();
52
        $package = $this->get('swp_bridge.transformer.json_to_package')->transform($content);
53 11
        $this->get('event_dispatcher')->dispatch(Events::SWP_VALIDATION, new GenericEvent($package));
54 11
55
        /** @var PackageInterface $existingPackage */
56 11
        $existingPackage = $this->findExistingPackage($package);
57
58 11
        if (null !== $existingPackage) {
59
            $objectManager = $this->get('swp.object_manager.package');
60
            $package->setId($existingPackage->getId());
61
            $package->setCreatedAt($existingPackage->getCreatedAt());
62
            $this->get('event_dispatcher')->dispatch(Events::PACKAGE_PRE_UPDATE, new GenericEvent($package));
63
            $objectManager->merge($package);
64
            $objectManager->flush();
65
            $this->get('event_dispatcher')->dispatch(Events::PACKAGE_POST_UPDATE, new GenericEvent($package));
66
67 11
            return new SingleResourceResponse(['status' => 'OK'], new ResponseContext(201));
68 11
        }
69 10
70 10
        $this->get('event_dispatcher')->dispatch(Events::PACKAGE_PRE_CREATE, new GenericEvent($package));
71
        $this->getPackageRepository()->add($package);
72 10
        $this->get('event_dispatcher')->dispatch(Events::PACKAGE_POST_CREATE, new GenericEvent($package));
73
74
        return new SingleResourceResponse(['status' => 'OK'], new ResponseContext(201));
75
    }
76
77
    /**
78
     * Receives HTTP Push Request's assets payload which is then processed and stored.
79
     *
80
     * @ApiDoc(
81
     *     resource=true,
82
     *     description="Adds new assets from HTTP Push",
83
     *     statusCodes={
84
     *         201="Returned on successful post.",
85
     *         500="Returned on invalid file.",
86
     *         200="Returned on form errors"
87
     *     },
88
     *     input="SWP\Bundle\ContentBundle\Form\Type\MediaFileType"
89
     * )
90
     * @Route("/api/{version}/assets/push", options={"expose"=true}, defaults={"version"="v1"}, name="swp_api_assets_push")
91
     * @Method("POST")
92
     */
93
    public function pushAssetsAction(Request $request)
94
    {
95
        $form = $this->createForm(MediaFileType::class);
96
        $form->handleRequest($request);
97
98
        if ($form->isSubmitted() && $form->isValid()) {
99
            $mediaManager = $this->get('swp_content_bundle.manager.media');
100
            $uploadedFile = $form->getData()['media'];
101
            $mediaId = $request->request->get('media_id');
102
103
            if ($uploadedFile->isValid()) {
104
                $image = $this->get('swp.repository.image')->findImageByAssetId(ArticleMedia::handleMediaId($mediaId));
105
106
                if (null == $image) {
107
                    $image = $mediaManager->handleUploadedFile($uploadedFile, $mediaId);
108
109
                    $this->get('swp.object_manager.media')->flush();
110
                }
111
112
                return new SingleResourceResponse([
113
                    'media_id' => $mediaId,
114
                    'URL' => $mediaManager->getMediaPublicUrl($image),
115
                    'media' => base64_encode($mediaManager->getFile($image)),
116
                    'mime_type' => Mime::getMimeFromExtension($image->getFileExtension()),
117
                    'filemeta' => [],
118
                ], new ResponseContext(201));
119
            }
120
121
            throw new \Exception('Uploaded file is not valid:'.$uploadedFile->getErrorMessage());
122
        }
123
124
        return new SingleResourceResponse($form);
125
    }
126
127
    /**
128
     * Checks if media exists in storage.
129
     *
130
     * @ApiDoc(
131
     *     resource=true,
132
     *     description="Gets a single media file",
133
     *     statusCodes={
134
     *         404="Returned when file doesn't exist.",
135
     *         200="Returned on form errors"
136
     *     }
137
     * )
138
     * @Route("/api/{version}/assets/push/{mediaId}", options={"expose"=true}, defaults={"version"="v1"}, requirements={"mediaId"=".+"}, name="swp_api_assets_get")
139
     * @Route("/api/{version}/assets/get/{mediaId}", options={"expose"=true}, defaults={"version"="v1"}, requirements={"mediaId"=".+"}, name="swp_api_assets_get_1")
140
     * @Method("GET")
141
     */
142
    public function getAssetsAction($mediaId)
143
    {
144
        $image = $this->get('swp.repository.image')
145
            ->findImageByAssetId(ArticleMedia::handleMediaId($mediaId));
146
147
        if (null === $image) {
148
            throw new NotFoundHttpException('Media don\'t exist in storage');
149
        }
150
151
        $mediaManager = $this->get('swp_content_bundle.manager.media');
152
153
        return new SingleResourceResponse([
154
            'media_id' => $mediaId,
155
            'URL' => $mediaManager->getMediaPublicUrl($image),
156
            'media' => base64_encode($mediaManager->getFile($image)),
157
            'mime_type' => Mime::getMimeFromExtension($image->getFileExtension()),
158
            'filemeta' => [],
159
        ]);
160
    }
161
162
    protected function findExistingPackage(PackageInterface $package)
163 11
    {
164
        $existingPackage = $this->getPackageRepository()->findOneBy(['guid' => $package->getGuid()]);
165 11
166 11
        if (null === $existingPackage) {
167
            $existingPackage = $this->getPackageRepository()->findOneBy([
168 11
                'guid' => $package->getEvolvedFrom(),
169 11
            ]);
170 11
        }
171
172
        return $existingPackage;
173 11
    }
174
175 11
    protected function getPackageRepository()
176
    {
177
        return $this->get('swp.repository.package');
178
    }
179
}
180