-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
ExchangeFactory.php
97 lines (79 loc) · 2.58 KB
/
ExchangeFactory.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php declare(strict_types=1);
namespace h4kuna\Exchange;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\HttpFactory;
use h4kuna\CriticalCache\PSR16\CacheLockingFactoryInterface;
use h4kuna\CriticalCache\PSR16\Locking\CacheLockingFactory;
use h4kuna\Dir\Dir;
use h4kuna\Exchange\Download\SourceDownload;
use h4kuna\Exchange\Exceptions\MissingDependencyException;
use h4kuna\Exchange\RatingList\CacheEntity;
use h4kuna\Exchange\RatingList\RatingListCache;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
final class ExchangeFactory implements ExchangeFactoryInterface
{
private RatingListCache $ratingListCache;
private CacheEntity $cacheEntity;
/**
* @param array<string> $allowedCurrencies
*/
public function __construct(
private string $from = 'CZK',
private ?string $to = null,
?RatingListCache $ratingListCache = null,
array $allowedCurrencies = [],
?ClientInterface $client = null,
?RequestFactoryInterface $requestFactory = null,
?CacheEntity $cacheEntity = null,
string|Dir|CacheLockingFactoryInterface $tempDir = 'exchange',
)
{
$this->cacheEntity = $cacheEntity ?? new CacheEntity();
$this->ratingListCache = $ratingListCache ?? self::createRatingListCache(Utils::transformCurrencies($allowedCurrencies), $client, $requestFactory, $tempDir);
}
/**
* @param array<string, int> $allowedCurrencies
*/
private static function createRatingListCache(
array $allowedCurrencies,
?ClientInterface $client,
?RequestFactoryInterface $requestFactory,
string|Dir|CacheLockingFactoryInterface $tempDir,
): RatingListCache
{
$cacheLockingFactory = $tempDir instanceof CacheLockingFactoryInterface
? $tempDir
: self::createCacheFactory($tempDir);
return new RatingListCache(
$cacheLockingFactory->create(),
new SourceDownload($client ?? self::createClient(), $requestFactory ?? self::createRequestFactory(), $allowedCurrencies),
);
}
public function create(
?string $from = null,
?string $to = null,
?CacheEntity $cacheEntity = null,
): Exchange
{
return new Exchange(
$from ?? $this->from,
$this->ratingListCache->build($cacheEntity ?? $this->cacheEntity),
$to ?? $this->to,
);
}
private static function createCacheFactory(string|Dir $tempDir): CacheLockingFactoryInterface
{
return new CacheLockingFactory($tempDir);
}
private static function createClient(): ClientInterface
{
MissingDependencyException::guzzleClient();
return new Client();
}
private static function createRequestFactory(): RequestFactoryInterface
{
MissingDependencyException::guzzleFactory();
return new HttpFactory();
}
}