-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathCsvPrices.php
46 lines (37 loc) · 1.01 KB
/
CsvPrices.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
declare(strict_types=1);
namespace Simara\Cart\Infrastructure;
use Simara\Cart\Domain\Price;
use Simara\Cart\Domain\Prices\PriceNotFoundException;
use Simara\Cart\Domain\Prices\Prices;
use function fopen;
use function is_resource;
final class CsvPrices implements Prices
{
/**
* @var array<string, Price>
*/
private array $prices = [];
public function __construct(private string $filename)
{
}
public function unitPrice(string $productId): Price
{
$this->loadPrices();
return $this->prices[$productId] ?? throw new PriceNotFoundException();
}
private function loadPrices(): void
{
if ($this->prices !== []) {
return;
}
$handle = fopen($this->filename, 'r');
assert(is_resource($handle));
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$id = $data[0];
$price = new Price($data[1]);
$this->prices[$id] = $price;
}
fclose($handle);
}
}