Passed
Push — master ( 4dfaf5...a9e490 )
by Aimeos
07:40 queued 05:13
created

Standard::getPaymentForm()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 36
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 21
c 0
b 0
f 0
nc 4
nop 2
dl 0
loc 36
rs 8.9617
1
<?php
2
3
/**
4
 * @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
5
 * @copyright Aimeos (aimeos.org), 2017-2022
6
 * @package Client
7
 * @subpackage JsonApi
8
 */
9
10
11
namespace Aimeos\Client\JsonApi\Order;
12
13
use Psr\Http\Message\ResponseInterface;
14
use Psr\Http\Message\ServerRequestInterface;
15
16
17
/**
18
 * JSON API standard client
19
 *
20
 * @package Client
21
 * @subpackage JsonApi
22
 */
23
class Standard
24
	extends \Aimeos\Client\JsonApi\Base
25
	implements \Aimeos\Client\JsonApi\Iface
26
{
27
	/** client/jsonapi/order/name
28
	 * Class name of the used order client implementation
29
	 *
30
	 * Each default JSON API client can be replace by an alternative imlementation.
31
	 * To use this implementation, you have to set the last part of the class
32
	 * name as configuration value so the client factory knows which class it
33
	 * has to instantiate.
34
	 *
35
	 * For example, if the name of the default class is
36
	 *
37
	 *  \Aimeos\Client\JsonApi\Order\Standard
38
	 *
39
	 * and you want to replace it with your own version named
40
	 *
41
	 *  \Aimeos\Client\JsonApi\Order\Myorder
42
	 *
43
	 * then you have to set the this configuration option:
44
	 *
45
	 *  client/jsonapi/order/name = Myorder
46
	 *
47
	 * The value is the last part of your own class name and it's case sensitive,
48
	 * so take care that the configuration value is exactly named like the last
49
	 * part of the class name.
50
	 *
51
	 * The allowed characters of the class name are A-Z, a-z and 0-9. No other
52
	 * characters are possible! You should always start the last part of the class
53
	 * name with an upper case character and continue only with lower case characters
54
	 * or numbers. Avoid chamel case names like "MyOrder"!
55
	 *
56
	 * @param string Last part of the class name
57
	 * @since 2017.03
58
	 * @category Developer
59
	 */
60
61
	/** client/jsonapi/order/decorators/excludes
62
	 * Excludes decorators added by the "common" option from the JSON API clients
63
	 *
64
	 * Decorators extend the functionality of a class by adding new aspects
65
	 * (e.g. log what is currently done), executing the methods of the underlying
66
	 * class only in certain conditions (e.g. only for logged in users) or
67
	 * modify what is returned to the caller.
68
	 *
69
	 * This option allows you to remove a decorator added via
70
	 * "client/jsonapi/common/decorators/default" before they are wrapped
71
	 * around the JsonApi client.
72
	 *
73
	 *  client/jsonapi/decorators/excludes = array( 'decorator1' )
74
	 *
75
	 * This would remove the decorator named "decorator1" from the list of
76
	 * common decorators ("\Aimeos\Client\JsonApi\Common\Decorator\*") added via
77
	 * "client/jsonapi/common/decorators/default" for the JSON API client.
78
	 *
79
	 * @param array List of decorator names
80
	 * @since 2017.07
81
	 * @category Developer
82
	 * @see client/jsonapi/common/decorators/default
83
	 * @see client/jsonapi/order/decorators/global
84
	 * @see client/jsonapi/order/decorators/local
85
	 */
86
87
	/** client/jsonapi/order/decorators/global
88
	 * Adds a list of globally available decorators only to the JsonApi client
89
	 *
90
	 * Decorators extend the functionality of a class by adding new aspects
91
	 * (e.g. log what is currently done), executing the methods of the underlying
92
	 * class only in certain conditions (e.g. only for logged in users) or
93
	 * modify what is returned to the caller.
94
	 *
95
	 * This option allows you to wrap global decorators
96
	 * ("\Aimeos\Client\JsonApi\Common\Decorator\*") around the JsonApi
97
	 * client.
98
	 *
99
	 *  client/jsonapi/order/decorators/global = array( 'decorator1' )
100
	 *
101
	 * This would add the decorator named "decorator1" defined by
102
	 * "\Aimeos\Client\JsonApi\Common\Decorator\Decorator1" only to the
103
	 * "order" JsonApi client.
104
	 *
105
	 * @param array List of decorator names
106
	 * @since 2017.07
107
	 * @category Developer
108
	 * @see client/jsonapi/common/decorators/default
109
	 * @see client/jsonapi/order/decorators/excludes
110
	 * @see client/jsonapi/order/decorators/local
111
	 */
112
113
	/** client/jsonapi/order/decorators/local
114
	 * Adds a list of local decorators only to the JsonApi client
115
	 *
116
	 * Decorators extend the functionality of a class by adding new aspects
117
	 * (e.g. log what is currently done), executing the methods of the underlying
118
	 * class only in certain conditions (e.g. only for logged in users) or
119
	 * modify what is returned to the caller.
120
	 *
121
	 * This option allows you to wrap local decorators
122
	 * ("\Aimeos\Client\JsonApi\Order\Decorator\*") around the JsonApi
123
	 * client.
124
	 *
125
	 *  client/jsonapi/order/decorators/local = array( 'decorator2' )
126
	 *
127
	 * This would add the decorator named "decorator2" defined by
128
	 * "\Aimeos\Client\JsonApi\Order\Decorator\Decorator2" only to the
129
	 * "order" JsonApi client.
130
	 *
131
	 * @param array List of decorator names
132
	 * @since 2017.07
133
	 * @category Developer
134
	 * @see client/jsonapi/common/decorators/default
135
	 * @see client/jsonapi/order/decorators/excludes
136
	 * @see client/jsonapi/order/decorators/global
137
	 */
138
139
140
	/**
141
	 * Returns the resource or the resource list
142
	 *
143
	 * @param \Psr\Http\Message\ServerRequestInterface $request Request object
144
	 * @param \Psr\Http\Message\ResponseInterface $response Response object
145
	 * @return \Psr\Http\Message\ResponseInterface Modified response object
146
	 */
147
	public function get( ServerRequestInterface $request, ResponseInterface $response ) : \Psr\Http\Message\ResponseInterface
148
	{
149
		$view = $this->view();
150
		$ref = $view->param( 'include', [] );
151
152
		if( is_string( $ref ) ) {
153
			$ref = explode( ',', $ref );
154
		}
155
156
		try
157
		{
158
			$cntl = \Aimeos\Controller\Frontend::create( $this->context(), 'order' )->uses( $ref );
159
160
			if( ( $id = $view->param( 'id' ) ) != '' )
161
			{
162
				$view->items = $cntl->get( $id );
163
				$view->total = 1;
164
			}
165
			else
166
			{
167
				$total = 0;
168
				$items = $cntl->sort( $view->param( 'sort', '-order.id' ) )
169
					->slice( $view->param( 'page/offset', 0 ), $view->param( 'page/limit', 48 ) )
170
					->parse( (array) $view->param( 'filter', [] ) )
171
					->search( $total );
172
173
				$view->items = $items;
174
				$view->total = $total;
175
			}
176
177
			$status = 200;
178
		}
179
		catch( \Aimeos\Controller\Frontend\Exception $e )
180
		{
181
			$status = 403;
182
			$view->errors = $this->getErrorDetails( $e, 'controller/frontend' );
183
		}
184
		catch( \Aimeos\MShop\Exception $e )
185
		{
186
			$status = 404;
187
			$view->errors = $this->getErrorDetails( $e, 'mshop' );
188
		}
189
		catch( \Exception $e )
190
		{
191
			$status = $e->getCode() >= 100 && $e->getCode() < 600 ? $e->getCode() : 500;
192
			$view->errors = $this->getErrorDetails( $e );
193
		}
194
195
		return $this->render( $response, $view, $status );
196
	}
197
198
199
	/**
200
	 * Creates or updates the resource or the resource list
201
	 *
202
	 * @param \Psr\Http\Message\ServerRequestInterface $request Request object
203
	 * @param \Psr\Http\Message\ResponseInterface $response Response object
204
	 * @return \Psr\Http\Message\ResponseInterface Modified response object
205
	 */
206
	public function post( ServerRequestInterface $request, ResponseInterface $response ) : \Psr\Http\Message\ResponseInterface
207
	{
208
		$view = $this->view();
209
210
		try
211
		{
212
			$body = (string) $request->getBody();
213
214
			if( ( $payload = json_decode( $body ) ) === null || !isset( $payload->data->attributes ) ) {
215
				throw new \Aimeos\Client\JsonApi\Exception( 'Invalid JSON in body', 400 );
216
			}
217
218
			if( !isset( $payload->data->attributes->{'order.baseid'} ) ) {
219
				throw new \Aimeos\Client\JsonApi\Exception( 'Required attribute "order.baseid" is missing', 400 );
220
			}
221
222
			$basket = $this->getBasket( $payload->data->attributes->{'order.baseid'} );
223
			$item = $this->createOrder( $payload->data->attributes->{'order.baseid'} );
224
225
			$view->form = $this->getPaymentForm( $item->setBaseItem( $basket ), (array) $payload->data->attributes );
226
			$view->items = $item;
227
			$view->total = 1;
228
229
			\Aimeos\Controller\Frontend::create( $this->context(), 'order' )->save( $item );
230
			$status = 201;
231
		}
232
		catch( \Aimeos\Client\JsonApi\Exception $e )
233
		{
234
			$status = $e->getCode();
235
			$view->errors = $this->getErrorDetails( $e, 'client/jsonapi' );
236
		}
237
		catch( \Aimeos\Controller\Frontend\Exception $e )
238
		{
239
			$status = 403;
240
			$view->errors = $this->getErrorDetails( $e, 'controller/frontend' );
241
		}
242
		catch( \Aimeos\MShop\Exception $e )
243
		{
244
			$status = 404;
245
			$view->errors = $this->getErrorDetails( $e, 'mshop' );
246
		}
247
		catch( \Exception $e )
248
		{
249
			$status = $e->getCode() >= 100 && $e->getCode() < 600 ? $e->getCode() : 500;
250
			$view->errors = $this->getErrorDetails( $e );
251
		}
252
253
		return $this->render( $response, $view, $status );
254
	}
255
256
257
	/**
258
	 * Returns the available REST verbs and the available parameters
259
	 *
260
	 * @param \Psr\Http\Message\ServerRequestInterface $request Request object
261
	 * @param \Psr\Http\Message\ResponseInterface $response Response object
262
	 * @return \Psr\Http\Message\ResponseInterface Modified response object
263
	 */
264
	public function options( ServerRequestInterface $request, ResponseInterface $response ) : \Psr\Http\Message\ResponseInterface
265
	{
266
		$view = $this->view();
267
268
		$view->attributes = [
269
			'order.baseid' => [
270
				'label' => 'ID of the stored basket (POST only)',
271
				'type' => 'string', 'default' => '', 'required' => true,
272
			],
273
		];
274
275
		$tplconf = 'client/jsonapi/template-options';
276
		$default = 'options-standard';
277
278
		$body = $view->render( $view->config( $tplconf, $default ) );
279
280
		return $response->withHeader( 'Allow', 'GET,OPTIONS,POST' )
281
			->withHeader( 'Cache-Control', 'max-age=300' )
282
			->withHeader( 'Content-Type', 'application/vnd.api+json' )
283
			->withBody( $view->response()->createStreamFromString( $body ) )
284
			->withStatus( 200 );
285
	}
286
287
288
	/**
289
	 * Adds and returns a new order item for the given order base ID
290
	 *
291
	 * @param string $baseId Unique order base ID
292
	 * @return \Aimeos\MShop\Order\Item\Iface New order item
293
	 */
294
	protected function createOrder( string $baseId ) : \Aimeos\MShop\Order\Item\Iface
295
	{
296
		$context = $this->context();
297
		$cntl = \Aimeos\Controller\Frontend::create( $context, 'order' );
298
		$item = $cntl->add( $baseId, ['order.channel' => 'jsonapi'] )->store();
299
300
		$context->session()->set( 'aimeos/orderid', $item->getId() );
301
302
		return $item;
303
	}
304
305
306
	/**
307
	 * Returns the basket object for the given ID
308
	 *
309
	 * @param string $basketId Unique order base ID
310
	 * @return \Aimeos\MShop\Order\Item\Base\Iface Basket object including only the services
311
	 * @throws \Aimeos\Client\JsonApi\Exception If basket ID is not the same as stored before in the current session
312
	 */
313
	protected function getBasket( string $basketId ) : \Aimeos\MShop\Order\Item\Base\Iface
314
	{
315
		$context = $this->context();
316
		$baseId = $context->session()->get( 'aimeos/order.baseid' );
317
318
		if( $baseId != $basketId )
319
		{
320
			$msg = sprintf( 'No basket for the "order.baseid" ("%1$s") found', $basketId );
321
			throw new \Aimeos\Client\JsonApi\Exception( $msg, 403 );
322
		}
323
324
		$cntl = \Aimeos\Controller\Frontend::create( $context, 'basket' );
325
326
		return $cntl->get( $baseId, ['order/base/service'] );
327
	}
328
329
330
	/**
331
	 * Returns the form helper object for building the payment form in the frontend
332
	 *
333
	 * @param \Aimeos\MShop\Order\Item\Iface $orderItem Saved order item created for the basket object
334
	 * @param array $attributes Associative list of payment data pairs
335
	 * @return \Aimeos\MShop\Common\Helper\Form\Iface|null Form object with URL, parameters, etc. or null if no form data is required
336
	 */
337
	protected function getPaymentForm( \Aimeos\MShop\Order\Item\Iface $orderItem, array $attributes ) : ?\Aimeos\MShop\Common\Helper\Form\Iface
338
	{
339
		$view = $this->view();
340
		$context = $this->context();
341
		$basket = $orderItem->getBaseItem();
342
343
		$total = $basket->getPrice()->getValue() + $basket->getPrice()->getCosts();
344
		$services = $basket->getService( \Aimeos\MShop\Order\Item\Base\Service\Base::TYPE_PAYMENT );
345
346
		if( $services === [] || $total <= '0.00' && $this->isSubscription( $basket->getProducts() ) === false )
347
		{
348
			$cntl = \Aimeos\Controller\Frontend::create( $context, 'order' );
349
			$cntl->save( $orderItem->setStatusPayment( \Aimeos\MShop\Order\Item\Base::PAY_AUTHORIZED ) );
350
351
			$url = $this->getUrlConfirm( $view, [], ['absoluteUri' => true, 'namespace' => false] );
352
			return new \Aimeos\MShop\Common\Helper\Form\Standard( $url, 'GET' );
353
		}
354
355
		if( ( $service = reset( $services ) ) !== false )
356
		{
357
			$args = array( 'code' => $service->getCode(), 'orderid' => $orderItem->getId() );
358
			$config = array( 'absoluteUri' => true, 'namespace' => false );
359
			$urls = array(
360
				'payment.url-success' => $this->getUrlConfirm( $view, $args, $config ),
361
				'payment.url-update' => $this->getUrlUpdate( $view, $args, $config ),
362
			);
363
364
			foreach( $service->getAttributeItems() as $item ) {
365
				$attributes[$item->getCode()] = $item->getValue();
366
			}
367
368
			$serviceCntl = \Aimeos\Controller\Frontend::create( $context, 'service' );
369
			return $serviceCntl->process( $orderItem, $service->getServiceId(), $urls, $attributes );
370
		}
371
372
		return null;
373
	}
374
375
376
	/**
377
	 * Returns the URL to the confirm page.
378
	 *
379
	 * @param \Aimeos\Base\View\Iface $view View object
380
	 * @param array $params Parameters that should be part of the URL
381
	 * @param array $config Default URL configuration
382
	 * @return string URL string
383
	 */
384
	protected function getUrlConfirm( \Aimeos\Base\View\Iface $view, array $params, array $config ) : string
385
	{
386
		$target = $view->config( 'client/html/checkout/confirm/url/target' );
387
		$cntl = $view->config( 'client/html/checkout/confirm/url/controller', 'checkout' );
388
		$action = $view->config( 'client/html/checkout/confirm/url/action', 'confirm' );
389
		$config = $view->config( 'client/html/checkout/confirm/url/config', $config );
390
391
		return $view->url( $target, $cntl, $action, $params, [], $config );
392
	}
393
394
395
	/**
396
	 * Returns the URL to the update page.
397
	 *
398
	 * @param \Aimeos\Base\View\Iface $view View object
399
	 * @param array $params Parameters that should be part of the URL
400
	 * @param array $config Default URL configuration
401
	 * @return string URL string
402
	 */
403
	protected function getUrlUpdate( \Aimeos\Base\View\Iface $view, array $params, array $config ) : string
404
	{
405
		$target = $view->config( 'client/html/checkout/update/url/target' );
406
		$cntl = $view->config( 'client/html/checkout/update/url/controller', 'checkout' );
407
		$action = $view->config( 'client/html/checkout/update/url/action', 'update' );
408
		$config = $view->config( 'client/html/checkout/update/url/config', $config );
409
410
		return $view->url( $target, $cntl, $action, $params, [], $config );
411
	}
412
413
414
	/**
415
	 * Tests if one of the products is a subscription
416
	 *
417
	 * @param \Aimeos\Map $products Ordered products implementing \Aimeos\MShop\Order\Item\Base\Product\Iface
418
	 * @return bool True if at least one product is a subscription, false if not
419
	 */
420
	protected function isSubscription( \Aimeos\Map $products ) : bool
421
	{
422
		foreach( $products as $orderProduct )
423
		{
424
			if( $orderProduct->getAttributeItem( 'interval', 'config' ) ) {
425
				return true;
426
			}
427
		}
428
429
		return false;
430
	}
431
432
433
	/**
434
	 * Returns the response object with the rendered header and body
435
	 *
436
	 * @param \Psr\Http\Message\ResponseInterface $response Response object
437
	 * @param \Aimeos\Base\View\Iface $view View instance
438
	 * @param int $status HTTP status code
439
	 * @return \Psr\Http\Message\ResponseInterface Modified response object
440
	 */
441
	protected function render( ResponseInterface $response, \Aimeos\Base\View\Iface $view, int $status ) : \Psr\Http\Message\ResponseInterface
442
	{
443
		/** client/jsonapi/order/template
444
		 * Relative path to the order JSON API template
445
		 *
446
		 * The template file contains the code and processing instructions
447
		 * to generate the result shown in the JSON API body. The
448
		 * configuration string is the path to the template file relative
449
		 * to the templates directory (usually in templates/client/jsonapi).
450
		 *
451
		 * You can overwrite the template file configuration in extensions and
452
		 * provide alternative templates. These alternative templates should be
453
		 * named like the default one but with the string "standard" replaced by
454
		 * an unique name. You may use the name of your project for this. If
455
		 * you've implemented an alternative client class as well, "standard"
456
		 * should be replaced by the name of the new class.
457
		 *
458
		 * @param string Relative path to the template creating the body of the JSON API
459
		 * @since 2017.03
460
		 * @category Developer
461
		 */
462
		$tplconf = 'client/jsonapi/order/template';
463
		$default = 'order/standard';
464
465
		$body = $view->render( $view->config( $tplconf, $default ) );
466
467
		return $response->withHeader( 'Allow', 'GET,OPTIONS,POST' )
468
			->withHeader( 'Cache-Control', 'no-cache, private' )
469
			->withHeader( 'Content-Type', 'application/vnd.api+json' )
470
			->withBody( $view->response()->createStreamFromString( $body ) )
471
			->withStatus( $status );
472
	}
473
}
474