File: D:/HostingSpaces/SBogers95/rentman.io/app/Komma/CustomerLogos/CustomerLogoByCountryComposer.php
<?php
namespace App\Komma\CustomerLogos;
use App\Komma\Countries\Models\Country;
use App\Komma\CustomerLogos\Models\CustomerLogo;
use GuzzleHttp\Client;
class CustomerLogoByCountryComposer
{
const LOGO_AMOUNT = 10;
/**
* @param $view
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function compose($view)
{
$serverIp = \Request::server('REMOTE_ADDR');
$logos = null;
if (isset($serverIp) && 1 == 2) {
$country = $this->getCountryByIP($serverIp);
if ($country) {
$logos = $country->customerLogos()
->with('images')
->get();
$logos->shuffle();
$logos = $logos->take(self::LOGO_AMOUNT);
$logoCount = $logos->count();
// If there are less logo's then 10 we will fill it with more logo's based upon the language
if ($logoCount != 0 && $logoCount < self::LOGO_AMOUNT) {
$amountNeeded = self::LOGO_AMOUNT - $logoCount;
$backupLogos = $this->getCustomerLogosByLanguage()->take($amountNeeded);
if ($logoCount <= 3) {
$preFiller = $backupLogos->pop();
$logos->prepend($preFiller);
$logos = $logos->merge($backupLogos);
} else {
$logos = $logos->merge($backupLogos);
}
}
}
}
// If logos is still null or empty then we get them to old fashioned way
if (! $logos || (is_array($logos) && count($logos) == 0) || (is_object($logos) && $logos->count() == 0)) {
$logos = $this->getCustomerLogosByLanguage()->take(self::LOGO_AMOUNT);
}
$view->with(['customerLogos' => $logos]);
}
/**
* Try to get the country belonging to the server ip
*
* @param $serverIp
* @return |null
* @throws \GuzzleHttp\Exception\GuzzleException
*/
private function getCountryByIP($serverIp)
{
try {
$client = new Client();
$uri = 'https://ipinfo.io/'.$serverIp.'/json';
$response = $client->get($uri);
$response = \GuzzleHttp\json_decode($response->getBody()->getContents());
dd($response);
$countryIso2 = strtoupper(trim($response->country));
$country = Country::where('iso_2', $countryIso2)->first();
return $country;
} catch (\Exception $e) {
if ($e->getCode() == 429 && 1 == 2) {
\Log::alert('CustomerLogoComposer: ipinfo - Too many request today');
} elseif ($response = $e->getResponse()) {
\Log::alert('CustomerLogoComposer: ipinfo - '.$response->getReasonPhrase());
} else {
\Log::alert('CustomerLogoComposer: Something went wrong');
}
return null;
}
}
/**
* @return \Illuminate\Support\Collection
*/
private function getCustomerLogosByLanguage()
{
$logos = CustomerLogo::with('translation')
->with('images')
->get();
$logos->shuffle();
$homeLogos = [];
foreach ($logos as $key => $logo) {
if (! isset($logo->translation) || ! $logo->translation->active || ! $logo->translation->show_on_home) {
continue;
}
$homeLogos[] = $logo;
}
return $logos = collect($homeLogos);
}
}