File: D:/HostingSpaces/SBogers10/shop.komma.nl/app/Discounts/Conditions/WeatherHandler.php
<?php declare(strict_types=1);
namespace App\Discounts\Conditions;
use App\Cart\ShoppingCartInterface;
use App\Discounts\Discount;
use App\Discounts\DiscountableInterface;
use App\Discounts\DiscountService;
use Illuminate\Support\Facades\Cache;
class WeatherHandler extends AbstractDiscountConditionHandler
{
public function canBeApplied(DiscountableInterface $discountable, string $operator, string $param): bool
{
$discountService = new DiscountService();
if(!is_a($discountable, ShoppingCartInterface::class)) return false;
$weatherParts = explode(',',$param);
if(count($weatherParts) !== 2) return false;
$weatherstationIndex = (int) $weatherParts[0];
$temperature = (float) $weatherParts[1];
$data = $discountService->weatherInfo();
if(!$data) return false;
if(!array_key_exists('actual', $data)) return false;
if(!array_key_exists('stationmeasurements', $data['actual'])) return false;
if(!is_array($data['actual']['stationmeasurements'])) return false;
$canBeApplied = false;
$stationMeasurements = $data['actual']['stationmeasurements'];
if($weatherstationIndex === 0) {
foreach ($stationMeasurements as $index => $stationMeasurement) {
$stationTemperature = $this->extractWeatherStationData($stationMeasurement, 'temperature');
if(!$stationTemperature) continue;
$canBeApplied = $this->compare($stationTemperature, $operator, $temperature);
if ($canBeApplied) break;
}
} else {
if(!isset($stationMeasurements[$weatherstationIndex])) $canBeApplied = false;
else $canBeApplied = $this->compare(
$this->extractWeatherStationData($stationMeasurements[$weatherstationIndex], 'temperature'),
$operator,
$temperature);
}
// if($canBeApplied) dd($stationMeasurement);
return $canBeApplied;
}
private function extractWeatherStationData(array $stationMeasurement, $variable) {
if (
!is_array($stationMeasurement) ||
!array_key_exists($variable, $stationMeasurement)
) {
return null;
} else {
return $stationMeasurement[$variable];
}
}
private function compare($lhs, $operator, $rhs) {
$result = false;
if($operator === '<') {
if($lhs < (float) $rhs) $result = true;
} else if($operator === '<=') {
if($lhs <= (float) $rhs) $result = true;
} else if($operator === '==') {
if($lhs == (float) $rhs) $result = true;
} else if($operator === '!=') {
if($lhs != (float) $rhs) $result = true;
} else if($operator >= '>=') {
if($lhs >= (float) $rhs) $result = true;
} else if($operator > '>') {
if($lhs > (float) $rhs) $result = true;
}
return $result;
}
private function dissectParam(string $param) {
return array_map('trim', explode(',', $param));
}
}