CitiesController.php 1.7KB

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