1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace MediaMonks\SonataMediaBundle\Controller; |
4
|
|
|
|
5
|
|
|
use MediaMonks\SonataMediaBundle\Admin\MediaAdmin; |
6
|
|
|
use MediaMonks\SonataMediaBundle\Model\MediaInterface; |
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 HelperController |
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 JsonResponse |
37
|
|
|
*/ |
38
|
|
View Code Duplication |
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, $searchText); |
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 MediaInterface $media |
60
|
|
|
*/ |
61
|
|
|
$items = []; |
62
|
|
|
foreach($results as $media) { |
63
|
|
|
$items[] = [ |
64
|
|
|
'id' => $media->getId(), |
65
|
|
|
'label' => $this->templating->render('@MediaMonksSonataMedia/CRUD/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
|
|
|
|
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.