Passed
Pull Request — master (#11)
by Svaťa
02:42
created

CsvPrices::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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
    /**
18
     * @var array<string, Price>
19
     */
20 4
    private array $prices = [];
21
22 4
    public function __construct(private string $filename)
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected T_PRIVATE, expecting T_VARIABLE on line 22 at column 32
Loading history...
23 4
    {
24
    }
25 3
26
    public function unitPrice(string $productId): Price
27 3
    {
28 3
        $this->loadPrices();
29 1
        return $this->prices[$productId] ?? throw new PriceNotFoundException();
30
    }
31 2
32
    private function loadPrices(): void
33
    {
34 3
        if ($this->prices !== []) {
35
            return;
36 3
        }
37 3
38 3
        $handle = fopen($this->filename, 'r');
39 3
        assert(is_resource($handle));
40 3
        while (($data = fgetcsv($handle, 1000, ",")) !== false) {
41 3
            $id = $data[0];
42 3
            $price = new Price($data[1]);
43
            $this->prices[$id] = $price;
44 3
        }
45
        fclose($handle);
46 3
    }
47
}
48