Passed
Push — master ( c0f32c...e879f4 )
by Chema
04:17 queued 41s
created

RecentNewsWasFound::findLatestDateTimeFromNews()   A

Complexity

Conditions 3
Paths 1

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 16
ccs 11
cts 11
cp 1
rs 9.9666
cc 3
nc 1
nop 1
crap 3
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\WriteModel\News;
9
use Chemaclass\StockTicker\Domain\WriteModel\Quote;
10
11
final class RecentNewsWasFound implements PolicyConditionInterface
12
{
13
    /**
14
     * @var array<string,string>
15
     * For example ['Symbol' => 'datetime']
16
     */
17
    private static array $cacheOldestBySymbol = [];
18
19 3
    public function __invoke(Quote $quote): bool
20
    {
21 3
        if (null === $quote->getSymbol()) {
22 2
            return false;
23
        }
24
25 2
        $current = $this->findLatestDateTimeFromNews($quote);
26 2
        $previous = self::$cacheOldestBySymbol[$quote->getSymbol()] ?? '';
27
28 2
        self::$cacheOldestBySymbol[$quote->getSymbol()] = $current;
29
30 2
        return $current > $previous;
31
    }
32
33 2
    private function findLatestDateTimeFromNews(Quote $quote): string
34
    {
35 2
        $reduced = array_reduce(
36 2
            $quote->getLatestNews(),
37 2
            static function (?News $carry, News $current): News {
38 2
                if (null === $carry) {
39 2
                    return $current;
40
                }
41
42 2
                return $carry->getDatetime() > $current->getDatetime()
43 1
                    ? $carry
44 2
                    : $current;
45 2
            }
46
        );
47
48 2
        return $reduced->getDatetime() ?? '';
49
    }
50
}
51