1+ <?php
2+
3+ namespace Tetranz \Select2EntityBundle \Service ;
4+
5+ use Doctrine \ORM \EntityRepository ;
6+ use Symfony \Component \DependencyInjection \ContainerAwareInterface ;
7+ use Symfony \Component \DependencyInjection \ContainerAwareTrait ;
8+ use Symfony \Component \DependencyInjection \ContainerInterface ;
9+ use Symfony \Component \Form \FormTypeInterface ;
10+ use Symfony \Component \HttpFoundation \Request ;
11+ use Symfony \Component \PropertyAccess \PropertyAccess ;
12+
13+ class AutocompleteService implements ContainerAwareInterface
14+ {
15+ use ContainerAwareTrait;
16+
17+
18+ public function __construct (ContainerInterface $ container )
19+ {
20+ $ this ->setContainer ($ container );
21+ }
22+
23+ /**
24+ * @param Request $request
25+ * @param string|FormTypeInterface $type
26+ *
27+ * @return array
28+ */
29+ public function getAutocompleteResults (Request $ request , $ type )
30+ {
31+ $ form = $ this ->container ->get ('form.factory ' )->create ($ type );
32+ $ fieldOptions = $ form ->get ($ request ->get ('field_name ' ))->getConfig ()->getOptions ();
33+
34+ /** @var EntityRepository $repo */
35+ $ repo = $ this ->container ->get ('doctrine ' )->getRepository ($ fieldOptions ['class ' ]);
36+
37+ $ term = $ request ->get ('q ' );
38+
39+ $ countQB = $ repo ->createQueryBuilder ('e ' );
40+ $ countQB
41+ ->select ($ countQB ->expr ()->count ('e ' ))
42+ ->where ('e. ' .$ fieldOptions ['property ' ].' LIKE :term ' )
43+ ->setParameter ('term ' , '% ' . $ term . '% ' )
44+ ;
45+
46+ $ maxResults = $ fieldOptions ['page_limit ' ];
47+ $ offset = ($ request ->get ('page ' , 1 ) - 1 ) * $ maxResults ;
48+
49+ $ resultQb = $ repo ->createQueryBuilder ('e ' );
50+ $ resultQb
51+ ->where ('e. ' .$ fieldOptions ['property ' ].' LIKE :term ' )
52+ ->setParameter ('term ' , '% ' . $ term . '% ' )
53+ ->setMaxResults ($ maxResults )
54+ ->setFirstResult ($ offset )
55+ ;
56+
57+
58+ if (array_key_exists ('callback ' , $ fieldOptions )) {
59+ $ cb = $ fieldOptions ['callback ' ];
60+
61+ $ cb ($ countQB , $ request );
62+ $ cb ($ resultQb , $ request );
63+ }
64+
65+ $ count = $ countQB ->getQuery ()->getSingleScalarResult ();
66+ $ paginationResults = $ resultQb ->getQuery ()->getResult ();
67+
68+ $ result = ['results ' => null , 'more ' => $ count > ($ offset + $ maxResults )];
69+
70+ $ accessor = PropertyAccess::createPropertyAccessor ();
71+
72+ $ result ['results ' ] = array_map (function ($ item ) use ($ accessor , $ fieldOptions ) {
73+ return ['id ' => $ accessor ->getValue ($ item , $ fieldOptions ['primary_key ' ]), 'text ' => $ accessor ->getValue ($ item , $ fieldOptions ['property ' ])];
74+ }, $ paginationResults );
75+
76+ return $ result ;
77+ }
78+ }
0 commit comments