CsvPrices::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 0
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 2
rs 10
ccs 1
cts 1
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Simara\Cart\Infrastructure;
6
7
use Simara\Cart\Domain\Price;
8
use Simara\Cart\Domain\Prices\PriceNotFoundException;
9
use Simara\Cart\Domain\Prices\Prices;
10
11
use function fopen;
12
use function is_resource;
13
14
final class CsvPrices implements Prices
15
{
16
    /**
17
     * @var array<string, Price>
18
     */
19
    private array $prices = [];
20 4
21
    public function __construct(private string $filename)
22 4
    {
23 4
    }
24
25 3
    public function unitPrice(string $productId): Price
26
    {
27 3
        $this->loadPrices();
28 3
        return $this->prices[$productId] ?? throw new PriceNotFoundException();
29 1
    }
30
31 2
    private function loadPrices(): void
32
    {
33
        if ($this->prices !== []) {
34 3
            return;
35
        }
36 3
37 3
        $handle = fopen($this->filename, 'r');
38 3
        assert(is_resource($handle));
39 3
        while (($data = fgetcsv($handle, 1000, ",")) !== false) {
40 3
            $id = $data[0];
41 3
            $price = new Price($data[1]);
42 3
            $this->prices[$id] = $price;
43
        }
44 3
        fclose($handle);
45
    }
46
}
47