Repository navigation
Expand file tree
/
Copy pathPayumBuilder.php
More file actions
1129 lines (933 loc) · 42.1 KB
/
Copy pathPayumBuilder.php
File metadata and controls
1129 lines (933 loc) · 42.1 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
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Payum\Core;
use DI\Container;
use DI\ContainerBuilder;
use DI\FactoryInterface;
use Exception;
use Http\Discovery\Psr17FactoryDiscovery;
use Http\Discovery\Psr18ClientDiscovery;
use Invoker\InvokerInterface;
use LogicException;
use Omnipay\Omnipay;
use Payum\AuthorizeNet\Aim\AuthorizeNetAimGatewayFactory;
use Payum\Be2Bill\Be2BillDirectGatewayFactory;
use Payum\Be2Bill\Be2BillOffsiteGatewayFactory;
use Payum\Core\Bridge\PlainPhp\Security\HttpRequestVerifier;
use Payum\Core\Bridge\PlainPhp\Security\TokenFactory;
use Payum\Core\Bridge\Twig\TwigRenderer;
use Payum\Core\Clock\SystemClock;
use Payum\Core\Config\GatewayConfig;
use Payum\Core\DI\ContainerConfiguration;
use Payum\Core\DI\CreatesGateway;
use Payum\Core\DI\FallbackContainer;
use Payum\Core\DI\ListableContainerInterface;
use Payum\Core\Event\NullEventDispatcher;
use Payum\Core\Exception\InvalidArgumentException;
use Payum\Core\Exception\LogicException as PayumLogicException;
use Payum\Core\Extension\GenericTokenFactoryExtension;
use Payum\Core\Extension\StorageExtension;
use Payum\Core\Gateway\DeclaresActions;
use Payum\Core\Gateway\DeclaresMiddleware;
use Payum\Core\Gateway\DeclaresTemplates;
use Payum\Core\Gateway\GatewayInterface as PaymentGateway;
use Payum\Core\Handler\HandlerMap;
use Payum\Core\Legacy\GenericTokenFactoryIssuer;
use Payum\Core\Legacy\LegacyFactoryScope;
use Payum\Core\Middleware\MiddlewareCollection;
use Payum\Core\Middleware\MiddlewareInterface;
use Payum\Core\Model\ArrayObject;
use Payum\Core\Model\GatewayConfigInterface;
use Payum\Core\Model\Payment;
use Payum\Core\Model\Payout;
use Payum\Core\Model\Token;
use Payum\Core\Registry\DynamicRegistry;
use Payum\Core\Registry\FallbackRegistry;
use Payum\Core\Registry\RegistryInterface;
use Payum\Core\Registry\SimpleRegistry;
use Payum\Core\Registry\StorageRegistryInterface;
use Payum\Core\Security\GenericTokenFactory;
use Payum\Core\Security\GenericTokenFactoryInterface;
use Payum\Core\Security\HttpRequestVerifierInterface;
use Payum\Core\Security\TokenFactoryInterface;
use Payum\Core\Security\TokenInterface;
use Payum\Core\Security\TokenIssuerInterface;
use Payum\Core\Storage\FilesystemStorage;
use Payum\Core\Storage\StorageInterface;
use Payum\Core\Template\RendererInterface;
use Payum\Klarna\Checkout\KlarnaCheckoutGatewayFactory;
use Payum\Klarna\Invoice\KlarnaInvoiceGatewayFactory;
use Payum\Offline\OfflineGatewayFactory;
use Payum\OmnipayBridge\OmnipayGatewayFactory;
use Payum\OmnipayV3Bridge\OmnipayGatewayFactory as OmnipayV3GatewayFactory;
use Payum\Payex\PayexGatewayFactory;
use Payum\Paypal\ExpressCheckout\Nvp\PaypalExpressCheckoutGatewayFactory;
use Payum\Paypal\Masspay\Nvp\PaypalMasspayGatewayFactory;
use Payum\Paypal\ProCheckout\Nvp\PaypalProCheckoutGatewayFactory;
use Payum\Paypal\ProHosted\Nvp\PaypalProHostedGatewayFactory;
use Payum\Paypal\Rest\PaypalRestGatewayFactory;
use Payum\Sofort\SofortGatewayFactory;
use Payum\Stripe\StripeCheckoutGatewayFactory;
use Payum\Stripe\StripeJsGatewayFactory;
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\StreamFactoryInterface;
use Twig\Environment;
use Twig\Loader\ChainLoader;
use function array_merge;
use function array_replace;
use function array_reverse;
use function DI\autowire;
use function DI\get;
use function in_array;
use function is_a;
use function is_dir;
use function strtolower;
use function sys_get_temp_dir;
use function trigger_deprecation;
class PayumBuilder
{
/**
* @var HttpRequestVerifierInterface|callable|null
*/
protected $httpRequestVerifier;
/**
* @var TokenFactoryInterface|callable|null
*/
protected $tokenFactory;
/**
* @var GenericTokenFactoryInterface|callable|null
*/
protected $genericTokenFactory;
/**
* @var string[]
*/
protected array $genericTokenFactoryPaths = [];
/**
* @var ?StorageInterface<TokenInterface>
*/
protected ?StorageInterface $tokenStorage = null;
/**
* @var GatewayFactoryInterface|callable|null
*/
protected $coreGatewayFactory;
/**
* @var GatewayConfigInterface[]
*/
protected array $coreGatewayFactoryConfig = [];
/**
* @var ?StorageInterface<GatewayConfigInterface>
*/
protected ?StorageInterface $gatewayConfigStorage = null;
/**
* @var GatewayInterface[]|GatewayConfig[]
*/
protected array $gateways = [];
/**
* @var array<string, mixed>
*/
protected array $gatewayConfigs = [];
/**
* @var GatewayFactoryInterface[]|callable[]
*/
protected array $gatewayFactories = [];
/**
* @var array<string, mixed>
*/
protected array $gatewayFactoryConfigs = [];
/**
* @var StorageInterface<object>[]
*/
protected array $storages = [];
/**
* @var ?RegistryInterface<object>
*/
protected ?RegistryInterface $mainRegistry = null;
protected MiddlewareCollection $middleware;
protected ?ContainerInterface $globalContainer = null;
/**
* @var array<string, mixed>
*/
protected array $globalDefinitions = [];
protected string $layout = '@PayumCore/layout.html.twig';
public function __construct()
{
$this->middleware = new MiddlewareCollection();
}
/**
* Adds a FilesystemStorage for the token and for each shipped model that has no storage yet.
*/
public function addDefaultStorages(): static
{
if (! $this->tokenStorage) {
/** @var StorageInterface<TokenInterface> $tokenStorage */
$tokenStorage = new FilesystemStorage(sys_get_temp_dir(), Token::class, 'hash');
$this->setTokenStorage($tokenStorage);
}
$defaults = [
Payment::class => 'number',
ArrayObject::class => 'payum_id',
Payout::class => 'payum_id',
];
foreach ($defaults as $modelClass => $idProperty) {
if (! isset($this->storages[$modelClass])) {
$this->addStorage($modelClass, new FilesystemStorage(sys_get_temp_dir(), $modelClass, $idProperty));
}
}
return $this;
}
/**
* @param class-string $modelClass
* @param StorageInterface<object> $storage
*/
public function addStorage(string $modelClass, StorageInterface $storage): static
{
$this->storages[$modelClass] = $storage;
return $this;
}
/**
* @deprecated since 2.0.0, will be removed in 3.0. Use Payum\Core\PayumBuilder::registerGateway()
* instead, passing the gateway's own Payum\Core\Config\GatewayConfig.
*
* @param GatewayInterface|array<string, mixed> $gateway
*/
public function addGateway(string $name, GatewayInterface | array $gateway): static
{
trigger_deprecation(
'payum/core',
'2.0.0',
'%s is deprecated and will be removed in 3.0. Use %s::registerGateway() instead, passing the gateway\'s own %s.',
__METHOD__,
self::class,
GatewayConfig::class,
);
if ($gateway instanceof GatewayInterface) {
$this->gateways[$name] = $gateway;
} else {
$currentConfig = $this->gatewayConfigs[$name] ?? [];
$currentConfig = array_replace_recursive($currentConfig, $gateway);
if (empty($currentConfig['factory'])) {
throw new InvalidArgumentException('Gateway config must have factory set in it and it must not be empty.');
}
$this->gatewayConfigs[$name] = $currentConfig;
}
return $this;
}
public function addGatewayFactory(string $name, callable | GatewayFactoryInterface $gatewayFactory): static
{
$this->gatewayFactories[$name] = $gatewayFactory;
return $this;
}
/**
* @param array<string, mixed> $config
*/
public function addGatewayFactoryConfig(string $name, array $config): static
{
$currentConfig = $this->gatewayFactoryConfigs[$name] ?? [];
$this->gatewayFactoryConfigs[$name] = array_replace_recursive($currentConfig, $config);
return $this;
}
public function setHttpRequestVerifier(HttpRequestVerifierInterface | callable | null $httpRequestVerifier = null): static
{
$this->httpRequestVerifier = $httpRequestVerifier;
return $this;
}
public function setTokenFactory(callable | TokenFactoryInterface | null $tokenFactory = null): static
{
$this->tokenFactory = $tokenFactory;
return $this;
}
public function setGenericTokenFactory(callable | GenericTokenFactoryInterface | null $tokenFactory = null): static
{
$this->genericTokenFactory = $tokenFactory;
return $this;
}
/**
* @param string[] $paths
*/
public function setGenericTokenFactoryPaths(array $paths = []): static
{
$this->genericTokenFactoryPaths = $paths;
return $this;
}
/**
* @param ?StorageInterface<TokenInterface> $tokenStorage
*/
public function setTokenStorage(?StorageInterface $tokenStorage = null): static
{
$this->tokenStorage = $tokenStorage;
return $this;
}
public function setCoreGatewayFactory(callable | GatewayFactoryInterface | null $coreGatewayFactory = null): static
{
$this->coreGatewayFactory = $coreGatewayFactory;
return $this;
}
/**
* @param array<string, mixed> $config
* @return $this
*/
public function setCoreGatewayFactoryConfig(array $config = []): static
{
$this->coreGatewayFactoryConfig = $config;
return $this;
}
/**
* @param array<string, mixed> $config
*/
public function addCoreGatewayFactoryConfig(array $config): static
{
$currentConfig = $this->coreGatewayFactoryConfig ?: [];
$this->coreGatewayFactoryConfig = array_replace_recursive($currentConfig, $config);
return $this;
}
/**
* @param StorageInterface<GatewayConfigInterface>|null $gatewayConfigStorage
*/
public function setGatewayConfigStorage(?StorageInterface $gatewayConfigStorage = null): static
{
$this->gatewayConfigStorage = $gatewayConfigStorage;
return $this;
}
/**
* @param RegistryInterface<object>|null $mainRegistry
*/
public function setMainRegistry(?RegistryInterface $mainRegistry = null): static
{
$this->mainRegistry = $mainRegistry;
return $this;
}
/**
* Add a global service definition that will be available to all gateways.
* This allows sharing services (like HTTP clients, loggers) across all gateway instances.
*/
/**
* Registers middleware that wraps every command, on every gateway.
*
* This is where most middleware belongs: logging, locking and idempotency are not specific to any one
* gateway. A package shipping middleware registers it here too, or contributes the container id and
* lets the integration add it.
*
* @param class-string<MiddlewareInterface>|MiddlewareInterface $middleware a container id or an instance
* @param int|null $priority higher runs further out. Defaults to what the middleware declares through
* Payum\Core\Middleware\HasPriority, or 0
*/
public function addMiddleware(string | MiddlewareInterface $middleware, ?int $priority = null): static
{
$this->middleware = $this->middleware->with($middleware, $priority);
return $this;
}
public function addGlobalService(string $id, mixed $service): static
{
$this->globalDefinitions[$id] = $service;
return $this;
}
public function setLayout(string $layout): static
{
$this->layout = $layout;
return $this;
}
/**
* Set a pre-built global container (for framework integration).
* When set, this container will be used instead of building one from global definitions.
*/
public function setGlobalContainer(ContainerInterface $container): static
{
$this->globalContainer = $container;
return $this;
}
/**
* @return Payum<StorageRegistryInterface<StorageInterface<TokenInterface>>>
* @throws ContainerExceptionInterface
* @throws NotFoundExceptionInterface
* @throws Exception
*/
public function getPayum(): Payum
{
$globalContainer = $this->buildGlobalContainer();
$genericTokenFactory = $globalContainer->get(GenericTokenFactoryInterface::class);
$httpRequestVerifier = $globalContainer->get(HttpRequestVerifierInterface::class);
$tokenStorage = $this->tokenStorage ?? $globalContainer->get('payum.security.token_storage');
/** @var CoreGatewayFactory $coreGatewayFactory */
$coreGatewayFactory = $this->buildCoreGatewayFactory(array_replace_recursive([
'payum.extension.token_factory' => new GenericTokenFactoryExtension($genericTokenFactory),
GenericTokenFactoryInterface::class => $genericTokenFactory,
TokenIssuerInterface::class => $globalContainer->get(TokenIssuerInterface::class),
'payum.security.token_storage' => $tokenStorage,
], $this->coreGatewayFactoryConfig));
$gatewayFactories = array_replace(
$this->buildGatewayFactories($coreGatewayFactory),
$this->buildOmnipayGatewayFactories($coreGatewayFactory),
$this->buildOmnipayV3GatewayFactories($coreGatewayFactory),
$this->buildAddedGatewayFactories($coreGatewayFactory)
);
$gatewayFactories['core'] = $coreGatewayFactory;
$gateways = [];
$applicationActions = array_values(array_unique(array_filter(
[
...array_keys($this->coreGatewayFactoryConfig),
...array_keys($this->globalDefinitions),
...$this->getKnownEntryNames($globalContainer),
],
static fn (string $id): bool => str_starts_with($id, 'payum.action.'),
)));
foreach ($this->gateways as $name => $config) {
if (! $config instanceof GatewayConfig) {
continue;
}
if ([] !== $applicationActions) {
trigger_deprecation(
'payum/core',
'2.0.0',
'Gateway "%s" is built from handlers and ignores %s. A payum.action.* entry only reaches a 1.x gateway, and is removed in 3.0. Write what a Convert action added onto the payment\'s details before executing the command, or decorate the gateway\'s handler in configureContainer().',
$name,
implode(', ', $applicationActions),
);
}
$gatewayClass = $config->getGatewayClass();
$gateway = new $gatewayClass();
$gatewayDefinitions = $gateway instanceof ContainerConfiguration ? $gateway->configureContainer() : null;
if (null !== $gatewayDefinitions && array_key_exists(RendererInterface::class, $gatewayDefinitions)) {
throw new PayumLogicException(sprintf(
'%s declares %s. The renderer is registered by the application, not by a gateway: a gateway replacing it breaks every other gateway\'s templates. Register your own directory under the gateway\'s template namespace instead.',
$gatewayClass,
RendererInterface::class,
));
}
$containerBuilder = new ContainerBuilder();
// Core defaults first, then the services shared by every gateway, then the handlers, then what
// the gateway declares for itself. Last wins.
$containerBuilder->addDefinitions($coreGatewayFactory->configureContainer());
$containerBuilder->addDefinitions($this->buildSharedDefinitions($globalContainer));
$handlerDefinitions = [];
// The interface resolves to the handler's own entry, so a gateway that builds or decorates a
// handler in configureContainer() is what runs.
foreach (HandlerMap::fromHandlers($gateway->handlers())->bindings() as $interface => $handlerClass) {
$handlerDefinitions[$handlerClass] = autowire($handlerClass);
$handlerDefinitions[$interface] = get($handlerClass);
}
$containerBuilder->addDefinitions($handlerDefinitions);
if (null !== $gatewayDefinitions) {
$containerBuilder->addDefinitions($gatewayDefinitions);
}
// Core defaults first, then what the application registered, then the gateway's own, so a
// gateway's middleware runs innermost on equal priority.
$middleware = CoreGatewayFactory::defaultMiddleware()->merge($this->middleware);
if ($gateway instanceof DeclaresMiddleware) {
foreach ($gateway->middleware() as $gatewayMiddleware) {
$middleware = $middleware->with($gatewayMiddleware);
}
}
$containerBuilder->addDefinitions([
MiddlewareCollection::class => $middleware,
]);
$containerBuilder->addDefinitions([
$config::class => $config,
GatewayConfig::class => $config,
$gatewayClass => $gateway,
PaymentGateway::class => $gateway,
]);
$gateways[$name] = $coreGatewayFactory->createGateway(
new FallbackContainer($containerBuilder->build(), $globalContainer)
);
if ($gateway instanceof DeclaresActions) {
$this->addLegacyExtensions($gateways[$name], $genericTokenFactory);
}
unset($this->gateways[$name]);
}
// Whatever is left in $this->gateways is a legacy instance rather than a config -- the loop above
// unset each config as it built it. Merged unconditionally: these have to reach the registry even
// when no gateway was registered by config.
$gateways = array_merge($this->gateways, $gateways);
if ($this->gatewayConfigs) {
$factoryRegistry = $this->buildRegistry([], $this->storages, $gatewayFactories);
foreach ($this->gatewayConfigs as $name => $gatewayConfig) {
$gatewayFactory = $factoryRegistry->getGatewayFactory($gatewayConfig['factory']);
unset($gatewayConfig['factory']);
if ($gatewayFactory instanceof ContainerConfiguration) {
$containerBuilder = new ContainerBuilder();
// The gateway factory defaults come first, ...
$containerBuilder->addDefinitions($coreGatewayFactory->configureContainer());
$containerBuilder->addDefinitions($gatewayFactory->configureContainer());
// ... then the services shared by every gateway, so that they win over the factory
// defaults, ...
$containerBuilder->addDefinitions($this->buildSharedDefinitions($globalContainer));
// ... and finally the gateway config, which overrides both.
$containerBuilder->addDefinitions($gatewayConfig);
// Anything the gateway container does not know about is looked up globally, so that
// services of a container which cannot list its entries stay reachable too.
$container = new FallbackContainer($containerBuilder->build(), $globalContainer);
// Assembly is uniform unless a factory says otherwise, which is why CreatesGateway is
// separate from ContainerConfiguration: a gateway declares services without having to
// know how a Gateway is built.
$gateways[$name] = $gatewayFactory instanceof CreatesGateway
? $gatewayFactory->createGateway($container)
: $coreGatewayFactory->createGateway($container);
} else {
trigger_deprecation(
'payum/core',
'2.0.0',
'%s is a 1.x gateway factory, which is deprecated and will not be supported in 3.0. It needs to implement %s.',
$gatewayFactory::class,
ContainerConfiguration::class,
);
$gateways[$name] = LegacyFactoryScope::run(static fn () => $gatewayFactory->create($gatewayConfig));
}
}
}
// Every assembled gateway learns the name it is registered under, so anything reporting a
// problem can say which gateway it happened on when the gateway is picked at runtime.
foreach ($gateways as $gatewayName => $gateway) {
if ($gateway instanceof Gateway) {
$gateway->setName($gatewayName);
}
}
$registry = $this->buildRegistry($gateways, $this->storages, $gatewayFactories);
return new Payum(
$registry,
$httpRequestVerifier,
$genericTokenFactory,
$tokenStorage,
$globalContainer->get(RendererInterface::class),
$globalContainer->get(TokenIssuerInterface::class),
);
}
/**
* Registers a gateway from its typed config.
*
* The config names its descriptor, and the descriptor names everything else -- handlers, metadata,
* the services it needs. Nothing about the gateway is spelled out here, which is the point: adding a
* capability is adding a handler class, not editing the application's wiring.
*
* Container assembly and the command => handler map are built later, in getPayum().
*/
public function registerGateway(string $name, GatewayConfig $config): self
{
// That this is a gateway is guaranteed by getGatewayClass()'s return type; re-checking would be
// dead code. Instantiated bare, which every gateway must support -- see the note on
// Payum\Core\Gateway\GatewayInterface about why metadata has to be readable without credentials.
$gatewayClass = $config->getGatewayClass();
$gateway = new $gatewayClass();
// This, on the other hand, is the one mistake the type system cannot see -- registering, say, a
// Paypal config against the Stripe gateway. Both sides only promise "a GatewayConfig".
if (! is_a($config, $gateway->configClass())) {
throw new LogicException(sprintf(
'%s is configured by %s, but %s was given.',
$gatewayClass,
$gateway->configClass(),
$config::class,
));
}
$this->gateways[$name] = $config;
return $this;
}
/**
* Build the global container with services shared across all gateways.
* This includes HTTP clients, token storage, token factories, and storage extensions.
*
* A container set with setGlobalContainer() is put in front of it, so that an application only has to
* declare the services it actually wants to provide itself and keeps Payum's defaults for the rest.
*
* @throws Exception
*/
protected function buildGlobalContainer(): ContainerInterface
{
$tokenStorage = $this->resolveTokenStorage();
/** @var StorageRegistryInterface<StorageInterface<TokenInterface>> $storageRegistry */
$storageRegistry = $this->buildRegistry([], $this->storages);
$paths = array_replace([
'capture' => 'capture.php',
'notify' => 'notify.php',
'authorize' => 'authorize.php',
'refund' => 'refund.php',
'payout' => 'payout.php',
'done' => 'done.php',
], $this->genericTokenFactoryPaths);
$presetContainer = $this->globalContainer;
$namespaces = $this->composeTemplateNamespaces();
$builder = new ContainerBuilder();
$builder->addDefinitions([
'payum.security.token_storage' => $tokenStorage,
// Payum's own token factory, unless the application brought its own. Resolving it here rather
// than only in the fallback keeps the generic factory below built on top of the right one.
TokenFactoryInterface::class => function () use ($presetContainer, $tokenStorage, $storageRegistry) {
if ($presetContainer?->has(TokenFactoryInterface::class)) {
return $presetContainer->get(TokenFactoryInterface::class);
}
return $this->buildTokenFactory($tokenStorage, $storageRegistry);
},
GenericTokenFactoryInterface::class => fn (ContainerInterface $c): GenericTokenFactoryInterface => $this->buildGenericTokenFactory($c->get(TokenFactoryInterface::class), $paths),
// The generic factory is looked up through the application's container first, the same way the
// token factory is, so a generic factory provided there backs the issuer too.
TokenIssuerInterface::class => static fn (ContainerInterface $c): TokenIssuerInterface => GenericTokenFactoryIssuer::wrap(
$presetContainer?->has(GenericTokenFactoryInterface::class)
? $presetContainer->get(GenericTokenFactoryInterface::class)
: $c->get(GenericTokenFactoryInterface::class)
),
HttpRequestVerifierInterface::class => fn (): HttpRequestVerifierInterface => $this->buildHttpRequestVerifier($tokenStorage),
// Storages only. A command carrying just a token needs this to load the payment its token
// points at, and building it without gateways keeps it clear of the registry below.
StorageRegistryInterface::class => $storageRegistry,
ClientInterface::class => Psr18ClientDiscovery::find(...),
StreamFactoryInterface::class => Psr17FactoryDiscovery::findStreamFactory(...),
RequestFactoryInterface::class => Psr17FactoryDiscovery::findRequestFactory(...),
// Shared, so that freezing time with addGlobalService() freezes it for every gateway at
// once rather than for whichever one happened to be asked.
ClockInterface::class => static fn (): ClockInterface => new SystemClock(),
// Shared for the same reason: one listener registered once hears about every gateway. A
// no-op until the application registers its own.
EventDispatcherInterface::class => static fn (): EventDispatcherInterface => new NullEventDispatcher(),
RendererInterface::class => fn (ContainerInterface $c): RendererInterface => new TwigRenderer(
$this->resolveTwigEnvironment($c),
$this->layout,
array_replace([
'PayumCore' => [__DIR__ . '/Resources/views'],
], $namespaces),
),
]);
foreach ($this->storages as $modelClass => $storage) {
$builder->addDefinitions([
$this->getStorageExtensionId($modelClass) => new StorageExtension($storage),
]);
}
$builder->addDefinitions($this->globalDefinitions);
$container = $builder->build();
if ($this->globalContainer) {
$container = new FallbackContainer($this->globalContainer, $container);
}
return $container;
}
/**
* The token storage in effect: the one set on the builder, else the one the application's container
* provides, else Payum's default storages.
*
* @return StorageInterface<TokenInterface>
*/
protected function resolveTokenStorage(): StorageInterface
{
if (! $this->tokenStorage && $this->globalContainer?->has('payum.security.token_storage')) {
/** @var StorageInterface<TokenInterface> $tokenStorage */
$tokenStorage = $this->globalContainer->get('payum.security.token_storage');
return $tokenStorage;
}
if (! $this->tokenStorage) {
$this->addDefaultStorages();
}
return $this->tokenStorage;
}
/**
* Definitions delegating to the global container, so that every gateway resolves the very same
* instance of a shared service.
*
* @return array<string, callable>
*/
protected function buildSharedDefinitions(ContainerInterface $globalContainer): array
{
$ids = [
'payum.security.token_storage',
HttpRequestVerifierInterface::class,
GenericTokenFactoryInterface::class,
TokenIssuerInterface::class,
TokenFactoryInterface::class,
StorageRegistryInterface::class,
ClientInterface::class,
StreamFactoryInterface::class,
RequestFactoryInterface::class,
ClockInterface::class,
EventDispatcherInterface::class,
];
foreach (array_keys($this->storages) as $modelClass) {
$ids[] = $this->getStorageExtensionId($modelClass);
}
// Everything registered with addGlobalService() is shared as well.
$ids = array_merge($ids, array_keys($this->globalDefinitions));
// Plus the rest of what the global container is able to report.
$ids = array_merge($ids, $this->getKnownEntryNames($globalContainer));
$definitions = [];
foreach (array_unique($ids) as $id) {
$definitions[$id] = static fn () => $globalContainer->get($id);
}
return $definitions;
}
/**
* The ids a container can report, if any. The container's own entries are left out, so that a gateway
* keeps being injected with its own container rather than the global one.
*
* @return list<string>
*/
protected function getKnownEntryNames(ContainerInterface $container): array
{
$names = [];
if ($container instanceof ListableContainerInterface || $container instanceof Container) {
$names = $container->getKnownEntryNames();
}
return array_values(array_diff($names, [
ContainerInterface::class,
Container::class,
FactoryInterface::class,
InvokerInterface::class,
]));
}
/**
* @param class-string $modelClass
*/
protected function getStorageExtensionId(string $modelClass): string
{
return 'payum.extension.storage_' . strtolower(str_replace('\\', '_', $modelClass));
}
/**
* @param StorageInterface<TokenInterface> $tokenStorage
* @param StorageRegistryInterface<StorageInterface<TokenInterface>> $storageRegistry
*/
protected function buildTokenFactory(StorageInterface $tokenStorage, StorageRegistryInterface $storageRegistry): TokenFactoryInterface
{
$tokenFactory = $this->tokenFactory;
if (is_callable($tokenFactory)) {
$tokenFactory = $tokenFactory($tokenStorage, $storageRegistry);
if (! $tokenFactory instanceof TokenFactoryInterface) {
throw new LogicException('Builder returned invalid instance');
}
}
return $tokenFactory ?: new TokenFactory($tokenStorage, $storageRegistry);
}
/**
* @param string[] $paths
*/
protected function buildGenericTokenFactory(TokenFactoryInterface $tokenFactory, array $paths): GenericTokenFactoryInterface
{
$genericTokenFactory = $this->genericTokenFactory;
if (is_callable($genericTokenFactory)) {
$genericTokenFactory = $genericTokenFactory($tokenFactory, $paths);
if (! $genericTokenFactory instanceof GenericTokenFactoryInterface) {
throw new LogicException('Builder returned invalid instance');
}
}
return $genericTokenFactory ?: new GenericTokenFactory($tokenFactory, $paths);
}
/**
* @param array<string, GatewayInterface> $gateways
* @param array<string, StorageInterface<object>> $storages
* @return RegistryInterface<StorageRegistryInterface<StorageInterface<TokenInterface>>>
*/
protected function buildRegistry(array $gateways = [], array $storages = [], array $gatewayFactories = []): RegistryInterface
{
$registry = new SimpleRegistry($gateways, $storages, $gatewayFactories);
$registry->setAddStorageExtensions(false);
if ($this->gatewayConfigStorage) {
$dynamicRegistry = new DynamicRegistry($this->gatewayConfigStorage, $registry);
$dynamicRegistry->setBackwardCompatibility(false);
$registry = new FallbackRegistry($dynamicRegistry, $registry);
}
if ($this->mainRegistry) {
$registry = new FallbackRegistry($this->mainRegistry, $registry);
}
/** @var RegistryInterface<StorageRegistryInterface<StorageInterface<TokenInterface>>> $registry */
return $registry;
}
/**
* @return GatewayFactoryInterface[]
*/
protected function buildGatewayFactories(GatewayFactoryInterface $coreGatewayFactory): array
{
$map = [
'paypal_express_checkout' => PaypalExpressCheckoutGatewayFactory::class,
'paypal_pro_checkout' => PaypalProCheckoutGatewayFactory::class,
'paypal_pro_hosted' => PaypalProHostedGatewayFactory::class,
'paypal_masspay' => PaypalMasspayGatewayFactory::class,
'paypal_rest' => PaypalRestGatewayFactory::class,
'authorize_net_aim' => AuthorizeNetAimGatewayFactory::class,
'be2bill_direct' => Be2BillDirectGatewayFactory::class,
'be2bill_offsite' => Be2BillOffsiteGatewayFactory::class,
'klarna_checkout' => KlarnaCheckoutGatewayFactory::class,
'klarna_invoice' => KlarnaInvoiceGatewayFactory::class,
'offline' => OfflineGatewayFactory::class,
'payex' => PayexGatewayFactory::class,
'stripe_checkout' => StripeCheckoutGatewayFactory::class,
'stripe_js' => StripeJsGatewayFactory::class,
'sofort' => SofortGatewayFactory::class,
];
$gatewayFactories = [];
foreach ($map as $name => $factoryClass) {
if (class_exists($factoryClass)) {
$gatewayFactories[$name] = new $factoryClass(
$this->gatewayFactoryConfigs[$name] ?? [],
$coreGatewayFactory
);
}
}
return $gatewayFactories;
}
/**
* @return GatewayFactoryInterface[]
*/
protected function buildAddedGatewayFactories(GatewayFactoryInterface $coreGatewayFactory): array
{
$gatewayFactories = [];
foreach ($this->gatewayFactories as $name => $factory) {
if (is_callable($factory)) {
$config = $this->gatewayFactoryConfigs[$name] ?? [];
$factory = $factory($config, $coreGatewayFactory);
}
$gatewayFactories[$name] = $factory;
}
return $gatewayFactories;
}
/**
* @deprecated since 2.0.0, will be removed in 3.0 along with the Omnipay v2 bridge. Install
* payum/omnipay-v3-bridge, whose factories are registered by
* {@see self::buildOmnipayV3GatewayFactories()}.
*
* @return array<string, object>
*/
protected function buildOmnipayGatewayFactories(GatewayFactoryInterface $coreGatewayFactory): array
{
$gatewayFactories = [];
if (! class_exists(Omnipay::class) || ! class_exists(OmnipayGatewayFactory::class)) {
return $gatewayFactories;
}
$factory = Omnipay::getFactory();
$gatewayFactories['omnipay'] = new OmnipayGatewayFactory('', $factory, [], $coreGatewayFactory);
$gatewayFactories['omnipay_direct'] = new OmnipayGatewayFactory('', $factory, [], $coreGatewayFactory);
$gatewayFactories['omnipay_offsite'] = new OmnipayGatewayFactory('', $factory, [], $coreGatewayFactory);
if (method_exists($factory, 'getSupportedGateways')) {
foreach ($factory->getSupportedGateways() as $type) {
// omnipay throws exception on these gateways https://github.com/thephpleague/omnipay/issues/312
// skip them for now
if (in_array($type, ['Buckaroo', 'Alipay Bank', 'AliPay Dual Func', 'Alipay Express', 'Alipay Mobile Express', 'Alipay Secured', 'Alipay Wap Express', 'Cybersource', 'DataCash', 'Ecopayz', 'Neteller', 'Pacnet', 'PaymentSense', 'Realex Remote', 'SecPay (PayPoint.net)', 'Sisow', 'Skrill', 'YandexMoney', 'YandexMoneyIndividual'])) {
continue;
}
$gatewayFactories[strtolower('omnipay_' . $type)] = new OmnipayGatewayFactory($type, $factory, [], $coreGatewayFactory);
}
}
return $gatewayFactories;
}
/**
* @return GatewayFactoryInterface[]
*/
protected function buildOmnipayV3GatewayFactories(GatewayFactoryInterface $coreGatewayFactory): array
{
$gatewayFactories = [];
if (! class_exists(Omnipay::class) || ! class_exists(OmnipayV3GatewayFactory::class)) {
return $gatewayFactories;
}
$factory = Omnipay::getFactory();
$gatewayFactories['omnipay'] = new OmnipayV3GatewayFactory($factory, [], $coreGatewayFactory);
return $gatewayFactories;
}
/**
* @param StorageInterface<TokenInterface> $tokenStorage
*/
private function buildHttpRequestVerifier(StorageInterface $tokenStorage): HttpRequestVerifierInterface
{
$httpRequestVerifier = $this->httpRequestVerifier;
if (is_callable($httpRequestVerifier)) {
$httpRequestVerifier = $httpRequestVerifier($tokenStorage);
if (! $httpRequestVerifier instanceof HttpRequestVerifierInterface) {
throw new LogicException('Builder returned invalid instance');