Completed
Push — master ( 9b6067...64e7c9 )
by Nicolas
03:06
created

EntryRestController::postEntriesAction()   F

Complexity

Conditions 19
Paths 1024

Size

Total Lines 83
Code Lines 48

Duplication

Lines 7
Ratio 8.43 %

Importance

Changes 0
Metric Value
dl 7
loc 83
rs 2.0734
c 0
b 0
f 0
cc 19
eloc 48
nc 1024
nop 1

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Wallabag\ApiBundle\Controller;
4
5
use Hateoas\Configuration\Route;
6
use Hateoas\Representation\Factory\PagerfantaFactory;
7
use JMS\Serializer\SerializationContext;
8
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\HttpKernel\Exception\HttpException;
13
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
14
use Wallabag\CoreBundle\Entity\Entry;
15
use Wallabag\CoreBundle\Entity\Tag;
16
use Wallabag\CoreBundle\Event\EntryDeletedEvent;
17
use Wallabag\CoreBundle\Event\EntrySavedEvent;
18
19
class EntryRestController extends WallabagRestController
20
{
21
    /**
22
     * Check if an entry exist by url.
23
     * Return ID if entry(ies) exist (and if you give the return_id parameter).
24
     * Otherwise it returns false.
25
     *
26
     * @todo Remove that `return_id` in the next major release
27
     *
28
     * @ApiDoc(
29
     *       parameters={
30
     *          {"name"="return_id", "dataType"="string", "required"=false, "format"="1 or 0", "description"="Set 1 if you want to retrieve ID in case entry(ies) exists, 0 by default"},
31
     *          {"name"="url", "dataType"="string", "required"=true, "format"="An url", "description"="Url to check if it exists"},
32
     *          {"name"="urls", "dataType"="string", "required"=false, "format"="An array of urls (?urls[]=http...&urls[]=http...)", "description"="Urls (as an array) to check if it exists"}
33
     *       }
34
     * )
35
     *
36
     * @return JsonResponse
37
     */
38
    public function getEntriesExistsAction(Request $request)
39
    {
40
        $this->validateAuthentication();
41
42
        $returnId = (null === $request->query->get('return_id')) ? false : (bool) $request->query->get('return_id');
43
        $urls = $request->query->get('urls', []);
44
45
        // handle multiple urls first
46
        if (!empty($urls)) {
47
            $results = [];
48
            foreach ($urls as $url) {
49
                $res = $this->getDoctrine()
0 ignored issues
show
Bug introduced by
The method findByUrlAndUserId() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
50
                    ->getRepository('WallabagCoreBundle:Entry')
51
                    ->findByUrlAndUserId($url, $this->getUser()->getId());
52
53
                $results[$url] = $this->returnExistInformation($res, $returnId);
54
            }
55
56
            return $this->sendResponse($results);
57
        }
58
59
        // let's see if it is a simple url?
60
        $url = $request->query->get('url', '');
61
62
        if (empty($url)) {
63
            throw $this->createAccessDeniedException('URL is empty?, logged user id: ' . $this->getUser()->getId());
64
        }
65
66
        $res = $this->getDoctrine()
0 ignored issues
show
Bug introduced by
The method findByUrlAndUserId() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
67
            ->getRepository('WallabagCoreBundle:Entry')
68
            ->findByUrlAndUserId($url, $this->getUser()->getId());
69
70
        $exists = $this->returnExistInformation($res, $returnId);
71
72
        return $this->sendResponse(['exists' => $exists]);
73
    }
74
75
    /**
76
     * Retrieve all entries. It could be filtered by many options.
77
     *
78
     * @ApiDoc(
79
     *       parameters={
80
     *          {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by archived status."},
81
     *          {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by starred status."},
82
     *          {"name"="sort", "dataType"="string", "required"=false, "format"="'created' or 'updated', default 'created'", "description"="sort entries by date."},
83
     *          {"name"="order", "dataType"="string", "required"=false, "format"="'asc' or 'desc', default 'desc'", "description"="order of sort."},
84
     *          {"name"="page", "dataType"="integer", "required"=false, "format"="default '1'", "description"="what page you want."},
85
     *          {"name"="perPage", "dataType"="integer", "required"=false, "format"="default'30'", "description"="results per page."},
86
     *          {"name"="tags", "dataType"="string", "required"=false, "format"="api,rest", "description"="a list of tags url encoded. Will returns entries that matches ALL tags."},
87
     *          {"name"="since", "dataType"="integer", "required"=false, "format"="default '0'", "description"="The timestamp since when you want entries updated."},
88
     *          {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0, all entries by default", "description"="filter by entries with a public link"},
89
     *       }
90
     * )
91
     *
92
     * @return JsonResponse
93
     */
94
    public function getEntriesAction(Request $request)
95
    {
96
        $this->validateAuthentication();
97
98
        $isArchived = (null === $request->query->get('archive')) ? null : (bool) $request->query->get('archive');
99
        $isStarred = (null === $request->query->get('starred')) ? null : (bool) $request->query->get('starred');
100
        $isPublic = (null === $request->query->get('public')) ? null : (bool) $request->query->get('public');
101
        $sort = $request->query->get('sort', 'created');
102
        $order = $request->query->get('order', 'desc');
103
        $page = (int) $request->query->get('page', 1);
104
        $perPage = (int) $request->query->get('perPage', 30);
105
        $tags = is_array($request->query->get('tags')) ? '' : (string) $request->query->get('tags', '');
106
        $since = $request->query->get('since', 0);
107
108
        /** @var \Pagerfanta\Pagerfanta $pager */
109
        $pager = $this->get('wallabag_core.entry_repository')->findEntries(
110
            $this->getUser()->getId(),
111
            $isArchived,
112
            $isStarred,
113
            $isPublic,
114
            $sort,
115
            $order,
116
            $since,
117
            $tags
118
        );
119
120
        $pager->setMaxPerPage($perPage);
121
        $pager->setCurrentPage($page);
122
123
        $pagerfantaFactory = new PagerfantaFactory('page', 'perPage');
124
        $paginatedCollection = $pagerfantaFactory->createRepresentation(
125
            $pager,
126
            new Route(
127
                'api_get_entries',
128
                [
129
                    'archive' => $isArchived,
130
                    'starred' => $isStarred,
131
                    'public' => $isPublic,
132
                    'sort' => $sort,
133
                    'order' => $order,
134
                    'page' => $page,
135
                    'perPage' => $perPage,
136
                    'tags' => $tags,
137
                    'since' => $since,
138
                ],
139
                UrlGeneratorInterface::ABSOLUTE_URL
140
            )
141
        );
142
143
        return $this->sendResponse($paginatedCollection);
144
    }
145
146
    /**
147
     * Retrieve a single entry.
148
     *
149
     * @ApiDoc(
150
     *      requirements={
151
     *          {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
152
     *      }
153
     * )
154
     *
155
     * @return JsonResponse
156
     */
157
    public function getEntryAction(Entry $entry)
158
    {
159
        $this->validateAuthentication();
160
        $this->validateUserAccess($entry->getUser()->getId());
161
162
        return $this->sendResponse($entry);
163
    }
164
165
    /**
166
     * Retrieve a single entry as a predefined format.
167
     *
168
     * @ApiDoc(
169
     *      requirements={
170
     *          {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
171
     *      }
172
     * )
173
     *
174
     * @return Response
175
     */
176
    public function getEntryExportAction(Entry $entry, Request $request)
177
    {
178
        $this->validateAuthentication();
179
        $this->validateUserAccess($entry->getUser()->getId());
180
181
        return $this->get('wallabag_core.helper.entries_export')
182
            ->setEntries($entry)
183
            ->updateTitle('entry')
184
            ->updateAuthor('entry')
185
            ->exportAs($request->attributes->get('_format'));
186
    }
187
188
    /**
189
     * Handles an entries list and delete URL.
190
     *
191
     * @ApiDoc(
192
     *       parameters={
193
     *          {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to delete."}
194
     *       }
195
     * )
196
     *
197
     * @return JsonResponse
198
     */
199
    public function deleteEntriesListAction(Request $request)
200
    {
201
        $this->validateAuthentication();
202
203
        $urls = json_decode($request->query->get('urls', []));
204
205
        if (empty($urls)) {
206
            return $this->sendResponse([]);
207
        }
208
209
        $results = [];
210
211
        // handle multiple urls
212
        foreach ($urls as $key => $url) {
213
            $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
214
                $url,
215
                $this->getUser()->getId()
216
            );
217
218
            $results[$key]['url'] = $url;
219
220
            if (false !== $entry) {
221
                $em = $this->getDoctrine()->getManager();
222
                $em->remove($entry);
223
                $em->flush();
224
225
                // entry deleted, dispatch event about it!
226
                $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
227
            }
228
229
            $results[$key]['entry'] = $entry instanceof Entry ? true : false;
230
        }
231
232
        return $this->sendResponse($results);
233
    }
234
235
    /**
236
     * Handles an entries list and create URL.
237
     *
238
     * @ApiDoc(
239
     *       parameters={
240
     *          {"name"="urls", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...'}, {'url': 'http://...'}]", "description"="Urls (as an array) to create."}
241
     *       }
242
     * )
243
     *
244
     * @throws HttpException When limit is reached
245
     *
246
     * @return JsonResponse
247
     */
248
    public function postEntriesListAction(Request $request)
249
    {
250
        $this->validateAuthentication();
251
252
        $urls = json_decode($request->query->get('urls', []));
253
254
        $limit = $this->container->getParameter('wallabag_core.api_limit_mass_actions');
255
256
        if (count($urls) > $limit) {
257
            throw new HttpException(400, 'API limit reached');
258
        }
259
260
        $results = [];
261
        if (empty($urls)) {
262
            return $this->sendResponse($results);
263
        }
264
265
        // handle multiple urls
266
        foreach ($urls as $key => $url) {
267
            $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
268
                $url,
269
                $this->getUser()->getId()
270
            );
271
272
            $results[$key]['url'] = $url;
273
274
            if (false === $entry) {
275
                $entry = new Entry($this->getUser());
0 ignored issues
show
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<Wallabag\UserBundle\Entity\User>.

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...
276
277
                $this->get('wallabag_core.content_proxy')->updateEntry($entry, $url);
278
            }
279
280
            $em = $this->getDoctrine()->getManager();
281
            $em->persist($entry);
282
            $em->flush();
283
284
            $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
285
286
            // entry saved, dispatch event about it!
287
            $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
288
        }
289
290
        return $this->sendResponse($results);
291
    }
292
293
    /**
294
     * Create an entry.
295
     *
296
     * If you want to provide the HTML content (which means wallabag won't fetch it from the url), you must provide `content`, `title` & `url` fields **non-empty**.
297
     * Otherwise, content will be fetched as normal from the url and values will be overwritten.
298
     *
299
     * @ApiDoc(
300
     *       parameters={
301
     *          {"name"="url", "dataType"="string", "required"=true, "format"="http://www.test.com/article.html", "description"="Url for the entry."},
302
     *          {"name"="title", "dataType"="string", "required"=false, "description"="Optional, we'll get the title from the page."},
303
     *          {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
304
     *          {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already archived"},
305
     *          {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="entry already starred"},
306
     *          {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
307
     *          {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
308
     *          {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
309
     *          {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
310
     *          {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
311
     *          {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
312
     *          {"name"="origin_url", "dataType"="string", "required"=false, "format"="http://www.test.com/article.html", "description"="Origin url for the entry (from where you found it)."},
313
     *       }
314
     * )
315
     *
316
     * @return JsonResponse
317
     */
318
    public function postEntriesAction(Request $request)
319
    {
320
        $this->validateAuthentication();
321
322
        $url = $request->request->get('url');
323
324
        $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
325
            $url,
326
            $this->getUser()->getId()
327
        );
328
329
        if (false === $entry) {
330
            $entry = new Entry($this->getUser());
0 ignored issues
show
Documentation introduced by
$this->getUser() is of type null|object, but the function expects a object<Wallabag\UserBundle\Entity\User>.

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...
331
            $entry->setUrl($url);
332
        }
333
334
        $data = $this->retrieveValueFromRequest($request);
335
336
        try {
337
            $this->get('wallabag_core.content_proxy')->updateEntry(
338
                $entry,
339
                $entry->getUrl(),
340
                [
341
                    'title' => !empty($data['title']) ? $data['title'] : $entry->getTitle(),
342
                    'html' => !empty($data['content']) ? $data['content'] : $entry->getContent(),
343
                    'url' => $entry->getUrl(),
344
                    'language' => !empty($data['language']) ? $data['language'] : $entry->getLanguage(),
345
                    'date' => !empty($data['publishedAt']) ? $data['publishedAt'] : $entry->getPublishedAt(),
346
                    // faking the open graph preview picture
347
                    'open_graph' => [
348
                        'og_image' => !empty($data['picture']) ? $data['picture'] : $entry->getPreviewPicture(),
349
                    ],
350
                    'authors' => is_string($data['authors']) ? explode(',', $data['authors']) : $entry->getPublishedBy(),
351
                ]
352
            );
353
        } catch (\Exception $e) {
354
            $this->get('logger')->error('Error while saving an entry', [
355
                'exception' => $e,
356
                'entry' => $entry,
357
            ]);
358
        }
359
360
        if (null !== $data['isArchived']) {
361
            $entry->setArchived((bool) $data['isArchived']);
362
        }
363
364
        if (null !== $data['isStarred']) {
365
            $entry->updateStar((bool) $data['isStarred']);
366
        }
367
368
        if (!empty($data['tags'])) {
369
            $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
370
        }
371
372
        if (!empty($data['origin_url'])) {
373
            $entry->setOriginUrl($data['origin_url']);
374
        }
375
376 View Code Duplication
        if (null !== $data['isPublic']) {
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...
377
            if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
378
                $entry->generateUid();
379
            } elseif (false === (bool) $data['isPublic']) {
380
                $entry->cleanUid();
381
            }
382
        }
383
384
        if (empty($entry->getDomainName())) {
385
            $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
386
        }
387
388
        if (empty($entry->getTitle())) {
389
            $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
390
        }
391
392
        $em = $this->getDoctrine()->getManager();
393
        $em->persist($entry);
394
        $em->flush();
395
396
        // entry saved, dispatch event about it!
397
        $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
398
399
        return $this->sendResponse($entry);
400
    }
401
402
    /**
403
     * Change several properties of an entry.
404
     *
405
     * @ApiDoc(
406
     *      requirements={
407
     *          {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
408
     *      },
409
     *      parameters={
410
     *          {"name"="title", "dataType"="string", "required"=false},
411
     *          {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
412
     *          {"name"="archive", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="archived the entry."},
413
     *          {"name"="starred", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="starred the entry."},
414
     *          {"name"="content", "dataType"="string", "required"=false, "description"="Content of the entry"},
415
     *          {"name"="language", "dataType"="string", "required"=false, "description"="Language of the entry"},
416
     *          {"name"="preview_picture", "dataType"="string", "required"=false, "description"="Preview picture of the entry"},
417
     *          {"name"="published_at", "dataType"="datetime|integer", "format"="YYYY-MM-DDTHH:II:SS+TZ or a timestamp", "required"=false, "description"="Published date of the entry"},
418
     *          {"name"="authors", "dataType"="string", "format"="Name Firstname,author2,author3", "required"=false, "description"="Authors of the entry"},
419
     *          {"name"="public", "dataType"="integer", "required"=false, "format"="1 or 0", "description"="will generate a public link for the entry"},
420
     *          {"name"="origin_url", "dataType"="string", "required"=false, "format"="http://www.test.com/article.html", "description"="Origin url for the entry (from where you found it)."},
421
     *      }
422
     * )
423
     *
424
     * @return JsonResponse
425
     */
426
    public function patchEntriesAction(Entry $entry, Request $request)
427
    {
428
        $this->validateAuthentication();
429
        $this->validateUserAccess($entry->getUser()->getId());
430
431
        $contentProxy = $this->get('wallabag_core.content_proxy');
432
433
        $data = $this->retrieveValueFromRequest($request);
434
435
        // this is a special case where user want to manually update the entry content
436
        // the ContentProxy will only cleanup the html
437
        // and also we force to not re-fetch the content in case of error
438
        if (!empty($data['content'])) {
439
            try {
440
                $contentProxy->updateEntry(
441
                    $entry,
442
                    $entry->getUrl(),
443
                    [
444
                        'html' => $data['content'],
445
                    ],
446
                    true
447
                );
448
            } catch (\Exception $e) {
449
                $this->get('logger')->error('Error while saving an entry', [
450
                    'exception' => $e,
451
                    'entry' => $entry,
452
                ]);
453
            }
454
        }
455
456
        if (!empty($data['title'])) {
457
            $entry->setTitle($data['title']);
458
        }
459
460
        if (!empty($data['language'])) {
461
            $contentProxy->updateLanguage($entry, $data['language']);
462
        }
463
464
        if (!empty($data['authors']) && is_string($data['authors'])) {
465
            $entry->setPublishedBy(explode(',', $data['authors']));
466
        }
467
468
        if (!empty($data['picture'])) {
469
            $contentProxy->updatePreviewPicture($entry, $data['picture']);
470
        }
471
472
        if (!empty($data['publishedAt'])) {
473
            $contentProxy->updatePublishedAt($entry, $data['publishedAt']);
474
        }
475
476
        if (null !== $data['isArchived']) {
477
            $entry->setArchived((bool) $data['isArchived']);
478
        }
479
480
        if (null !== $data['isStarred']) {
481
            $entry->updateStar((bool) $data['isStarred']);
482
        }
483
484
        if (!empty($data['tags'])) {
485
            $entry->removeAllTags();
486
            $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $data['tags']);
487
        }
488
489 View Code Duplication
        if (null !== $data['isPublic']) {
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...
490
            if (true === (bool) $data['isPublic'] && null === $entry->getUid()) {
491
                $entry->generateUid();
492
            } elseif (false === (bool) $data['isPublic']) {
493
                $entry->cleanUid();
494
            }
495
        }
496
497
        if (!empty($data['origin_url'])) {
498
            $entry->setOriginUrl($data['origin_url']);
499
        }
500
501
        if (empty($entry->getDomainName())) {
502
            $this->get('wallabag_core.content_proxy')->setEntryDomainName($entry);
503
        }
504
505
        if (empty($entry->getTitle())) {
506
            $this->get('wallabag_core.content_proxy')->setDefaultEntryTitle($entry);
507
        }
508
509
        $em = $this->getDoctrine()->getManager();
510
        $em->persist($entry);
511
        $em->flush();
512
513
        // entry saved, dispatch event about it!
514
        $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
515
516
        return $this->sendResponse($entry);
517
    }
518
519
    /**
520
     * Reload an entry.
521
     * An empty response with HTTP Status 304 will be send if we weren't able to update the content (because it hasn't changed or we got an error).
522
     *
523
     * @ApiDoc(
524
     *      requirements={
525
     *          {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
526
     *      }
527
     * )
528
     *
529
     * @return JsonResponse
530
     */
531
    public function patchEntriesReloadAction(Entry $entry)
532
    {
533
        $this->validateAuthentication();
534
        $this->validateUserAccess($entry->getUser()->getId());
535
536
        try {
537
            $this->get('wallabag_core.content_proxy')->updateEntry($entry, $entry->getUrl());
538
        } catch (\Exception $e) {
539
            $this->get('logger')->error('Error while saving an entry', [
540
                'exception' => $e,
541
                'entry' => $entry,
542
            ]);
543
544
            return new JsonResponse([], 304);
545
        }
546
547
        // if refreshing entry failed, don't save it
548
        if ($this->getParameter('wallabag_core.fetching_error_message') === $entry->getContent()) {
549
            return new JsonResponse([], 304);
550
        }
551
552
        $em = $this->getDoctrine()->getManager();
553
        $em->persist($entry);
554
        $em->flush();
555
556
        // entry saved, dispatch event about it!
557
        $this->get('event_dispatcher')->dispatch(EntrySavedEvent::NAME, new EntrySavedEvent($entry));
558
559
        return $this->sendResponse($entry);
560
    }
561
562
    /**
563
     * Delete **permanently** an entry.
564
     *
565
     * @ApiDoc(
566
     *      requirements={
567
     *          {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
568
     *      }
569
     * )
570
     *
571
     * @return JsonResponse
572
     */
573 View Code Duplication
    public function deleteEntriesAction(Entry $entry)
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...
574
    {
575
        $this->validateAuthentication();
576
        $this->validateUserAccess($entry->getUser()->getId());
577
578
        $em = $this->getDoctrine()->getManager();
579
        $em->remove($entry);
580
        $em->flush();
581
582
        // entry deleted, dispatch event about it!
583
        $this->get('event_dispatcher')->dispatch(EntryDeletedEvent::NAME, new EntryDeletedEvent($entry));
584
585
        return $this->sendResponse($entry);
586
    }
587
588
    /**
589
     * Retrieve all tags for an entry.
590
     *
591
     * @ApiDoc(
592
     *      requirements={
593
     *          {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
594
     *      }
595
     * )
596
     *
597
     * @return JsonResponse
598
     */
599
    public function getEntriesTagsAction(Entry $entry)
600
    {
601
        $this->validateAuthentication();
602
        $this->validateUserAccess($entry->getUser()->getId());
603
604
        return $this->sendResponse($entry->getTags());
605
    }
606
607
    /**
608
     * Add one or more tags to an entry.
609
     *
610
     * @ApiDoc(
611
     *      requirements={
612
     *          {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
613
     *      },
614
     *      parameters={
615
     *          {"name"="tags", "dataType"="string", "required"=false, "format"="tag1,tag2,tag3", "description"="a comma-separated list of tags."},
616
     *       }
617
     * )
618
     *
619
     * @return JsonResponse
620
     */
621
    public function postEntriesTagsAction(Request $request, Entry $entry)
622
    {
623
        $this->validateAuthentication();
624
        $this->validateUserAccess($entry->getUser()->getId());
625
626
        $tags = $request->request->get('tags', '');
627
        if (!empty($tags)) {
628
            $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
629
        }
630
631
        $em = $this->getDoctrine()->getManager();
632
        $em->persist($entry);
633
        $em->flush();
634
635
        return $this->sendResponse($entry);
636
    }
637
638
    /**
639
     * Permanently remove one tag for an entry.
640
     *
641
     * @ApiDoc(
642
     *      requirements={
643
     *          {"name"="tag", "dataType"="integer", "requirement"="\w+", "description"="The tag ID"},
644
     *          {"name"="entry", "dataType"="integer", "requirement"="\w+", "description"="The entry ID"}
645
     *      }
646
     * )
647
     *
648
     * @return JsonResponse
649
     */
650 View Code Duplication
    public function deleteEntriesTagsAction(Entry $entry, Tag $tag)
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...
651
    {
652
        $this->validateAuthentication();
653
        $this->validateUserAccess($entry->getUser()->getId());
654
655
        $entry->removeTag($tag);
656
        $em = $this->getDoctrine()->getManager();
657
        $em->persist($entry);
658
        $em->flush();
659
660
        return $this->sendResponse($entry);
661
    }
662
663
    /**
664
     * Handles an entries list delete tags from them.
665
     *
666
     * @ApiDoc(
667
     *       parameters={
668
     *          {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...','tags': 'tag1, tag2'}, {'url': 'http://...','tags': 'tag1, tag2'}]", "description"="Urls (as an array) to handle."}
669
     *       }
670
     * )
671
     *
672
     * @return JsonResponse
673
     */
674
    public function deleteEntriesTagsListAction(Request $request)
675
    {
676
        $this->validateAuthentication();
677
678
        $list = json_decode($request->query->get('list', []));
679
680
        if (empty($list)) {
681
            return $this->sendResponse([]);
682
        }
683
684
        // handle multiple urls
685
        $results = [];
686
687
        foreach ($list as $key => $element) {
688
            $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
689
                $element->url,
690
                $this->getUser()->getId()
691
            );
692
693
            $results[$key]['url'] = $element->url;
694
            $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
695
696
            $tags = $element->tags;
697
698
            if (false !== $entry && !(empty($tags))) {
699
                $tags = explode(',', $tags);
700
                foreach ($tags as $label) {
701
                    $label = trim($label);
702
703
                    $tag = $this->getDoctrine()
0 ignored issues
show
Bug introduced by
The method findOneByLabel() does not exist on Doctrine\Common\Persistence\ObjectRepository. Did you maybe mean findOneBy()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
704
                        ->getRepository('WallabagCoreBundle:Tag')
705
                        ->findOneByLabel($label);
706
707
                    if (false !== $tag) {
708
                        $entry->removeTag($tag);
709
                    }
710
                }
711
712
                $em = $this->getDoctrine()->getManager();
713
                $em->persist($entry);
714
                $em->flush();
715
            }
716
        }
717
718
        return $this->sendResponse($results);
719
    }
720
721
    /**
722
     * Handles an entries list and add tags to them.
723
     *
724
     * @ApiDoc(
725
     *       parameters={
726
     *          {"name"="list", "dataType"="string", "required"=true, "format"="A JSON array of urls [{'url': 'http://...','tags': 'tag1, tag2'}, {'url': 'http://...','tags': 'tag1, tag2'}]", "description"="Urls (as an array) to handle."}
727
     *       }
728
     * )
729
     *
730
     * @return JsonResponse
731
     */
732
    public function postEntriesTagsListAction(Request $request)
733
    {
734
        $this->validateAuthentication();
735
736
        $list = json_decode($request->query->get('list', []));
737
738
        if (empty($list)) {
739
            return $this->sendResponse([]);
740
        }
741
742
        $results = [];
743
744
        // handle multiple urls
745
        foreach ($list as $key => $element) {
746
            $entry = $this->get('wallabag_core.entry_repository')->findByUrlAndUserId(
747
                $element->url,
748
                $this->getUser()->getId()
749
            );
750
751
            $results[$key]['url'] = $element->url;
752
            $results[$key]['entry'] = $entry instanceof Entry ? $entry->getId() : false;
753
754
            $tags = $element->tags;
755
756
            if (false !== $entry && !(empty($tags))) {
757
                $this->get('wallabag_core.tags_assigner')->assignTagsToEntry($entry, $tags);
758
759
                $em = $this->getDoctrine()->getManager();
760
                $em->persist($entry);
761
                $em->flush();
762
            }
763
        }
764
765
        return $this->sendResponse($results);
766
    }
767
768
    /**
769
     * Shortcut to send data serialized in json.
770
     *
771
     * @param mixed $data
772
     *
773
     * @return JsonResponse
774
     */
775
    private function sendResponse($data)
776
    {
777
        // https://github.com/schmittjoh/JMSSerializerBundle/issues/293
778
        $context = new SerializationContext();
779
        $context->setSerializeNull(true);
780
781
        $json = $this->get('jms_serializer')->serialize($data, 'json', $context);
782
783
        return (new JsonResponse())->setJson($json);
784
    }
785
786
    /**
787
     * Retrieve value from the request.
788
     * Used for POST & PATCH on a an entry.
789
     *
790
     * @param Request $request
791
     *
792
     * @return array
793
     */
794
    private function retrieveValueFromRequest(Request $request)
795
    {
796
        return [
797
            'title' => $request->request->get('title'),
798
            'tags' => $request->request->get('tags', []),
799
            'isArchived' => $request->request->get('archive'),
800
            'isStarred' => $request->request->get('starred'),
801
            'isPublic' => $request->request->get('public'),
802
            'content' => $request->request->get('content'),
803
            'language' => $request->request->get('language'),
804
            'picture' => $request->request->get('preview_picture'),
805
            'publishedAt' => $request->request->get('published_at'),
806
            'authors' => $request->request->get('authors', ''),
807
            'origin_url' => $request->request->get('origin_url', ''),
808
        ];
809
    }
810
811
    /**
812
     * Return information about the entry if it exist and depending on the id or not.
813
     *
814
     * @param Entry|null $entry
815
     * @param bool       $returnId
816
     *
817
     * @return bool|int
818
     */
819
    private function returnExistInformation($entry, $returnId)
820
    {
821
        if ($returnId) {
822
            return $entry instanceof Entry ? $entry->getId() : null;
823
        }
824
825
        return $entry instanceof Entry;
826
    }
827
}
828