Repository navigation
Expand file tree
/
Copy pathCoreGatewayFactory.php
More file actions
677 lines (577 loc) · 30.8 KB
/
Copy pathCoreGatewayFactory.php
File metadata and controls
677 lines (577 loc) · 30.8 KB
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
<?php
namespace Payum\Core;
use Closure;
use DI\ContainerBuilder;
use Exception;
use Http\Adapter\Buzz\Client as HttpBuzzClient;
use Http\Adapter\Guzzle5\Client as HttpGuzzle5Client;
use Http\Adapter\Guzzle6\Client as HttpGuzzle6Client;
use Http\Adapter\Guzzle7\Client as HttpGuzzle7Client;
use Http\Client\Curl\Client as HttpCurlClient;
use Http\Client\HttpClient;
use Http\Client\Socket\Client as HttpSocketClient;
use Http\Discovery\Exception\NotFoundException;
use Http\Discovery\HttpClientDiscovery;
use Http\Discovery\MessageFactoryDiscovery;
use Http\Discovery\Psr17Factory;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;
use Http\Discovery\StreamFactoryDiscovery;
use Http\Message\MessageFactory;
use Http\Message\StreamFactory;
use LogicException;
use Money\Currencies;
use Money\Currencies\AggregateCurrencies;
use Money\Currencies\CryptoCurrencies;
use Money\Currencies\ISOCurrencies;
use Money\Formatter\DecimalMoneyFormatter;
use Money\MoneyFormatter;
use Money\MoneyParser;
use Money\Parser\DecimalMoneyParser;
use Payum\Core\Action\AuthorizePaymentAction;
use Payum\Core\Action\CapturePaymentAction;
use Payum\Core\Action\ExecuteSameRequestWithModelDetailsAction;
use Payum\Core\Action\GetCurrencyAction;
use Payum\Core\Action\GetHttpRequestAction;
use Payum\Core\Action\GetTokenAction;
use Payum\Core\Action\PayoutPayoutAction;
use Payum\Core\Action\PrependActionInterface;
use Payum\Core\Action\RenderTemplateAction;
use Payum\Core\Bridge\Httplug\HttplugClient;
use Payum\Core\Bridge\Spl\ArrayObject;
use Payum\Core\Bridge\Twig\TwigRenderer;
use Payum\Core\Bridge\Twig\TwigUtil;
use Payum\Core\Clock\SystemClock;
use Payum\Core\DI\ContainerConfiguration;
use Payum\Core\DI\CreatesGateway;
use Payum\Core\Event\NullEventDispatcher;
use Payum\Core\Extension\EndlessCycleDetectorExtension;
use Payum\Core\Extension\PrependExtensionInterface;
use Payum\Core\Gateway\DeclaresActions;
use Payum\Core\Gateway\GatewayInterface as PaymentGateway;
use Payum\Core\Handler\HandlerMap;
use Payum\Core\Idempotency\IdempotencyStoreInterface;
use Payum\Core\Idempotency\InMemoryIdempotencyStore;
use Payum\Core\Legacy\LegacyFactoryScope;
use Payum\Core\Legacy\NoTokenIssuer;
use Payum\Core\Legacy\Psr18HttpClient;
use Payum\Core\Middleware\EndlessCycleDetectorMiddleware;
use Payum\Core\Middleware\IdempotencyMiddleware;
use Payum\Core\Middleware\LegacyExtensionMiddleware;
use Payum\Core\Middleware\MiddlewareCollection;
use Payum\Core\Middleware\PersistStateMiddleware;
use Payum\Core\Middleware\RecordPaymentStatusMiddleware;
use Payum\Core\Middleware\TemplateRenderMiddleware;
use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\TokenIssuerInterface;
use Payum\Core\Template\RendererInterface;
use Psr\Clock\ClockInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Message\UriFactoryInterface;
use ReflectionFunction;
use ReflectionMethod;
use ReflectionNamedType;
use ReflectionType;
use Symfony\Component\HttpClient\HttplugClient as SymfonyHttplugClient;
use Twig\Environment;
use Twig\Loader\ChainLoader;
use function array_combine;
use function array_diff;
use function array_filter;
use function array_map;
use function array_merge;
use function class_exists;
use function func_get_args;
use function func_num_args;
use function in_array;
use function is_string;
use function str_starts_with;
use function trigger_deprecation;
class CoreGatewayFactory implements GatewayFactoryInterface, ContainerConfiguration, CreatesGateway, GatewayFactoryConfigInterface
{
private const ACTIONS = [
GetHttpRequestAction::class,
CapturePaymentAction::class,
AuthorizePaymentAction::class,
PayoutPayoutAction::class,
ExecuteSameRequestWithModelDetailsAction::class,
RenderTemplateAction::class,
GetCurrencyAction::class,
GetTokenAction::class,
];
private const EXTENSIONS = [
EndlessCycleDetectorExtension::class,
];
/**
* Core's own api entry, which every 1.x gateway gets: the http client an ApiAwareInterface action with
* that api class was handed in 1.x.
*/
private const CORE_API = 'payum.api.http_client';
private const BUILD_METHODS = ['buildClosures', 'buildActions', 'buildApis', 'buildExtensions'];
/**
* @var array<string, mixed>
*/
protected array $defaultConfig = [];
/**
* @var array<string, true>
*/
private static array $reportedOverrides = [];
/**
* @param array<string, mixed> $defaultConfig
*/
public function __construct(array $defaultConfig = [])
{
$this->defaultConfig = $defaultConfig;
}
/**
* @param array<string, mixed> $config
*
* @throws ContainerExceptionInterface|NotFoundExceptionInterface|Exception
*/
public function create(array $config = []): Gateway
{
if (! LegacyFactoryScope::isActive()) {
trigger_deprecation('payum/core', '2.0.0', 'The %s is deprecated and will be removed in 3.0. Implement the %s interface instead.', __METHOD__, ContainerConfiguration::class);
}
$this->reportOverriddenBuildMethods();
return LegacyFactoryScope::run(fn (): Gateway => $this->build($config));
}
/**
* @param array<string, mixed> $config
*
* @return array<string, mixed>
*/
public function createConfig(array $config = []): array
{
if (! LegacyFactoryScope::isActive()) {
trigger_deprecation('payum/core', '2.0.0', 'The %s is deprecated and will be removed in 3.0. Implement the %s interface instead.', __METHOD__, ContainerConfiguration::class);
}
$containerConfig = $this->configureContainer();
// The caller's entries come first as well as winning: actions and extensions register in key
// order, and the first action that supports a request is the one that runs.
$result = $config + $containerConfig;
if (isset($config['payum.paths'])) {
$result['payum.paths'] = array_merge(
$containerConfig['payum.paths'] ?? [],
$config['payum.paths']
);
}
return $result;
}
public function configureContainer(): array
{
// The builder's entries, such as the token and storage extensions, register ahead of core's own.
return $this->defaultConfig + array_merge(
[
// A 1.x gateway that type-hints an HTTPlug factory gets one as long as it installs
// php-http/message-factory and an implementation itself; core no longer depends on
// either. Without an implementation these fall back to PSR-17, because buildClosures()
// resolves them for every gateway, including the ones that never read them.
'httplug.message_factory' => static function (): object {
if (! LegacyFactoryScope::isActive()) {
trigger_deprecation('payum/core', '2.0.0', 'The "httplug.message_factory" config key is deprecated and will be removed in 3.0. Use "payum.http_message_factory", a %s, instead.', RequestFactoryInterface::class);
}
if (interface_exists(MessageFactory::class)) {
try {
return MessageFactoryDiscovery::find();
} catch (NotFoundException) {
}
}
return Psr17FactoryDiscovery::findRequestFactory();
},
'httplug.stream_factory' => static function (): object {
if (! LegacyFactoryScope::isActive()) {
trigger_deprecation('payum/core', '2.0.0', 'The "httplug.stream_factory" config key is deprecated and will be removed in 3.0. Use "payum.http_stream_factory", a %s, instead.', StreamFactoryInterface::class);
}
if (interface_exists(StreamFactory::class)) {
try {
return StreamFactoryDiscovery::find();
} catch (NotFoundException) {
}
}
return Psr17FactoryDiscovery::findStreamFactory();
},
'httplug.client' => static function (ArrayObject $config) {
if (! LegacyFactoryScope::isActive()) {
trigger_deprecation('payum/core', '2.0.0', 'The "httplug.client" config key is deprecated and will be removed in 3.0. Use "payum.http_client", a %s, instead.', ClientInterface::class);
}
if (class_exists(HttpClientDiscovery::class)) {
try {
return HttpClientDiscovery::find();
} catch (NotFoundException) {
// symfony/http-client 7+ claims php-http/client-implementation but its HttplugClient
// implements PSR-18 only, which HTTPlug discovery does not accept.
return Psr18ClientDiscovery::find();
}
}
if (class_exists(HttpGuzzle7Client::class)) {
return new HttpGuzzle7Client();
}
if (class_exists(HttpGuzzle6Client::class)) {
return new HttpGuzzle6Client();
}
if (class_exists(HttpGuzzle5Client::class)) {
return new HttpGuzzle5Client();
}
if (class_exists(SymfonyHttplugClient::class)) {
return new SymfonyHttplugClient();
}
if (class_exists(HttpSocketClient::class)) {
return new HttpSocketClient();
}
if (class_exists(HttpCurlClient::class)) {
return new HttpCurlClient();
}
if (class_exists(HttpBuzzClient::class)) {
return new HttpBuzzClient();
}
throw new LogicException('The httplug.client could not be guessed. Install one of the following packages: php-http/guzzle7-adapter, php-http/guzzle7-adapter. You can also overwrite the config option with your implementation.');
},
// PSR-18/17 services - lazily discover if not provided
ClientInterface::class => Psr18ClientDiscovery::find(...),
StreamFactoryInterface::class => Psr17FactoryDiscovery::findStreamFactory(...),
RequestFactoryInterface::class => Psr17FactoryDiscovery::findRequestFactory(...),
ResponseFactoryInterface::class => Psr17FactoryDiscovery::findResponseFactory(...),
UriFactoryInterface::class => Psr17FactoryDiscovery::findUriFactory(...),
ServerRequestFactoryInterface::class => Psr17FactoryDiscovery::findServerRequestFactory(...),
// Every time read goes through this, so that expiry and staleness can be tested at a
// fixed instant. The application registers its own through PayumBuilder, which wins
// over this one.
ClockInterface::class => static fn (): ClockInterface => new SystemClock(),
// Where the payment lifecycle is announced. A no-op by default, so core dispatches
// unconditionally; the application registers its own -- Symfony's, Laravel's, anything
// PSR-14 -- and starts hearing about it.
EventDispatcherInterface::class => static fn (): EventDispatcherInterface => new NullEventDispatcher(),
// Middleware wrapping command execution. The collection is what decides the order;
// PayumBuilder replaces it with the defaults plus whatever the application and the
// gateway registered.
MiddlewareCollection::class => self::defaultMiddleware(...),
EndlessCycleDetectorMiddleware::class => static fn (): EndlessCycleDetectorMiddleware => new EndlessCycleDetectorMiddleware(),
LegacyExtensionMiddleware::class => static fn (): LegacyExtensionMiddleware => new LegacyExtensionMiddleware(),
IdempotencyStoreInterface::class => static fn (ContainerInterface $c): IdempotencyStoreInterface => new InMemoryIdempotencyStore(
$c->get(ClockInterface::class),
),
IdempotencyMiddleware::class => static fn (ContainerInterface $c): IdempotencyMiddleware => new IdempotencyMiddleware(
$c->get(IdempotencyStoreInterface::class),
$c->get(ClockInterface::class),
$c->has(StorageRegistryInterface::class) ? $c->get(StorageRegistryInterface::class) : null,
),
RecordPaymentStatusMiddleware::class => static fn (ContainerInterface $c): RecordPaymentStatusMiddleware => new RecordPaymentStatusMiddleware(
$c->get(EventDispatcherInterface::class),
),
PersistStateMiddleware::class => static fn (ContainerInterface $c): PersistStateMiddleware => new PersistStateMiddleware(
$c->has(StorageRegistryInterface::class) ? $c->get(StorageRegistryInterface::class) : null,
),
TemplateRenderMiddleware::class => static fn (): TemplateRenderMiddleware => new TemplateRenderMiddleware(),
// PayumBuilder registers the real issuer over this one. A gateway built without it still
// runs handlers that never create a token.
TokenIssuerInterface::class => static fn (): TokenIssuerInterface => new NoTokenIssuer(),
// Built from every superglobal, with the headers and the raw php://input body: a PSP signs
// the raw bytes, usually in a header, and $_POST is empty for the JSON payloads most of
// them send. An application with a framework should register its own request instead,
// through PayumBuilder::addGlobalService(), which overrides this.
ServerRequestInterface::class => static function (ContainerInterface $c): ServerRequestInterface {
$factory = new Psr17Factory(
serverRequestFactory: $c->get(ServerRequestFactoryInterface::class),
streamFactory: $c->get(StreamFactoryInterface::class),
);
// The URI stays REQUEST_URI alone: 1.x gateways read it from GetHttpRequest::$uri,
// and the PlainPhp action they were written against gave them exactly that.
return $factory->createServerRequestFromGlobals()
->withUri($factory->createUri($_SERVER['REQUEST_URI'] ?? '/'), true);
},
// Legacy Payum service names - delegate to PSR interfaces
'payum.http_client' => static fn (ContainerInterface $c): HttplugClient => new HttplugClient($c->get(ClientInterface::class)),
'payum.http_stream_factory' => static fn (ContainerInterface $c): StreamFactoryInterface => $c->get(StreamFactoryInterface::class),
'payum.http_message_factory' => static fn (ContainerInterface $c): RequestFactoryInterface => $c->get(RequestFactoryInterface::class),
'payum.template.layout' => '@PayumCore/layout.html.twig',
'twig.env' => static fn () => new Environment(new ChainLoader()),
// The application registers its own through PayumBuilder, which wins over this one: a
// renderer is shared by every gateway, so this default only covers a gateway built
// straight from the factory.
RendererInterface::class => static fn (ContainerInterface $c): RendererInterface => new TwigRenderer(
$c->get('twig.env'),
$c->get('payum.template.layout'),
self::composeTemplatePaths($c),
),
// What every money in this gateway is measured against. ISO 4217 first, so a code that
// means one thing there cannot be shadowed; crypto after it, which is what makes an
// eight- or eighteen-decimal amount come out right. Register your own to add a currency
// neither lists.
Currencies::class => static fn (): Currencies => new AggregateCurrencies([new ISOCurrencies(), new CryptoCurrencies()]),
MoneyFormatter::class => static fn (ContainerInterface $c): MoneyFormatter => new DecimalMoneyFormatter($c->get(Currencies::class)),
MoneyParser::class => static fn (ContainerInterface $c): MoneyParser => new DecimalMoneyParser($c->get(Currencies::class)),
'payum.default_options' => [],
'payum.required_options' => [],
// Backwards compatibility arrays for deprecated build* methods
'payum.prepend_actions' => [],
'payum.prepend_apis' => [],
'payum.prepend_extensions' => [],
'payum.api.http_client' => static fn (ContainerInterface $c) => $c->get('payum.http_client'),
// Token storage - should be provided externally
// 'payum.security.token_storage' => null,
'payum.paths' => self::corePaths(),
// Additional aliases
Environment::class => static fn (ContainerInterface $c) => $c->get('twig.env'),
HttpClient::class => static fn (ContainerInterface $c) => $c->get('payum.http_client'),
// BC: Deprecated action entries (used by deprecated buildActions method)
'payum.action.get_http_request' => static fn (ContainerInterface $c) => $c->get(GetHttpRequestAction::class),
'payum.action.capture_payment' => static fn () => new CapturePaymentAction(),
'payum.action.authorize_payment' => static fn () => new AuthorizePaymentAction(),
'payum.action.payout_payout' => static fn () => new PayoutPayoutAction(),
'payum.action.execute_same_request_with_model_details' => static fn () => new ExecuteSameRequestWithModelDetailsAction(),
'payum.action.render_template' => static fn (ContainerInterface $c) => $c->get(RenderTemplateAction::class),
'payum.action.get_currency' => static fn (ContainerInterface $c) => $c->get(GetCurrencyAction::class),
'payum.action.get_token' => static fn (ContainerInterface $c) => $c->has('payum.security.token_storage')
? new GetTokenAction($c->get('payum.security.token_storage'))
: null,
// BC: Deprecated extension entries (used by deprecated buildExtensions method)
'payum.extension.endless_cycle_detector' => static fn () => new EndlessCycleDetectorExtension(),
// The 1.x information requests, answered from the services 2.0 injects. A gateway still
// dispatching GetHttpRequest or RenderTemplate needs nothing registered by hand.
GetHttpRequestAction::class => static fn (ContainerInterface $c) => new GetHttpRequestAction($c->get(ServerRequestInterface::class)),
RenderTemplateAction::class => static fn (ContainerInterface $c) => new RenderTemplateAction($c->get(RendererInterface::class)),
GetCurrencyAction::class => static fn (ContainerInterface $c) => new GetCurrencyAction($c->get(Currencies::class)),
// GetTokenAction is conditionally added in createGateway() if token storage is available
GetTokenAction::class => static fn (ContainerInterface $c) => $c->has('payum.security.token_storage')
? new GetTokenAction($c->get('payum.security.token_storage'))
: throw new LogicException('Token storage must be configured to use GetTokenAction'),
],
$this->defaultConfig,
);
}
/**
* @throws ContainerExceptionInterface|NotFoundExceptionInterface
*/
/**
* The middleware every gateway gets, before anything the application or the gateway adds.
*/
public static function defaultMiddleware(): MiddlewareCollection
{
return (new MiddlewareCollection())
->with(TemplateRenderMiddleware::class)
->with(EndlessCycleDetectorMiddleware::class)
->with(IdempotencyMiddleware::class)
->with(LegacyExtensionMiddleware::class)
->with(PersistStateMiddleware::class)
->with(RecordPaymentStatusMiddleware::class)
;
}
public function createGateway(ContainerInterface $container): Gateway
{
// create() hands over a gateway it has already given core's own actions and extensions, from
// their payum.action.* and payum.extension.* entries. Only what a subclass adds is still missing.
$built = 2 === func_num_args() && func_get_args()[1] instanceof Gateway;
$gateway = $built ? func_get_args()[1] : new Gateway();
$actions = $built ? array_diff($this->getActions(), self::ACTIONS) : $this->getActions();
$extensions = $built ? array_diff($this->getExtensions(), self::EXTENSIONS) : $this->getExtensions();
$gateway->setContainer($container);
$declaredActions = [];
if ($container->has(PaymentGateway::class)) {
$paymentGateway = $container->get(PaymentGateway::class);
$gateway->setHandlerMap(HandlerMap::fromHandlers($paymentGateway->handlers()));
// A gateway that has finished moving gets nothing else: no actions, no extensions, no Twig
// environment it will never render with. One still holding actions says so, and then needs
// core's own alongside them, since an action dispatching GetHttpRequest expects an answer.
if (! $paymentGateway instanceof DeclaresActions) {
return $gateway;
}
$declaredActions = $paymentGateway->actions();
}
if ($container->has('twig.env')) {
TwigUtil::registerPaths($container->get('twig.env'), self::composeTemplatePaths($container));
}
foreach ([...$actions, ...$declaredActions] as $action) {
// Skip GetTokenAction if token storage is not configured
if (GetTokenAction::class === $action && ! $container->has('payum.security.token_storage')) {
continue;
}
$action = $container->get($action);
$gateway->addAction($action, $action instanceof PrependActionInterface);
}
foreach ($extensions as $extension) {
if (is_string($extension)) {
$extension = $container->get($extension);
}
$gateway->addExtension($extension, $extension instanceof PrependExtensionInterface);
}
return $gateway;
}
public function getActions(): array
{
return self::ACTIONS;
}
public function getExtensions(): array
{
return self::EXTENSIONS;
}
/**
* @deprecated since 2.0.0, will be removed in 3.0. Implement
* Payum\Core\DI\ContainerConfiguration instead.
*/
protected function buildClosures(ArrayObject $config): void
{
// Helper to check if closure expects ArrayObject
$canInvokeWithArrayObject = static function ($value): bool {
if (! $value instanceof Closure) {
return false;
}
$reflection = new ReflectionFunction($value);
if (0 === $reflection->getNumberOfParameters()) {
return true;
}
$params = $reflection->getParameters();
$firstParam = $params[0];
return ! $firstParam->getType() instanceof ReflectionType || ($firstParam->getType() instanceof ReflectionNamedType && ArrayObject::class === $firstParam->getType()->getName());
};
/** @var ContainerInterface $container */
$container = $config[ContainerInterface::class]();
foreach ($config as $name => $value) {
if (GetTokenAction::class === $name && ! $container->has('payum.security.token_storage')) {
continue;
}
if (is_callable($value) && ! (is_string($value) && function_exists('\\' . $value))) {
if ($canInvokeWithArrayObject($value)) {
$config[$name] = $value($config);
} else {
$config[$name] = $container->get($name);
}
}
}
}
/**
* @deprecated since 2.0.0, will be removed in 3.0. Implement
* Payum\Core\DI\ContainerConfiguration instead.
*/
protected function buildActions(Gateway $gateway, ArrayObject $config): void
{
foreach ($config as $name => $value) {
if (str_starts_with($name, 'payum.action') && null !== $value) {
$prepend = in_array($name, $config['payum.prepend_actions'], true) || $value instanceof PrependActionInterface;
$gateway->addAction($value, $prepend);
}
}
}
/**
* @deprecated since 2.0.0, will be removed in 3.0. Implement
* Payum\Core\DI\ContainerConfiguration instead.
*/
protected function buildApis(Gateway $gateway, ArrayObject $config): void
{
foreach ($config as $name => $value) {
if (str_starts_with($name, 'payum.api')) {
if (self::CORE_API !== $name) {
trigger_deprecation('payum/core', '2.0.0', 'The "%s" config key is deprecated and will be removed in 3.0, along with every payum.api.* key. Take the api as a constructor argument on the action instead, and let the container inject it.', $name);
}
$prepend = in_array($name, $config['payum.prepend_apis'], true);
$gateway->addApi($value, $prepend);
}
}
}
/**
* @deprecated since 2.0.0, will be removed in 3.0. Implement
* Payum\Core\DI\ContainerConfiguration instead.
*/
protected function buildExtensions(Gateway $gateway, ArrayObject $config): void
{
foreach ($config as $name => $value) {
if (str_starts_with($name, 'payum.extension')) {
$prepend = in_array($name, $config['payum.prepend_extensions'], true) || $value instanceof PrependExtensionInterface;
$gateway->addExtension($value, $prepend);
}
}
}
/**
* @param array<string, mixed> $config
*/
private function build(array $config): Gateway
{
if (($config['payum.http_client'] ?? null) instanceof HttpClientInterface && ! $config['payum.http_client'] instanceof ClientInterface) {
$config['payum.http_client'] = new Psr18HttpClient($config['payum.http_client']);
}
$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions($config);
$containerBuilder->addDefinitions($this->configureContainer());
// What the caller set wins over core's defaults, as it did in 1.x: a gateway's payum.paths or
// payum.template.layout reaches the renderer. Closures are left to buildClosures(), since a 1.x
// closure takes the config array, which the container cannot pass.
$containerBuilder->addDefinitions(array_filter($config, static fn ($value): bool => ! $value instanceof Closure));
$containerBuilder->addDefinitions([
ArrayObject::class => static function (ContainerInterface $container) {
if (! LegacyFactoryScope::isActive()) {
trigger_deprecation('payum/core', '2.0.0', 'The %s service is deprecated and will be removed in 3.0. Use the %s service instead.', ArrayObject::class, ContainerInterface::class);
}
return new class($container) extends ArrayObject {
private ContainerInterface $container;
public function __construct(ContainerInterface $container)
{
parent::__construct();
$this->container = $container;
}
public function offsetGet($key): mixed
{
return $this->container->get($key);
}
public function offsetExists($key): bool
{
return $this->container->has($key);
}
};
},
]);
$container = $containerBuilder->build();
$entries = $container->getKnownEntryNames();
$configArray = ArrayObject::ensureArrayObject($config);
$configArray->defaults(array_combine(
$entries,
array_map(static fn (string $name) => static fn () => $container->get($name), $entries)
));
$gateway = new Gateway();
$this->buildClosures($configArray);
$this->buildActions($gateway, $configArray);
$this->buildApis($gateway, $configArray);
$this->buildExtensions($gateway, $configArray);
return $this->createGateway($container, $gateway);
}
/**
* The build methods are deprecated for whoever overrides them. Core calling its own is not something
* a caller can change, so a subclass is reported for each one it overrides, once.
*/
private function reportOverriddenBuildMethods(): void
{
foreach (self::BUILD_METHODS as $method) {
$declaringClass = (new ReflectionMethod($this, $method))->getDeclaringClass()->getName();
$key = $declaringClass . '::' . $method;
if (self::class === $declaringClass || isset(self::$reportedOverrides[$key])) {
continue;
}
self::$reportedOverrides[$key] = true;
trigger_deprecation('payum/core', '2.0.0', 'Overriding %s::%s() in %s is deprecated and will be removed in 3.0. Implement the %s interface instead.', self::class, $method, $declaringClass, ContainerConfiguration::class);
}
}
/**
* @return array<string, string>
*/
private static function corePaths(): array
{
return [
'PayumCore' => __DIR__ . '/Resources/views',
];
}
/**
* @return array<string, string>
*/
private static function composeTemplatePaths(ContainerInterface $c): array
{
return array_merge(self::corePaths(), (array) $c->get('payum.paths'));
}
}