58 lines
1.7KB

  1. <?php
  2. namespace Lc\ShopBundle\Controller ;
  3. use Lc\ShopBundle\Services\Cities;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. class CitiesController extends AbstractController
  8. {
  9. protected $cities ;
  10. public function __construct(Cities $cities)
  11. {
  12. $this->cities = $cities ;
  13. }
  14. public function index(Request $request) : JsonResponse
  15. {
  16. $term = $request->get('term') ;
  17. $context = $request->get('context') ;
  18. $data = [
  19. 'boost' => 'population',
  20. ] ;
  21. if(strlen($term) == 5 && is_numeric($term)) {
  22. $data['codePostal'] = $term ;
  23. }
  24. else {
  25. $data['nom'] = $term;
  26. }
  27. $result = array_merge(
  28. json_decode($this->cities->callApi('get', 'communes', array_merge($data, ['codeRegion' => 27]))),
  29. json_decode($this->cities->callApi('get', 'communes', array_merge($data, ['codeRegion' => 44])))
  30. );
  31. $return = [] ;
  32. foreach($result as $city) {
  33. $return[] = [
  34. 'label' => $city->nom,
  35. 'value' => $city->code
  36. ] ;
  37. }
  38. if($context == 'frontend') {
  39. $return = [
  40. 'items' => $return
  41. ] ;
  42. }
  43. return new JsonResponse($return) ;
  44. }
  45. }