Completed
Push — master ( f5370a...515534 )
by
unknown
04:37
created

MediaHelperController   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 66
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
c 1
b 0
f 0
lcom 1
cbo 4
dl 0
loc 66
ccs 0
cts 36
cp 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
B getAutocompleteItemsAction() 0 39 3
1
<?php
2
3
namespace MediaMonks\SonataMediaBundle\Controller;
4
5
use MediaMonks\SonataMediaBundle\Admin\MediaAdmin;
6
use MediaMonks\SonataMediaBundle\Entity\Media;
7
use Symfony\Component\HttpFoundation\JsonResponse;
8
use Symfony\Component\HttpFoundation\Request;
9
use Symfony\Component\HttpFoundation\Response;
10
use Symfony\Component\Templating\EngineInterface;
11
12
class MediaHelperController
13
{
14
    /**
15
     * @var MediaAdmin
16
     */
17
    private $mediaAdmin;
18
19
    /**
20
     * @var EngineInterface
21
     */
22
    private $templating;
23
24
    /**
25
     * @param MediaAdmin $mediaAdmin
26
     * @param EngineInterface $templating
27
     */
28
    public function __construct(MediaAdmin $mediaAdmin, EngineInterface $templating)
29
    {
30
        $this->mediaAdmin = $mediaAdmin;
31
        $this->templating = $templating;
32
    }
33
34
    /**
35
     * @param Request $request
36
     * @return \Symfony\Component\HttpFoundation\JsonResponse
37
     */
38
    public function getAutocompleteItemsAction(Request $request)
39
    {
40
        $this->mediaAdmin->checkAccess('list');
41
42
        $minimumInputLength = 3;
43
        $searchText = $request->get('q');
44
        if (mb_strlen($searchText, 'UTF-8') < $minimumInputLength) {
45
            return new JsonResponse(['status' => 'KO', 'message' => 'Too short search string'], Response::HTTP_FORBIDDEN);
46
        }
47
48
        $this->mediaAdmin->setPersistFilters(false);
49
        $datagrid = $this->mediaAdmin->getDatagrid();
50
        $datagrid->setValue('title', null, 'Suc');
51
        $datagrid->setValue('_per_page', null, $request->query->get('_per_page', 1));
52
        $datagrid->setValue('_page', null, $request->query->get('_page', 10));
53
        $datagrid->buildPager();
54
55
        $pager = $datagrid->getPager();
56
        $results = $pager->getResults();
57
58
        /**
59
         * @var Media $media
60
         */
61
        $items = [];
62
        foreach($results as $media) {
63
            $items[] = [
64
                'id' => $media->getId(),
65
                'label' => $this->templating->render('@MediaMonksSonataMedia/MediaAdmin/autocomplete.html.twig', [
66
                    'media' => $media
67
                ])
68
            ];
69
        }
70
71
        return new JsonResponse([
72
            'status' => 'OK',
73
            'more' => false,
74
            'items' => $items
75
        ]);
76
    }
77
}
78