src/Diplix/KMGBundle/Service/TalixoConnector.php line 74

Open in your IDE?
  1. <?php
  2. namespace Diplix\KMGBundle\Service;
  3. use Diplix\KMGBundle\Entity\TalixoItem;
  4. use Diplix\KMGBundle\Entity\TalixoItemPlace;
  5. use Doctrine\ORM\EntityManager;
  6. use Doctrine\ORM\EntityManagerInterface;
  7. use GuzzleHttp;
  8. use Doctrine\DBAL\Driver\Connection;
  9. use Symfony\Component\PropertyAccess\PropertyAccess;
  10. /**
  11.     Beta key
  12.     48f78fa081264362af976bfaa0f93b29
  13.     Production key
  14.     9d548fb259e944788684860fb5d8fa71
  15.  */
  16. class TalixoConnector
  17. {
  18.     const STATUS "status";
  19.     const BODY "body";
  20.     const URL "url";
  21.     const METHOD "method";
  22.     const REQUEST "request";
  23.     const BETA_KEY "48f78fa081264362af976bfaa0f93b29";
  24.     public static $connectionSettings = array(
  25.                 'connect_timeout' => "5"// abort if no response after X seconds
  26.                 'verify' => false// we do not care if the cert is valid or not
  27.                 'http_errors' => false// do not throw exception on 4xx/5xx http responses
  28.     );
  29.     public static $transformationMap = [
  30.             "firstName"=>"first_name",
  31.             "lastName"=> "last_name",
  32.             "mobilePhone"=>"mobile",
  33.             "paymentMethod"=>"payment_method",
  34.             "bookingNumber"=>"booking_number"
  35.         ];
  36.     /**
  37.      * @var GuzzleHttp\Client
  38.      */
  39.     protected $client;
  40.     /**
  41.      * @var EntityManager
  42.      */
  43.     protected $em;
  44.     /**
  45.      * @var Connection
  46.      */
  47.     protected $db;
  48.     protected $serverAddress "http://localhost/KMG/Web/web/app_dev.php/kmg/talixo-mock/";
  49.     public function __construct(EntityManagerInterface $em)
  50.     {
  51.         $this->logPath =  __DIR__ "/../../../../app/logs/talixo.log";
  52.         $this->em $em;
  53.         $this->db $this->em->getConnection();
  54.         // init http client (guzzle 6.x)
  55.         $this->client = new GuzzleHttp\Client($this::$connectionSettings);
  56.     }
  57.     public function setServerAddress($url)
  58.     {
  59.         $this->serverAddress $url;
  60.     }
  61.     protected function log($dir=0,$urlOrStatus,$data)
  62.     {
  63.         $msg "[".date("Y-m-d H:i:s")."]".($dir == ">>>\n" : ($dir == ?  "<<<\n"  "(trace)" ) );
  64.         $msg .= $urlOrStatus " : " $data "\n";
  65.         file_put_contents($this->logPath$msgFILE_APPEND);
  66.     }
  67.     protected function getUrl($cmd)
  68.     {
  69.         return rtrim($this->serverAddress,"/")."/" $cmd;
  70.     }
  71.     protected function flattenPlace($prefixTalixoItemPlace $place)
  72.     {
  73.         return [
  74.             $prefix."_iata_code"    => $place->getIataCode(),
  75.             $prefix."_point"    => $place->getAddress(),
  76.             $prefix."_place_id"    => $place->getPlaceId(),
  77.             $prefix."_point_lat"    => $place->getLatitude(),
  78.             $prefix."_point_lng"    => $place->getLongitude(),
  79.         ];
  80.     }
  81.     /**
  82.      * @param $data
  83.      * @param TalixoItemPlace|null $place
  84.      * @return TalixoItemPlace
  85.      */
  86.     protected function erectPlace($data,TalixoItemPlace $place)
  87.     {
  88.         if (is_null($place)) $place = new TalixoItemPlace();
  89.         $place->setTalixoId($data["talixo_id"]);
  90.         $place->setLatitude($data["latitude"]);
  91.         $place->setLongitude($data["longitude"]);
  92.         $place->setAddress($data["address"]);
  93.         // [...]
  94.         return $place;
  95.     }
  96.     /**
  97.      * convert from TalixoItem to associative array
  98.      * @param TalixoItem $item
  99.      * @return array
  100.      */
  101.     protected function flatten(TalixoItem $item)
  102.     {
  103.         $out = [];
  104.         $out array_merge($out,$this->flattenPlace("start",$item->getStartPoint()));
  105.         $out array_merge($out,$this->flattenPlace("end",$item->getEndPoint()));
  106.         if (!is_null($item->getStartTime()))
  107.         {
  108.             $out["start_time_date"] = $item->getStartTime()->format("Y-m-d");
  109.             $out["start_time_time"] = $item->getStartTime()->format("H:i");
  110.         }
  111.         $accessor PropertyAccess::createPropertyAccessor();
  112.         foreach (self::$transformationMap as $fin=>$fout)
  113.         {
  114.             $out[$fout] = $accessor->getValue($item,$fin);
  115.         }
  116.         return $out;
  117.     }
  118.     /**
  119.      * convert from assoc array to TalixoItem
  120.      * @param array $data
  121.      * @param TalixoItem $item
  122.      */
  123.     protected function erect(array $data,TalixoItem $item)
  124.     {
  125.         $item->setRaw(json_encode($data));
  126.         $pm $data["payment_method"];
  127.         unset($data["payment_method"]);
  128.         $item->setPaymentMethod$pm["label"] );
  129.         $accessor PropertyAccess::createPropertyAccessor();
  130.         foreach (array_flip(self::$transformationMap) as $fx=>$fobj)
  131.         {
  132.             if (array_key_exists($fx,$data)) $accessor->setValue($item,$fobj,$data[$fx]);
  133.         }
  134.         if (array_key_exists("start_point",$data))
  135.         {
  136.             $item->setStartPoint$this->erectPlace($data["start_point"],$item->getStartPoint()) );
  137.         }
  138.         if (array_key_exists("end_point",$data))
  139.         {
  140.             $item->setEndPoint$this->erectPlace($data["end_point"],$item->getEndPoint()) );
  141.         }
  142.     }
  143.     protected function req($method,$cmd$data)
  144.     {
  145.         $url = (strpos($cmd,"http") === false $this->getUrl($cmd) : $cmd );
  146.         $body json_encode($data);
  147.         $this->log(0,$url,$body);
  148.         $res $this->client->request($method,$url,[
  149.                 'headers'   =>[
  150.                     'Content-Type' => 'application/json'// content-type text/json not supported by talixo v3
  151.                     'Partner' => self::BETA_KEY
  152.                 ],
  153.                 "body"      =>$body
  154.         ]);
  155.         $content $res->getBody()->getContents();
  156.         $this->log(1,$res->getStatusCode(),$content);
  157.         return [
  158.             self::METHOD => $method,
  159.             self::URL => $url,
  160.             self::REQUEST => $data,
  161.             self::STATUS => $res->getStatusCode() ,
  162.             self::BODY =>  json_decode($content,true)
  163.         ];
  164.     }
  165.     protected function post($cmd,$data)
  166.     {
  167.         return $this->req("POST",$cmd,$data);
  168.     }
  169.     protected function get($cmd,$data)
  170.     {
  171.         return $this->req("GET",$cmd,$data);
  172.     }
  173.     protected function check4ErrorResponse($res)
  174.     {
  175.         if ($res[self::STATUS] > 299)
  176.         {
  177.             $err = [];
  178.             $err[] = sprintf("Service error (http %d) on %s %s",$res[self::STATUS],$res[self::METHOD],$res[self::URL]);
  179.             if (array_key_exists("errors",$res[self::BODY]))
  180.             {
  181.                 foreach ($res[self::BODY]["errors"] as $one)
  182.                 {
  183.                     $err[]= $one["id"].": " join(",",$one["errors"]);
  184.                 }
  185.             }
  186.             else
  187.             {
  188.                 $err[]= "Undefined error";
  189.             }
  190.             throw new \Exception(join(";\n",$err));
  191.         }
  192.     }
  193.     public function remote2entity(TalixoItem $it, array $row)
  194.     {
  195.         $it->setRaw(json_encode($row));
  196.         $it->setBookingNumber($row["booking_number"]);
  197.         $start TalixoItemPlace::fromArray($row["start_point"]);
  198.         $end TalixoItemPlace::fromArray($row["end_point"]);
  199.         $it->setStartPoint($start);
  200.         $it->setEndPoint($end);
  201.         $it->setStartTime(new \DateTime($row["start_time"]));
  202.         $it->setEndTime(new \DateTime($row["end_time"]));
  203.         $it->setPin($row["pin"]);
  204.         $it->setDuration($row["duration"]);
  205.         $it->setDistance($row["distance"]);
  206.         $it->setPassengerCount($row["passengers"]);
  207.         $it->setOrigin($row["booking_origin"]);
  208.         $it->setFirstName($row["passenger"]["first_name"]);
  209.         $it->setLastName($row["passenger"]["last_name"]);
  210.         $it->setMobilePhone($row["passenger"]["mobile"]);
  211.         
  212.         return $it;
  213.     }
  214.     public function booking_query(TalixoItem $item)
  215.     {
  216.         $data $this->flatten($item);
  217.         $res $this->post("vehicles/booking_query/",$data);
  218.         $this->check4ErrorResponse($res);
  219.         return $res;
  220.     }
  221.     public function createBooking(TalixoItem $item)
  222.     {
  223.         $data $this->flatten($item);
  224.         $res $this->post("bookings/",$data);
  225.         $this->check4ErrorResponse($res);
  226.         $this->erect($res[self::BODY],$item);
  227.         return $res;
  228.     }
  229.     public function bookings()
  230.     {
  231.         $res $this->get("bookings/",[]);
  232.         $this->check4ErrorResponse($res);
  233.         $resultRows = [];
  234.         while (1)
  235.         {
  236.             $b $res["body"];
  237.             if ($b["count"]>0)
  238.             {
  239.                 foreach ($b["results"] as $row)
  240.                 {
  241.                     $resultRows[] = $row;
  242.                 }
  243.             }
  244.             if ($b["next"]!=null)
  245.             {
  246.                 $res $this->get($b["next"],[]);
  247.                 $this->check4ErrorResponse($res);
  248.             }
  249.             else
  250.             {
  251.                 break;
  252.             }
  253.         }
  254.         return $resultRows;
  255.     }
  256. }