Passed
Push — master ( 74775e...beeae9 )
by Aimeos
04:42
created

Base::setData()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 9
c 0
b 0
f 0
dl 0
loc 18
rs 9.9666
cc 3
nc 3
nop 3
1
<?php
2
3
/**
4
 * @license LGPLv3, https://opensource.org/licenses/LGPL-3.0
5
 * @copyright Metaways Infosystems GmbH, 2011
6
 * @copyright Aimeos (aimeos.org), 2015-2022
7
 * @package MShop
8
 * @subpackage Service
9
 */
10
11
12
namespace Aimeos\MShop\Service\Provider;
13
14
15
/**
16
 * Abstract class for all service provider implementations with some default methods.
17
 *
18
 * @package MShop
19
 * @subpackage Service
20
 */
21
abstract class Base
22
	implements Iface, \Aimeos\Macro\Iface
23
{
24
	use \Aimeos\Macro\Macroable;
25
26
	private $object;
27
	private $context;
28
	private $serviceItem;
29
	private $beGlobalConfig;
30
31
32
	/**
33
	 * Initializes the service provider object.
34
	 *
35
	 * @param \Aimeos\MShop\ContextIface $context Context object with required objects
36
	 * @param \Aimeos\MShop\Service\Item\Iface $serviceItem Service item with configuration for the provider
37
	 */
38
	public function __construct( \Aimeos\MShop\ContextIface $context, \Aimeos\MShop\Service\Item\Iface $serviceItem )
39
	{
40
		$this->context = $context;
41
		$this->serviceItem = $serviceItem;
42
	}
43
44
45
	/**
46
	 * Returns the price when using the provider.
47
	 * Usually, this is the lowest price that is available in the service item but can also be a calculated based on
48
	 * the basket content, e.g. 2% of the value as transaction cost.
49
	 *
50
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $basket Basket object
51
	 * @param array $options Selected options by customer from frontend
52
	 * @return \Aimeos\MShop\Price\Item\Iface Price item containing the price, shipping, rebate
53
	 */
54
	public function calcPrice( \Aimeos\MShop\Order\Item\Base\Iface $basket, array $options = [] ) : \Aimeos\MShop\Price\Item\Iface
55
	{
56
		$manager = \Aimeos\MShop::create( $this->context, 'price' );
57
		$prices = $this->serviceItem->getRefItems( 'price', 'default', 'default' );
58
59
		return $prices->isEmpty() ? $manager->create() : $manager->getLowestPrice( $prices, 1 );
60
	}
61
62
63
	/**
64
	 * Checks the backend configuration attributes for validity.
65
	 *
66
	 * @param array $attributes Attributes added by the shop owner in the administraton interface
67
	 * @return array An array with the attribute keys as key and an error message as values for all attributes that are
68
	 * 	known by the provider but aren't valid resp. null for attributes whose values are OK
69
	 */
70
	public function checkConfigBE( array $attributes ) : array
71
	{
72
		return [];
73
	}
74
75
76
	/**
77
	 * Checks the frontend configuration attributes for validity.
78
	 *
79
	 * @param array $attributes Attributes entered by the customer during the checkout process
80
	 * @return array An array with the attribute keys as key and an error message as values for all attributes that are
81
	 * 	known by the provider but aren't valid resp. null for attributes whose values are OK
82
	 */
83
	public function checkConfigFE( array $attributes ) : array
84
	{
85
		return [];
86
	}
87
88
89
	/**
90
	 * Returns the configuration attribute definitions of the provider to generate a list of available fields and
91
	 * rules for the value of each field in the administration interface.
92
	 *
93
	 * @return array List of attribute definitions implementing \Aimeos\Base\Critera\Attribute\Iface
94
	 */
95
	public function getConfigBE() : array
96
	{
97
		return [];
98
	}
99
100
101
	/**
102
	 * Returns the configuration attribute definitions of the provider to generate a list of available fields and
103
	 * rules for the value of each field in the frontend.
104
	 *
105
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $basket Basket object
106
	 * @return array List of attribute definitions implementing \Aimeos\Base\Critera\Attribute\Iface
107
	 */
108
	public function getConfigFE( \Aimeos\MShop\Order\Item\Base\Iface $basket ) : array
109
	{
110
		return [];
111
	}
112
113
114
	/**
115
	 * Returns the service item which also includes the configuration for the service provider.
116
	 *
117
	 * @return \Aimeos\MShop\Service\Item\Iface Service item
118
	 */
119
	public function getServiceItem() : \Aimeos\MShop\Service\Item\Iface
120
	{
121
		return $this->serviceItem;
122
	}
123
124
125
	/**
126
	 * Injects additional global configuration for the backend.
127
	 *
128
	 * It's used for adding additional backend configuration from the application
129
	 * like the URLs to redirect to.
130
	 *
131
	 * Supported redirect URLs are:
132
	 * - payment.url-success
133
	 * - payment.url-failure
134
	 * - payment.url-cancel
135
	 * - payment.url-update
136
	 *
137
	 * @param array $config Associative list of config keys and their value
138
	 * @return \Aimeos\MShop\Service\Provider\Iface Provider object for chaining method calls
139
	 */
140
	public function injectGlobalConfigBE( array $config ) : \Aimeos\MShop\Service\Provider\Iface
141
	{
142
		$this->beGlobalConfig = $config;
143
		return $this;
144
	}
145
146
147
	/**
148
	 * Checks if payment provider can be used based on the basket content.
149
	 * Checks for country, currency, address, RMS, etc. -> in separate decorators
150
	 *
151
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $basket Basket object
152
	 * @return bool True if payment provider can be used, false if not
153
	 */
154
	public function isAvailable( \Aimeos\MShop\Order\Item\Base\Iface $basket ) : bool
155
	{
156
		return true;
157
	}
158
159
160
	/**
161
	 * Checks what features the payment provider implements.
162
	 *
163
	 * @param int $what Constant from abstract class
164
	 * @return bool True if feature is available in the payment provider, false if not
165
	 */
166
	public function isImplemented( int $what ) : bool
167
	{
168
		return false;
169
	}
170
171
172
	/**
173
	 * Queries for status updates for the given order if supported.
174
	 *
175
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order invoice object
176
	 * @return \Aimeos\MShop\Order\Item\Iface Updated order item object
177
	 */
178
	public function query( \Aimeos\MShop\Order\Item\Iface $order ) : \Aimeos\MShop\Order\Item\Iface
179
	{
180
		$msg = $this->context->translate( 'mshop', 'Method "%1$s" for provider not available' );
181
		throw new \Aimeos\MShop\Service\Exception( sprintf( $msg, 'query' ) );
182
	}
183
184
185
	/**
186
	 * Injects the outer object into the decorator stack
187
	 *
188
	 * @param \Aimeos\MShop\Service\Provider\Iface $object First object of the decorator stack
189
	 * @return \Aimeos\MShop\Service\Provider\Iface Service object for chaining method calls
190
	 */
191
	public function setObject( \Aimeos\MShop\Service\Provider\Iface $object ) : \Aimeos\MShop\Service\Provider\Iface
192
	{
193
		$this->object = $object;
194
		return $this;
195
	}
196
197
198
	/**
199
	 * Looks for new update files and updates the orders for which status updates were received.
200
	 * If batch processing of files isn't supported, this method can be empty.
201
	 *
202
	 * @return bool True if the update was successful, false if async updates are not supported
203
	 * @throws \Aimeos\MShop\Service\Exception If updating one of the orders failed
204
	 */
205
	public function updateAsync() : bool
206
	{
207
		return false;
208
	}
209
210
211
	/**
212
	 * Updates the order status sent by payment gateway notifications
213
	 *
214
	 * @param \Psr\Http\Message\ServerRequestInterface $request Request object
215
	 * @param \Psr\Http\Message\ResponseInterface $response Response object
216
	 * @return \Psr\Http\Message\ResponseInterface Response object
217
	 */
218
	public function updatePush( \Psr\Http\Message\ServerRequestInterface $request,
219
		\Psr\Http\Message\ResponseInterface $response ) : \Psr\Http\Message\ResponseInterface
220
	{
221
		return $response->withStatus( 501, 'Not implemented' );
222
	}
223
224
225
	/**
226
	 * Updates the orders for whose status updates have been received by the confirmation page
227
	 *
228
	 * @param \Psr\Http\Message\ServerRequestInterface $request Request object with parameters and request body
229
	 * @param \Aimeos\MShop\Order\Item\Iface $order Order item that should be updated
230
	 * @return \Aimeos\MShop\Order\Item\Iface Updated order item
231
	 * @throws \Aimeos\MShop\Service\Exception If updating the orders failed
232
	 */
233
	public function updateSync( \Psr\Http\Message\ServerRequestInterface $request,
234
		\Aimeos\MShop\Order\Item\Iface $order ) : \Aimeos\MShop\Order\Item\Iface
235
	{
236
		return $order;
237
	}
238
239
240
	/**
241
	 * Checks required fields and the types of the given data map
242
	 *
243
	 * @param array $criteria Multi-dimensional associative list of criteria configuration
244
	 * @param array $map Values to check agains the criteria
245
	 * @return array An array with the attribute keys as key and an error message as values for all attributes that are
246
	 * 	known by the provider but aren't valid resp. null for attributes whose values are OK
247
	 */
248
	protected function checkConfig( array $criteria, array $map ) : array
249
	{
250
		$helper = new \Aimeos\MShop\Common\Helper\Config\Standard( $this->getConfigItems( $criteria ) );
251
		return $helper->check( $map );
252
	}
253
254
255
	/**
256
	 * Returns the context item.
257
	 *
258
	 * @return \Aimeos\MShop\ContextIface Context item
259
	 */
260
	protected function context() : \Aimeos\MShop\ContextIface
261
	{
262
		return $this->context;
263
	}
264
265
266
	/**
267
	 * Returns the service related data from the customer account if available
268
	 *
269
	 * @param string $customerId Unique customer ID the service token belongs to
270
	 * @param string $key Key of the value that should be returned
271
	 * @return array|string|null Service data or null if none is available
272
	 */
273
	protected function data( string $customerId, string $key )
274
	{
275
		if( $customerId )
276
		{
277
			$item = \Aimeos\MShop::create( $this->context, 'customer' )->get( $customerId, ['service'] );
278
279
			if( $listItem = $item->getListItem( 'service', 'default', $this->getServiceItem()->getId() ) ) {
280
				return $listItem->getConfigValue( $key );
281
			}
282
		}
283
284
		return null;
285
	}
286
287
288
	/**
289
	 * Returns the calculated amount of the price item
290
	 *
291
	 * @param \Aimeos\MShop\Price\Item\Iface $price Price item
292
	 * @param bool $costs Include costs per item
293
	 * @param bool $tax Include tax
294
	 * @param int $precision Number for decimal digits
295
	 * @return string Formatted money amount
296
	 */
297
	protected function getAmount( \Aimeos\MShop\Price\Item\Iface $price, bool $costs = true, bool $tax = true,
298
		int $precision = null ) : string
299
	{
300
		$amount = $price->getValue();
301
302
		if( $costs === true ) {
303
			$amount += $price->getCosts();
304
		}
305
306
		if( $tax === true && $price->getTaxFlag() === false )
307
		{
308
			$tmp = clone $price;
309
310
			if( $costs === false )
311
			{
312
				$tmp->clear();
313
				$tmp->setValue( $price->getValue() );
314
				$tmp->setTaxRate( $price->getTaxRate() );
315
				$tmp->setQuantity( $price->getQuantity() );
316
			}
317
318
			$amount += $tmp->getTaxValue();
319
		}
320
321
		return number_format( $amount, $precision !== null ? $precision : $price->getPrecision(), '.', '' );
322
	}
323
324
325
	/**
326
	 * Returns the order service matching the given code from the basket
327
	 *
328
	 * @param \Aimeos\MShop\Order\Item\Base\Iface $basket Basket object
329
	 * @param string $type Service type constant from \Aimeos\MShop\Order\Item\Service\Base
330
	 * @param string $code Code of the service item that should be returned
331
	 * @return \Aimeos\MShop\Order\Item\Base\Service\Iface Order service item
332
	 * @throws \Aimeos\MShop\Order\Exception If no service for the given type and code is found
333
	 */
334
	protected function getBasketService( \Aimeos\MShop\Order\Item\Base\Iface $basket, string $type,
335
		string $code ) : \Aimeos\MShop\Order\Item\Base\Service\Iface
336
	{
337
		$msg = $this->context->translate( 'mshop', 'Service not available' );
338
339
		return map( $basket->getService( $type ) )->find( function( $service ) use ( $code ) {
340
				return $service->getCode() === $code;
341
		}, new \Aimeos\MShop\Service\Exception( $msg ) );
342
	}
343
344
345
	/**
346
	 * Returns the criteria attribute items for the backend configuration
347
	 *
348
	 * @return \Aimeos\Base\Criteria\Attribute\Iface[] List of criteria attribute items
349
	 */
350
	protected function getConfigItems( array $configList ) : array
351
	{
352
		$list = [];
353
354
		foreach( $configList as $key => $config ) {
355
			$list[$key] = new \Aimeos\Base\Criteria\Attribute\Standard( $config );
356
		}
357
358
		return $list;
359
	}
360
361
362
	/**
363
	 * Returns the configuration value that matches one of the given keys.
364
	 *
365
	 * The config of the service item and (optionally) the global config
366
	 * is tested in the order of the keys. The first one that matches will
367
	 * be returned.
368
	 *
369
	 * @param array|string $keys Key name or list of key names that should be tested for in the order to test
370
	 * @param mixed $default Returned value if the key wasn't was found
371
	 * @return mixed Value of the first key that matches or null if none was found
372
	 */
373
	protected function getConfigValue( $keys, $default = null )
374
	{
375
		foreach( (array) $keys as $key )
376
		{
377
			if( ( $value = $this->getServiceItem()->getConfigValue( $key ) ) !== null ) {
378
				return $value;
379
			}
380
381
			if( isset( $this->beGlobalConfig[$key] ) ) {
382
				return $this->beGlobalConfig[$key];
383
			}
384
		}
385
386
		return $default;
387
	}
388
389
390
	/**
391
	 * Logs the given message with the passed log level
392
	 *
393
	 * @param mixed $msg Message or object
394
	 * @param int $level Log level (default: ERR)
395
	 * @return self Same object for fluid method calls
396
	 */
397
	protected function log( $msg, int $level = \Aimeos\Base\Logger\Iface::ERR ) : self
398
	{
399
		$facility = basename( str_replace( '\\', '/', get_class( $this ) ) );
400
		$trace = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 2 );
401
		$trace = array_pop( $trace ) ?: [];
402
		$name = ( $trace['class'] ?? '' ) . '::' . ( $trace['function'] ?? '' );
403
404
		if( !is_scalar( $msg ) ) {
405
			$msg = print_r( $msg, true );
406
		}
407
408
		$this->context->logger()->log( $name . ': ' . $msg, $level, 'core/service/' . $facility );
409
		return $this;
410
	}
411
412
413
	/**
414
	 * Returns the first object of the decorator stack
415
	 *
416
	 * @return \Aimeos\MShop\Service\Provider\Iface First object of the decorator stack
417
	 */
418
	protected function object() : \Aimeos\MShop\Service\Provider\Iface
419
	{
420
		return $this->object ?? $this;
421
	}
422
423
424
	/**
425
	 * Returns the configuration value that matches given key
426
	 *
427
	 * @param string $key Key name
428
	 * @return mixed Value for the key
429
	 * @throws \Aimeos\MShop\Service\Exception If configuration key isn't found
430
	 */
431
	protected function require( string $key )
432
	{
433
		if( ( $value = $this->getConfigValue( $key ) ) === null )
434
		{
435
			$msg = $this->context()->translate( 'mshop', 'Missing configuration "%1$s"' );
436
			throw new \Aimeos\MShop\Service\Exception( sprintf( $msg, $key ) );
437
		}
438
439
		return $value;
440
	}
441
442
443
	/**
444
	 * Saves the order item.
445
	 *
446
	 * @param \Aimeos\MShop\Order\Item\Iface $item Order object
447
	 * @return \Aimeos\MShop\Order\Item\Iface Order object including the generated ID
448
	 */
449
	protected function save( \Aimeos\MShop\Order\Item\Iface $item ) : \Aimeos\MShop\Order\Item\Iface
450
	{
451
		return \Aimeos\MShop::create( $this->context, 'order' )->save( $item );
452
	}
453
454
455
	/**
456
	 * Sets the attributes in the given service item.
457
	 *
458
	 * @param \Aimeos\MShop\Order\Item\Base\Service\Iface $orderServiceItem Order service item that will be added to the basket
459
	 * @param array $attributes Attribute key/value pairs entered by the customer during the checkout process
460
	 * @param string $type Type of the configuration values (delivery or payment)
461
	 * @return \Aimeos\MShop\Order\Item\Base\Service\Iface Modified order service item
462
	 */
463
	protected function setAttributes( \Aimeos\MShop\Order\Item\Base\Service\Iface $orderServiceItem, array $attributes,
464
		string $type ) : \Aimeos\MShop\Order\Item\Base\Service\Iface
465
	{
466
		$manager = \Aimeos\MShop::create( $this->context, 'order/base/service/attribute' );
467
468
		foreach( $attributes as $key => $value )
469
		{
470
			$item = $manager->create();
471
			$item->setCode( $key );
472
			$item->setValue( $value );
473
			$item->setType( $type );
474
475
			$orderServiceItem->setAttributeItem( $item );
476
		}
477
478
		return $orderServiceItem;
479
	}
480
481
482
	/**
483
	 * Adds the service data to the customer account if available
484
	 *
485
	 * @param string $customerId Unique customer ID the service token belongs to
486
	 * @param string $key Key of the value that should be added
487
	 * @param string|array $data Service data to store
488
	 * @param \Aimeos\MShop\Service\Provider\Iface Provider object for chaining method calls
0 ignored issues
show
Bug introduced by
The type Aimeos\MShop\Service\Provider\Provider was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
489
	 */
490
	protected function setData( string $customerId, string $key, $data ) : \Aimeos\MShop\Service\Provider\Iface
491
	{
492
		if( $customerId )
493
		{
494
			$manager = \Aimeos\MShop::create( $this->context, 'customer' );
495
			$item = $manager->get( $customerId, ['service'] );
496
			$serviceId = $this->getServiceItem()->getId();
497
498
			if( ( $listItem = $item->getListItem( 'service', 'default', $serviceId, false ) ) === null )
499
			{
500
				$listManager = \Aimeos\MShop::create( $this->context, 'customer/lists' );
501
				$listItem = $listManager->create()->setRefId( $serviceId );
502
			}
503
504
			$manager->save( $item->addListItem( 'service', $listItem->setConfigValue( $key, $data ) ) );
505
		}
506
507
		return $this;
508
	}
509
510
511
	/**
512
	 * Throws an exception with the given message
513
	 *
514
	 * @param string $msg Message
515
	 * @param string|null $domain Translation domain
516
	 * @param int $code Custom error code
517
	 */
518
	protected function throw( string $msg, string $domain = null, int $code = 0 )
519
	{
520
		if( $domain ) {
521
			$msg = $this->context->translate( $domain, $msg );
522
		}
523
524
		throw new \Aimeos\MShop\Service\Exception( $msg, $code );
525
	}
526
}
527