87 lines
2.3 KiB
PHP
87 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Repositories;
|
|
|
|
use App\Contracts\PriceClient;
|
|
use App\Contracts\PriceRepository as ContractsPriceRepository;
|
|
use App\Data\ElectricityData;
|
|
use App\Data\GasData;
|
|
use Carbon\Carbon;
|
|
use Illuminate\Support\Collection;
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Override;
|
|
|
|
class ZonneplanPriceRepository implements ContractsPriceRepository
|
|
{
|
|
private int $cacheTtl;
|
|
private string $cachePrefix;
|
|
|
|
public function __construct(
|
|
public PriceClient $client
|
|
) {
|
|
$this->cacheTtl = config('cache_prices.ttl', 3600);
|
|
$this->cachePrefix = config('cache_prices.prefix', 'zonneplan:');
|
|
}
|
|
|
|
#[Override]
|
|
public function retrieveElectricity(): Collection
|
|
{
|
|
$raw = $this->remember(
|
|
'electricity:upcoming',
|
|
fn () => $this->client->getElectricityPrices()->toArray()
|
|
);
|
|
|
|
return ElectricityData::collect($raw, Collection::class);
|
|
}
|
|
|
|
#[Override]
|
|
public function retrieveGas(): Collection
|
|
{
|
|
$raw = $this->remember(
|
|
'gas:upcoming',
|
|
fn () => $this->client->getGasPrices()->toArray()
|
|
);
|
|
|
|
return GasData::collect($raw, Collection::class);
|
|
}
|
|
|
|
#[Override]
|
|
public function retrieveElectricityForDate(Carbon $date): Collection
|
|
{
|
|
$raw = $this->remember(
|
|
'electricity:' . $date->format('Y-m-d'),
|
|
fn () => $this->client->getElectricityPricesForDate($date)->toArray()
|
|
);
|
|
|
|
return ElectricityData::collect($raw, Collection::class);
|
|
}
|
|
|
|
#[Override]
|
|
public function retrieveGasForDate(Carbon $date): Collection
|
|
{
|
|
$raw = $this->remember(
|
|
'gas:' . $date->format('Y-m-d'),
|
|
fn () => $this->client->getGasPricesForDate($date)->toArray()
|
|
);
|
|
|
|
return GasData::collect($raw, Collection::class);
|
|
}
|
|
|
|
/**
|
|
* Cache via JSON encoding to ensure clean array structure on retrieval.
|
|
*
|
|
* @param callable(): array $callback
|
|
* @return array
|
|
*/
|
|
private function remember(string $key, callable $callback): array
|
|
{
|
|
$cached = Cache::remember(
|
|
$this->cachePrefix . $key,
|
|
$this->cacheTtl,
|
|
fn () => json_encode($callback())
|
|
);
|
|
|
|
return json_decode($cached, true);
|
|
}
|
|
}
|