4 лет назад
4 лет назад
4 лет назад
4 лет назад
4 лет назад
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace Lc\ShopBundle\Services ;
  3. class CityUtils
  4. {
  5. function callApi($method, $url, $data = false)
  6. {
  7. $url = 'https://geo.api.gouv.fr/'.$url ;
  8. $curl = curl_init();
  9. switch ($method)
  10. {
  11. case "POST":
  12. curl_setopt($curl, CURLOPT_POST, 1);
  13. if ($data)
  14. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  15. break;
  16. case "PUT":
  17. curl_setopt($curl, CURLOPT_PUT, 1);
  18. break;
  19. default:
  20. if ($data)
  21. $url = sprintf("%s?%s", $url, http_build_query($data));
  22. }
  23. // Optional Authentication:
  24. curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  25. curl_setopt($curl, CURLOPT_USERPWD, "username:password");
  26. curl_setopt($curl, CURLOPT_URL, $url);
  27. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  28. $result = curl_exec($curl);
  29. curl_close($curl);
  30. return $result;
  31. }
  32. public function getZipByCity($city)
  33. {
  34. $zip = null ;
  35. $returnCitiesSearchZip = json_decode($this->callApi('get', 'communes', ['nom' => $city, 'fields' => 'nom,codesPostaux'])) ;
  36. if($returnCitiesSearchZip) {
  37. foreach($returnCitiesSearchZip as $citySearchZip) {
  38. if(strtolower(trim($city)) == strtolower(trim($citySearchZip->nom))) {
  39. $zip = $citySearchZip->codesPostaux[0] ;
  40. }
  41. }
  42. }
  43. return $zip ;
  44. }
  45. }