<?php
namespace App\Infra\Services;
use App\Domain\Entity\Apimo;
use App\Domain\Repository\ApimoRepository;
use App\Domain\Repository\PropertyRepository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Contracts\HttpClient\HttpClientInterface;
class ApiService
{
private $httpClient;
private $apimoRepository;
private $propertyRepository;
public function __construct(
HttpClientInterface $httpClient,
ApimoRepository $apimoRepository,
PropertyRepository $propertyRepository
)
{
$this->httpClient = $httpClient;
$this->apimoRepository = $apimoRepository;
$this->propertyRepository = $propertyRepository;
}
public function getAllProperties()
{
$apimos = $this->apimoRepository->findAll();
$properties = [];
$db_response = [];
if($apimos){
foreach($apimos as $apimo){
$properties[] = $this->setLocalImages($apimo);
}
$db_response = ["total_items" => count($apimos), "properties" => $properties];
return $db_response;
}
else{
$response = $this->httpClient->request(
'GET',
'https://api.apimo.pro/agencies/20169/properties', [
'auth_basic' => [
'user' => '2450:0e7a10ed20e96147ecb47c083644ffa023b4155e',
],
'timeout' => 3
],
);
return $response->getStatusCode() !== 200 ? ['properties' => []] : $response->toArray();
}
}
public function getPropertyById(string $id)
{
$apimo = ($this->apimoRepository->findOneBy(["apimo_id" => $id]));
if($apimo) return $this->setLocalImages($apimo);
try{
$response = $this->httpClient->request(
'GET',
'https://api.apimo.pro/agencies/20169/properties/'.$id, [
'auth_basic' => [
'user' => '2450:0e7a10ed20e96147ecb47c083644ffa023b4155e',
],
'timeout' => 3
]
);
return $response->getStatusCode() !== 200 ? [
'bedrooms' => null,
'type' => null,
'reference' => null,
'pictures' => null,
'area' => ['value' => null],
'areas' => null,
'construction' => ['construction_year' => null],
'available_at' => null,
'city' => ["name" => null],
'regulations' => null,
'price' => ["value" => null],
'comments' => [["comment" => "erreur de connexion avec l'API, merci de réessayer plus tard"]],
'category' => null,
] : $response->toArray();
}
catch(\Exception $e){
return [
'bedrooms' => null,
'type' => null,
'reference' => null,
'pictures' => null,
'area' => ['value' => null],
'areas' => null,
'construction' => ['construction_year' => null],
'available_at' => null,
'city' => ["name" => null],
'regulations' => null,
'price' => ["value" => null],
'comments' => [["comment" => "erreur de connexion avec l'API, merci de réessayer plus tard"]],
'category' => null,
];
}
}
/**
* Return Apimo json content in array with replacement of images url
*
* @param Apimo $apimo
* @return array
*/
private function setLocalImages(Apimo $apimo): array{
$property = $this->propertyRepository->findOneBy(["apimo" => $apimo]);
$datas = json_decode($apimo->getJson(), true);
$i = 0;
foreach($datas["pictures"] as $picture){
if($property->getImages()[$i]){
$datas["pictures"][$i]["url"] = $property->getImages()[$i]->getUrl();
}
$i++;
}
return $datas;
}
}