-
Notifications
You must be signed in to change notification settings - Fork 174
Expand file tree
/
Copy pathGateways.php
More file actions
570 lines (496 loc) · 17 KB
/
Gateways.php
File metadata and controls
570 lines (496 loc) · 17 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
<?php
/**
* @link https://craftcms.com/
* @copyright Copyright (c) Pixel & Tonic, Inc.
* @license https://craftcms.github.io/license/
*/
namespace craft\commerce\services;
use Craft;
use craft\commerce\base\Gateway;
use craft\commerce\base\GatewayInterface;
use craft\commerce\base\SubscriptionGateway;
use craft\commerce\db\Table;
use craft\commerce\events\GatewayEvent;
use craft\commerce\gateways\Dummy;
use craft\commerce\gateways\Manual;
use craft\commerce\gateways\MissingGateway;
use craft\commerce\records\Gateway as GatewayRecord;
use craft\db\Query;
use craft\errors\DeprecationException;
use craft\errors\MissingComponentException;
use craft\events\ConfigEvent;
use craft\events\RegisterComponentTypesEvent;
use craft\helpers\ArrayHelper;
use craft\helpers\Component as ComponentHelper;
use craft\helpers\Db;
use craft\helpers\StringHelper;
use DateTime;
use Illuminate\Support\Collection;
use Throwable;
use yii\base\Component;
use yii\base\ErrorException;
use yii\base\Event;
use yii\base\Exception;
use yii\base\InvalidConfigException;
use yii\base\NotSupportedException;
use yii\web\ServerErrorHttpException;
/**
* Gateway service.
*
* @property GatewayInterface[] $allGateways all gateways
* @property GatewayInterface[] $allCustomerEnabledGateways all gateways enabled for the customer
* @property array $allSubscriptionGateways
* @property string[] $allGatewayTypes all registered gateway types
* @author Pixel & Tonic, Inc. <support@pixelandtonic.com>
* @since 2.0
*/
class Gateways extends Component
{
/**
* @event GatewayEvent The event that is triggered before a gateway is saved.
*
* ```php
* use craft\commerce\events\GatewayEvent;
* use craft\commerce\services\Gateways;
* use craft\commerce\models\Gateway;
* use yii\base\Event;
*
* Event::on(
* Gateways::class,
* Gateways::EVENT_BEFORE_SAVE_GATEWAY,
* function(GatewayEvent $event) {
* // @var Gateway $gateway
* $gateway = $event->gateway;
* // @var bool $isNew
* $isNew = $event->isNew;
*
* // ...
* }
* );
* ```
*/
public const EVENT_BEFORE_SAVE_GATEWAY = 'beforeSaveGateway';
/**
* @event GatewayEvent The event that is triggered after a gateway is saved.
*
* ```php
* use craft\commerce\events\GatewayEvent;
* use craft\commerce\services\Gateways;
* use craft\commerce\models\Gateway;
* use yii\base\Event;
*
* Event::on(
* Gateways::class,
* Gateways::EVENT_AFTER_SAVE_GATEWAY,
* function(GatewayEvent $event) {
* // @var Gateway $gateway
* $gateway = $event->gateway;
* // @var bool $isNew
* $isNew = $event->isNew;
*
* // ...
* }
* );
* ```
*/
public const EVENT_AFTER_SAVE_GATEWAY = 'afterSaveGateway';
/**
* @var array|null Gateway setting overrides
*/
private ?array $_overrides = null;
/**
* @var Collection<Gateway>|null All gateways
*/
private ?Collection $_allGateways = null;
/**
* @event RegisterComponentTypesEvent The event that is triggered for the registration of additional gateways.
*
* This example registers a custom gateway instance of the `MyGateway` class:
*
* ```php
* use craft\events\RegisterComponentTypesEvent;
* use craft\commerce\services\Purchasables;
* use yii\base\Event;
*
* Event::on(
* Gateways::class,
* Gateways::EVENT_REGISTER_GATEWAY_TYPES,
* function(RegisterComponentTypesEvent $event) {
* $event->types[] = MyGateway::class;
* }
* );
* ```
*/
public const EVENT_REGISTER_GATEWAY_TYPES = 'registerGatewayTypes';
public const CONFIG_GATEWAY_KEY = 'commerce.gateways';
/**
* Returns all registered gateway types.
*
* @return string[]
*/
public function getAllGatewayTypes(): array
{
$gatewayTypes = [
Dummy::class,
Manual::class,
];
$event = new RegisterComponentTypesEvent([
'types' => $gatewayTypes,
]);
$this->trigger(self::EVENT_REGISTER_GATEWAY_TYPES, $event);
return $event->types;
}
/**
* Returns all customer enabled gateways.
*
* @return Collection All gateways that are enabled for frontend
* @throws DeprecationException
* @throws InvalidConfigException
*/
public function getAllCustomerEnabledGateways(): Collection
{
return $this->getAllGateways()->filter(fn(GatewayInterface $gateway) => $gateway->getIsFrontendEnabled());
}
/**
* Returns all subscription gateways.
*
* @return Collection<GatewayInterface> All Subscription gateways
* @throws DeprecationException
* @throws InvalidConfigException
*/
public function getAllSubscriptionGateways(): Collection
{
return $this->getAllGateways()->where(fn(GatewayInterface $gateway) => $gateway instanceof SubscriptionGateway);
}
/**
* Returns all gateways
*
* @return Collection All gateways
* @throws DeprecationException
* @throws InvalidConfigException
*/
public function getAllGateways(): Collection
{
return $this->_getAllGateways()->where('isArchived', false);
}
/**
* @return array
* @throws DeprecationException
* @throws InvalidConfigException
* @sine 5.3.0
*/
public function getAllArchivedGateways(): array
{
return ArrayHelper::where($this->_getAllGateways(), 'isArchived', true);
}
/**
* Archives a gateway by its ID.
*
* @param int $id gateway ID
* @return bool Whether the archiving was successful or not
* @throws ErrorException
* @throws Exception
* @throws InvalidConfigException
* @throws NotSupportedException
* @throws ServerErrorHttpException
* @throws \yii\db\Exception
*/
public function archiveGatewayById(int $id): bool
{
/** @var Gateway $gateway */
$gateway = $this->getGatewayById($id);
$gateway->isArchived = true;
if (!$this->saveGateway($gateway)) {
return false;
}
// remove all payment sources for this gateway
// this will also remove them as the payment source for a cart
Craft::$app->getDb()->createCommand()
->delete(Table::PAYMENTSOURCES, ['gatewayId' => $id])
->execute();
// Clear this as the selected gateway from all active carts and orders
Craft::$app->getDb()->createCommand()
->update(Table::ORDERS,
[
'gatewayId' => null,
'paymentSourceId' => null,
],
[
'gatewayId' => $id,
], [], false)
->execute();
return true;
}
/**
* Returns a gateway by its ID.
*
* @param int $id
* @return Gateway|null The gateway or null if not found.
* @throws DeprecationException
* @throws InvalidConfigException
*/
public function getGatewayById(int $id): ?Gateway
{
return $this->_getAllGateways()->firstWhere('id', $id);
}
/**
* Returns a gateway by its handle.
*
* @param string $handle
* @return Gateway|null The gateway or null if not found.
* @throws DeprecationException
* @throws InvalidConfigException
*/
public function getGatewayByHandle(string $handle): ?Gateway
{
return $this->_getAllGateways()->firstWhere('handle', $handle);
}
/**
* Saves a gateway.
*
* @param Gateway $gateway The gateway to be saved.
* @param bool $runValidation Whether the gateway should be validated
* @return bool Whether the gateway was saved successfully or not.
* @throws Exception
* @throws InvalidConfigException
* @throws ErrorException
* @throws NotSupportedException
* @throws ServerErrorHttpException
*/
public function saveGateway(Gateway $gateway, bool $runValidation = true): bool
{
$isNewGateway = $gateway->getIsNew();
if ($this->hasEventHandlers(self::EVENT_BEFORE_SAVE_GATEWAY)) {
$this->trigger(self::EVENT_BEFORE_SAVE_GATEWAY, new GatewayEvent([
'gateway' => $gateway,
'isNew' => $isNewGateway,
]));
}
if ($runValidation && !$gateway->validate()) {
Craft::info('Gateway not saved due to validation error.', __METHOD__);
return false;
}
if ($isNewGateway) {
$gatewayUid = StringHelper::UUID();
} else {
$gatewayUid = $gateway->uid;
}
$existingGateway = $this->getGatewayByHandle($gateway->handle);
if ($existingGateway && (!$gateway->id || $gateway->id != $existingGateway->id)) {
$gateway->addError('handle', Craft::t('commerce', 'That handle is already in use.'));
return false;
}
$projectConfig = Craft::$app->getProjectConfig();
if ($gateway->isArchived) {
$configData = null;
} else {
$configData = $gateway->getConfig();
}
$configPath = self::CONFIG_GATEWAY_KEY . '.' . $gatewayUid;
$projectConfig->set($configPath, $configData);
if ($isNewGateway) {
$gateway->id = Db::idByUid(Table::GATEWAYS, $gatewayUid);
}
$this->_allGateways = null; // reset cache
return true;
}
/**
* Handle gateway change
*
* @throws Throwable if reasons
*/
public function handleChangedGateway(ConfigEvent $event): void
{
$gatewayUid = $event->tokenMatches[0];
$data = $event->newValue;
$transaction = Craft::$app->getDb()->beginTransaction();
try {
$gatewayRecord = $this->_getGatewayRecord($gatewayUid);
$isNewGateway = $gatewayRecord->getIsNewRecord();
$gatewayRecord->name = $data['name'];
$gatewayRecord->handle = $data['handle'];
$gatewayRecord->type = $data['type'];
$gatewayRecord->settings = $data['settings'] ?? null;
$gatewayRecord->sortOrder = $data['sortOrder'];
$gatewayRecord->paymentType = $data['paymentType'];
if ($data['isFrontendEnabled'] === null || is_bool($data['isFrontendEnabled'])) {
$data['isFrontendEnabled'] = $data['isFrontendEnabled'] ? '1' : '0';
}
$gatewayRecord->isFrontendEnabled = $data['isFrontendEnabled'];
$gatewayRecord->orderCondition = $data['orderCondition'] ?? null;
$gatewayRecord->isArchived = false;
$gatewayRecord->dateArchived = null;
$gatewayRecord->uid = $gatewayUid;
// Save the volume
$gatewayRecord->save(false);
$transaction->commit();
} catch (Throwable $e) {
$transaction->rollBack();
throw $e;
}
if ($this->hasEventHandlers(self::EVENT_AFTER_SAVE_GATEWAY)) {
$this->trigger(self::EVENT_AFTER_SAVE_GATEWAY, new GatewayEvent([
'gateway' => $this->getGatewayById($gatewayRecord->id),
'isNew' => $isNewGateway,
]));
}
}
/**
* Handle gateway being archived
*
* @throws Throwable if reasons
*/
public function handleArchivedGateway(ConfigEvent $event): void
{
$gatewayUid = $event->tokenMatches[0];
$transaction = Craft::$app->getDb()->beginTransaction();
try {
$gatewayRecord = $this->_getGatewayRecord($gatewayUid);
$gatewayRecord->isArchived = true;
$gatewayRecord->dateArchived = Db::prepareDateForDb(new DateTime());
// Save the volume
$gatewayRecord->save(false);
$transaction->commit();
} catch (Throwable $e) {
$transaction->rollBack();
throw $e;
}
}
/**
* Reorders gateways by ids.
*
* @param array $ids Array of gateways.
* @return bool Always true.
* @throws ErrorException
* @throws Exception
* @throws InvalidConfigException
* @throws NotSupportedException
* @throws ServerErrorHttpException
*/
public function reorderGateways(array $ids): bool
{
$projectConfig = Craft::$app->getProjectConfig();
$uidsByIds = Db::uidsByIds(Table::GATEWAYS, $ids);
foreach ($ids as $gatewayOrder => $gatewayId) {
if (!empty($uidsByIds[$gatewayId])) {
$gatewayUid = $uidsByIds[$gatewayId];
$projectConfig->set(self::CONFIG_GATEWAY_KEY . '.' . $gatewayUid . '.sortOrder', $gatewayOrder + 1);
}
}
$this->_allGateways = null; // reset cache
return true;
}
/**
* Creates a gateway with a given config
*
* @param string|array $config The gateway’s class name, or its config, with a `type` value and optionally a `settings` value
* @return Gateway The gateway
* @throws DeprecationException
* @throws InvalidConfigException
*/
public function createGateway(string|array $config): Gateway
{
if (is_string($config)) {
$config = ['type' => $config];
}
// Are they overriding any settings?
if (!empty($config['handle']) && ($override = $this->getGatewayOverrides($config['handle'])) !== null) {
// Save a reference to the original config in case the gateway type is missing
$originalConfig = $config;
// Apply the settings early so the overrides don't get overridden
$config = array_merge(ComponentHelper::mergeSettings($config), $override);
}
try {
if ($config['type'] == MissingGateway::class) {
throw new MissingComponentException('Missing Gateway Class.');
}
/** @var Gateway $gateway */
$gateway = ComponentHelper::createComponent($config, GatewayInterface::class);
} catch (MissingComponentException $e) {
$config['errorMessage'] = $e->getMessage();
$config['expectedType'] = $config['type'];
unset($config['type']);
$gateway = new MissingGateway($config);
}
return $gateway;
}
/**
* Returns any custom gateway settings form config file.
*
* @param string $handle The gateway handle
* @throws DeprecationException
* @deprecated in 3.3. Overriding gateway settings using the `commerce-gateways.php` file has been deprecated. Use the gateway’s config file instead.
*/
public function getGatewayOverrides(string $handle): ?array
{
if ($this->_overrides === null) {
$this->_overrides = Craft::$app->getConfig()->getConfigFromFile('commerce-gateways');
}
$overrides = $this->_overrides[$handle] ?? null;
if ($overrides != null) {
Craft::$app->getDeprecator()->log('craft.commerce.gateways.getGatewayOverrides()', 'Overriding gateway settings using the `commerce-gateways.php` file has been deprecated. Use the gateway’s config file instead.');
}
return $overrides;
}
/**
* Returns a Query object prepped for retrieving gateways.
*
* @return Query The query object.
*/
private function _createGatewayQuery(): Query
{
$query = (new Query())
->select([
'dateArchived',
'handle',
'id',
'isArchived',
'isFrontendEnabled',
'name',
'paymentType',
'settings',
'sortOrder',
'type',
'uid',
])
->orderBy(['sortOrder' => SORT_ASC])
->from([Table::GATEWAYS]);
// TODO: remove after next breakpoint
$db = Craft::$app->getDb();
if ($db->columnExists(Table::GATEWAYS, 'orderCondition')) {
$query->addSelect('orderCondition');
}
return $query;
}
/**
* Gets a gateway's record by uid.
*/
private function _getGatewayRecord(string $uid): GatewayRecord
{
if ($gateway = GatewayRecord::findOne(['uid' => $uid])) {
return $gateway;
}
return new GatewayRecord();
}
/**
* @return Collection<Gateway>
* @throws DeprecationException
* @throws InvalidConfigException
*/
private function _getAllGateways(): Collection
{
if ($this->_allGateways === null) {
$results = $this->_createGatewayQuery()
->all();
if ($this->_allGateways === null) {
$this->_allGateways = collect();
}
$gateways = [];
foreach ($results as $result) {
$gateways[] = $this->createGateway($result);
}
$this->_allGateways = collect($gateways)->keyBy('id');
}
return $this->_allGateways;
}
}