-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCardFactory.php
326 lines (273 loc) · 9.76 KB
/
CardFactory.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
<?php
/**
* Payment Card factory.
*
* @package TheWebSolver\Codegarage\Validation
*/
declare( strict_types = 1 );
namespace TheWebSolver\Codegarage\PaymentCard;
use Generator;
use Throwable;
use TypeError;
use InvalidArgumentException;
use TheWebSolver\Codegarage\PaymentCard\CardInterface as Card;
/**
* @phpstan-type CardSchema array{
* type?: string,
* classname?: string,
* checkLuhn?: bool,
* name: string,
* alias: string,
* breakpoint: array<string|int>,
* code: array{0:string, 1:int},
* length: array<int,string|int|array<int,string|int>>,
* idRange: array<int,string|int|array<int,string|int>>,
* }
*/
class CardFactory {
public const CREDIT_CARD = 'Credit Card';
public const DEBIT_CARD = 'Debit Card';
public const DEFAULT_CARD = 'Payment Card';
/**
* Possible array keys and their values' datatype Schema for a Payment Card.
*
* - If `type` key not passed, Payment Card is treated as a Credit Card.
* - If `classname` key not passed, anonymous class is used.
* - If `checkLuhn` key not passed, Luhn algorithm is always checked.
*/
public const CARD_SCHEMA = array(
'type?' => 'string',
'classname?' => 'string',
'checkLuhn?' => 'bool',
'name' => 'string',
'alias' => 'string',
'breakpoint' => 'array<string|int>',
'code' => 'array{0:string,1:int}',
'length' => 'array<int,string|int|array<int,string|int>>',
'idRange' => 'array<int,string|int|array<int,string|int>>',
);
/** @var array<mixed> */
private array $content;
private string $path = '';
/**
* List of Payment Card instances for `PaymentCard` enums.
*
* @var Card[]
*/
private static array $cards;
/** @var ?class-string<Card> */
private static ?string $defaultCardClass;
public function __construct( mixed $data = null /* $fileType: for internal use only */ ) {
if ( null !== $data ) {
if ( 2 === func_num_args() && ( $fileType = func_get_arg( position: 1 ) ) && is_string( $fileType ) ) {
$type = $fileType;
}
$this->resolvePayloadContent( $data, $type ?? '' );
}
}
/** @param class-string<Card> $classname */
public static function setGlobalCardClass( string $classname ): void {
self::$defaultCardClass ??= $classname;
}
public static function resetGlobalCardClass(): void {
self::$defaultCardClass = null;
}
/** @param string|mixed[] $data */
public function withPayload( string|array $data ): self {
$this->resolvePayloadContent( $data );
return $this;
}
/**
* @param string $index The JSON key.
* @param mixed[] $args Never used.
* @throws TypeError When something went wrong.
* @access private
*/
public static function __callStatic( string $index, array $args ): Card {
$slash = DIRECTORY_SEPARATOR;
self::$cards ??= ( new self() )
->withPayload( data: dirname( __DIR__ ) . $slash . 'Resource' . $slash . 'paymentCards.json' )
->createCards();
return self::$cards[ $index ] ?? self::shutdownForInvalidJsonKey( $index );
}
/**
* @return array<string|int,Card>|Generator
* @throws TypeError When $args passed does not match the `CardFactory::CARD_SCHEMA`.
* @phpstan-return ($lazyload is true ? Generator : array<string|int,Card>)
*/
public static function createFromPhpFile(
string $path,
bool $preserveKeys = true,
bool $lazyload = false
): array|Generator {
$factory = ( new self( ...self::parsePhpContent( $path ) ) );
$factory->path = $path;
return $lazyload ? $factory->lazyLoadCards( $preserveKeys ) : $factory->createCards( $preserveKeys );
}
/**
* @return array<string|int,Card>|Generator
* @throws TypeError When $args passed does not match the `CardFactory::CARD_SCHEMA`.
* @phpstan-return ($lazyload is true ? Generator : array<string|int,Card>)
*/
public static function createFromJsonFile(
string $path,
bool $preserveKeys = true,
bool $lazyload = false
): array|Generator {
$factory = ( new self( ...self::parseJsonContent( $path ) ) );
$factory->path = $path;
return $lazyload ? $factory->lazyLoadCards( $preserveKeys ) : $factory->createCards( $preserveKeys );
}
/**
* @return array<string|int,Card>
* @throws TypeError When $args passed does not match the `CardFactory::CARD_SCHEMA`.
* @phpstan-return ($lazyload is true ? Generator : array<string|int,Card>)
*/
public static function createFromFile(
string $path,
bool $preserveKeys = true,
bool $lazyload = false
): array|Generator {
$factory = new self( ...self::parseContentIfFile( $path ) );
$factory->path = $path;
return $lazyload ? $factory->lazyLoadCards( $preserveKeys ) : $factory->createCards( $preserveKeys );
}
/**
* @return array<string|int,Card>
* @throws TypeError When $args passed does not match the `CardFactory::CARD_SCHEMA`.
*/
public function createCards( bool $preserveKeys = true ): array {
/** @var array<string|int,Card> */
return iterator_to_array( $this->lazyLoadCards( $preserveKeys ), $preserveKeys );
}
public function lazyLoadCards( bool $preserveKeys = true ): Generator {
foreach ( $this->content as $index => $args ) {
if ( $preserveKeys ) {
yield $index => $this->createCard( $index );
} else {
yield $this->createCard( $index );
}
}
}
/** @throws TypeError When $args passed does not match the `CardFactory::CARD_SCHEMA`. */
public function createCard( string|int|null $index = null ): Card {
$args = $index
? $this->content[ $index ]
: ( array_is_list( $this->content ) ? reset( $this->content ) : $this->content );
self::shutdownIfNonAssociative( $args );
try {
return $this->getCardInstance( $args )
->setName( $args['name'] )
->setAlias( $args['alias'] )
->setBreakpoint( ...$args['breakpoint'] )
->setCode( ...$args['code'] )
->setLength( $args['length'] )
->setIdRange( $args['idRange'] );
} catch ( TypeError | InvalidArgumentException $e ) {
$this->shutdownForInvalidSchema( $args, $index, $e );
}
}
private function resolvePayloadContent( mixed $data, string $type = '' ): void {
if ( $this->content ?? false ) {
return;
}
[ $content, $typeWithPath, $this->path ] = self::parseContentIfFile( $data );
if ( is_array( $content ) ) {
$this->content = $content;
return;
}
if ( $type ) {
$typeWithPath = $type;
}
self::shutdownForInvalidFile( $typeWithPath );
}
/** @param array<string,mixed> $args */
private function getCardInstance( array $args ): Card {
[ $type, $classname, $checkLuhn ] = $this->polyfillOptional( $args );
$classname = $classname ?: ( self::$defaultCardClass ?? '' );
return $classname && is_a( $classname, Card::class, allow_string: true )
? new $classname( $type, $checkLuhn )
: new CardType( $type, $checkLuhn );
}
/**
* @param array<string,mixed> $args
* @return array{0:string,1:string,2:bool}
*/
private function polyfillOptional( array $args ): array {
return array(
is_string( $card = ( $args['type'] ?? null ) ) ? $card : self::CREDIT_CARD,
is_string( $class = ( $args['classname'] ?? null ) ) ? $class : '',
is_bool( $luhn = ( $args['checkLuhn'] ?? null ) ) ? $luhn : true,
);
}
/** @return array{0:mixed,1:string,2:string} */
private static function parseContentIfFile( mixed $payload ): array {
if ( ! is_string( $payload ) || ! is_readable( $payload ) ) {
return array( $payload, 'file type', '' );
}
return match ( true ) {
default => array( '', 'file: ' . $payload, $payload ),
self::isFileType( $payload, 'json' ) => self::parseJsonContent( $payload ),
self::isFileType( $payload, 'php' ) => self::parsePhpContent( $payload )
};
}
private static function isFileType( string $file, string $ext ): bool {
return substr( $file, offset: - strlen( $ext ) ) === $ext;
}
/** @return array{0:mixed,1:string,2:string} */
private static function parsePhpContent( string $file ): array {
$content = require $file;
$content = is_callable( $content ) ? $content() : $content;
return array( $content, 'php file: ' . $file, $file );
}
/** @return array{0:mixed,1:string,2:string} */
private static function parseJsonContent( string $file ): mixed {
$type = 'JSON file: ' . $file;
$content = file_get_contents( $file );
if ( false === $content ) {
self::shutdownForInvalidFile( $type );
}
return array( json_decode( $content, associative: true ), $type, $file );
}
private static function shutdownIfNonAssociative( mixed $args ): void {
if ( is_array( $args ) && ! array_is_list( $args ) ) {
return;
}
$schema = '';
$isLast = array_key_last( self::CARD_SCHEMA );
foreach ( self::CARD_SCHEMA as $key => $type ) {
if ( str_ends_with( haystack: $key, needle: '?' ) ) {
continue;
}
$schema .= $key . ':' . $type . ( $isLast === $key ? '' : ', ' );
}
throw new TypeError(
sprintf(
'Invalid data provided for creating card. It must be an associative array with schema: array{%s}',
$schema
)
);
}
private static function shutdownForInvalidFile( string $typeWithPath ): never {
throw new TypeError(
sprintf( 'Invalid %s provided for creating cards. File must return an array data.', $typeWithPath )
);
}
/** @param mixed[] $args */
private function shutdownForInvalidSchema( array $args, string|int|null $index, Throwable $e ): never {
throw new TypeError(
previous: $e,
message: sprintf(
'Invalid Payment Card arguments given%1$s%2$s.%5$sGiven argument: %3$s%5$sError message: %4$s.',
/* %1 */ null !== $index ? ' for array key [#' . $index . ']' : '',
/* %2 */ $this->path ? ' in file "' . $this->path . '"' : '',
/* %3 */ json_encode( $args ),
/* %4 */ $e->getMessage(),
/* %5 */ PHP_EOL,
)
);
}
private static function shutdownForInvalidJsonKey( string $key ): never {
throw new TypeError( sprintf( 'Impossible to find Card instance from given JSON key: %s', $key ) );
}
}