RegionCurrencies::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace ICanBoogie\CLDR\Supplemental\Territory;
4
5
use ArrayIterator;
6
use IteratorAggregate;
7
use Traversable;
8
9
/**
10
 * @implements IteratorAggregate<RegionCurrency>
11
 */
12
final class RegionCurrencies implements IteratorAggregate
13
{
14
    /**
15
     * @phpstan-ignore-next-line
16
     */
17
    public static function from(array $data): self
18
    {
19
        $currencies = array_values(array_map(fn($currency) => RegionCurrency::from($currency), $data));
20
21
        usort($currencies, function (RegionCurrency $a, RegionCurrency $b) {
22
            if ($a->from && $b->from) {
23
                return $a->from <=> $b->from;
24
            } elseif ($a->to && $b->to) {
25
                return $b->to <=> $a->to;
26
            }
27
28
            return -1;
29
        });
30
31
        return new self($currencies);
32
    }
33
34
    /**
35
     * @param RegionCurrency[] $currencies
36
     */
37
    private function __construct(
38
        private readonly array $currencies
39
    ) {
40
    }
41
42
    public function getIterator(): Traversable
43
    {
44
        return new ArrayIterator($this->currencies);
45
    }
46
47
    public function at(string $date): ?RegionCurrency
48
    {
49
        $currencies = array_filter(
50
            $this->currencies,
51
            function (RegionCurrency $currency) use ($date) {
52
                return $currency->tender
53
                    && ($currency->to === null || $currency->to >= $date)
54
                    && ($currency->from === null || $currency->from <= $date);
55
            }
56
        );
57
58
        $currencies = array_values($currencies);
59
60
        return current($currencies) ?: null;
61
    }
62
}
63