Passed
Push — master ( 3ec735...0b5e67 )
by Chema
01:36 queued 14s
created

OlderWasFound::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chemaclass\StockTicker\Domain\Notifier\Policy\Condition;
6
7
use Chemaclass\StockTicker\Domain\Notifier\Policy\PolicyConditionInterface;
8
use Chemaclass\StockTicker\Domain\ReadModel\Company;
9
10
final class OlderWasFound implements PolicyConditionInterface
11
{
12
    /**
13
     * @var array<string,string>
14
     * For example ['TickerSymbol' => 'datetime']
15
     */
16
    private static array $cacheOldestBySymbol = [];
17
18
    private string $companyKey;
19
20
    private string $keyToCompare;
21
22 1
    public function __construct(string $companyKey, string $keyToCompare = 'datetime')
23
    {
24 1
        $this->companyKey = $companyKey;
25 1
        $this->keyToCompare = $keyToCompare;
26 1
    }
27
28 1
    public function __invoke(Company $company): bool
29
    {
30 1
        $current = $this->findLatestDateTimeFromNews($company);
31 1
        $previous = self::$cacheOldestBySymbol[$company->symbol()->toString()] ?? '';
32
33 1
        self::$cacheOldestBySymbol[$company->symbol()->toString()] = $current;
34
35 1
        return $current > $previous;
36
    }
37
38 1
    private function findLatestDateTimeFromNews(Company $company): string
39
    {
40 1
        $reduced = array_reduce(
41 1
            (array) $company->info($this->companyKey),
42 1
            function (?array $carry, array $current): array {
43 1
                if (null === $carry) {
0 ignored issues
show
introduced by
The condition null === $carry is always false.
Loading history...
44 1
                    return $current;
45
                }
46
47 1
                return $carry[$this->keyToCompare] > $current[$this->keyToCompare]
48 1
                    ? $carry
49 1
                    : $current;
50 1
            }
51
        );
52
53 1
        return $reduced[$this->keyToCompare];
54
    }
55
}
56