-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCardResolver.php
90 lines (71 loc) · 2.32 KB
/
CardResolver.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
<?php
/**
* Resolves payment card type.
*
* @package TheWebSolver\Codegarage\Validation
*/
declare( strict_types = 1 );
namespace TheWebSolver\Codegarage\PaymentCard\Traits;
use TypeError;
use LogicException;
use TheWebSolver\Codegarage\PaymentCard\PaymentCard;
use TheWebSolver\Codegarage\PaymentCard\CardInterface as Card;
use TheWebSolver\Codegarage\PaymentCard\CardFactory as Factory;
/** @phpstan-import-type CardSchema from Factory */
trait CardResolver {
/** @var Card[] */
private array $cards;
private bool $registeredOnly;
private function setCards( Card $card, Card ...$cards ): void {
$this->cards = array( $card, ...$cards );
}
private function withoutDefaults(): static {
$this->registeredOnly = true;
return $this;
}
/**
* @param string|CardSchema $data
* @throws TypeError When content parsed from $data does not match the `CardSchema`.
*/
private function registerCardsFromPayload( string|array $data ): void {
$this->cards = ( new Factory() )->withPayload( $data )->createCards( preserveKeys: false );
}
/** @return Card[] */
private function getCards(): array {
$cards = $this->cards ?? array();
return ( $this->registeredOnly ?? false ) ? $cards : array( ...PaymentCard::cases(), ...$cards );
}
/** @return CardSchema[] */
private function getCardsContent(): array {
return array_map( array: $this->getCards(), callback: $this->getCardContent( ... ) );
}
/** @return CardSchema */
private function getCardContent( Card $card ): array {
$data = array();
foreach ( Factory::CARD_SCHEMA as $key => $schema ) {
if ( str_ends_with( haystack: $key, needle: '?' ) ) {
continue;
}
$getterMethod = 'get' . ucwords( $key );
$data[ $key ] = $card->{$getterMethod}();
}
/** @var CardSchema */
return $data;
}
/** @throws LogicException When cards not registered and `CardResolver::withoutDefaults()` used. */
private function resolveCardFromNumber( string|int $number ): ?Card {
if ( empty( $cards = $this->getCards() ) ) {
throw new LogicException(
sprintf( 'Payment Cards not registered. Impossible to resolve card number: "%s".', $number )
);
}
$length = 0;
$matches = null;
foreach ( $cards as $card ) {
if ( $card->isNumberValid( $number ) ) {
PaymentCard::matchIdRange( $card, $number, $length, $matches );
}
}
return $matches;
}
}