Completed
Push — master ( daa767...0b51f5 )
by Barry
06:13
created

WordPressRepository::retrieve()   B

Complexity

Conditions 9
Paths 96

Size

Total Lines 89
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 49
nc 96
nop 5
dl 0
loc 89
rs 7.5571
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Never5\DownloadMonitor\Shop\Order;
4
5
use Never5\DownloadMonitor\Shop\Services\Services;
6
7
class WordPressRepository implements Repository {
8
9
	/**
10
	 * Prep where statement for WP DB SQL queries
11
	 *
12
	 * An example filter is an array like this:
13
	 * array(
14
	 *  'key'       => 'id',
15
	 *  'value'     => 1,
16
	 *  'operator'  => '='
17
	 * )
18
	 *
19
	 * @param $filters
20
	 *
21
	 * @return string
22
	 */
23
	private function prep_where_statement( $filters ) {
24
		global $wpdb;
25
		// setup where statements
26
		$where = array( "WHERE 1=1" );
27
		foreach ( $filters as $filter ) {
28
			$operator = ( ! empty( $filter['operator'] ) ) ? esc_sql( $filter['operator'] ) : "=";
0 ignored issues
show
Bug introduced by
The function esc_sql was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

28
			$operator = ( ! empty( $filter['operator'] ) ) ? /** @scrutinizer ignore-call */ esc_sql( $filter['operator'] ) : "=";
Loading history...
29
			if ( 'IN' == $operator && is_array( $filter['value'] ) ) {
30
				array_walk( $filter['value'], 'esc_sql' );
31
				$value_str = implode( "','", $filter['value'] );
32
				$where[]   = "AND `" . esc_sql( $filter['key'] ) . "` " . $operator . " ('" . $value_str . "')";
33
			} else {
34
				$where[] = $wpdb->prepare( "AND `" . esc_sql( $filter['key'] ) . "` " . $operator . " '%s'", $filter['value'] );
35
			}
36
		}
37
		$where_str = "";
38
		if ( count( $where ) > 1 ) {
39
			$where_str = implode( " ", $where );
40
		}
41
42
		return $where_str;
43
	}
44
45
	/**
46
	 * Fetch and add orders items to order
47
	 *
48
	 * @param Order $order
49
	 *
50
	 * @return Order
51
	 */
52
	private function add_order_items_to_order( $order ) {
53
		global $wpdb;
54
55
		/** Fetch order items */
56
		$order_items = array();
57
		$db_items    = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `" . $wpdb->prefix . "dlm_order_item` WHERE `order_id` = %d ORDER BY `id` ASC ;", $order->get_id() ) );
58
		if ( count( $db_items ) > 0 ) {
59
			foreach ( $db_items as $db_item ) {
60
				$order_item = new OrderItem();
61
62
				$order_item->set_id( $db_item->id );
63
				$order_item->set_label( $db_item->label );
64
				$order_item->set_qty( $db_item->qty );
65
				$order_item->set_download_id( $db_item->download_id );
66
				$order_item->set_subtotal( $db_item->subtotal );
67
				$order_item->set_tax_class( $db_item->tax_class );
68
				$order_item->set_tax_total( $db_item->tax_total );
69
				$order_item->set_total( $db_item->total );
70
71
				$order_items[] = $order_item;
72
			}
73
		}
74
75
		$order->set_items( $order_items );
76
77
		return $order;
78
	}
79
80
	/**
81
	 * Fetch and add transactions to order
82
	 *
83
	 * @param Order $order
84
	 *
85
	 * @return Order
86
	 */
87
	private function add_transactions_to_order( $order ) {
88
		global $wpdb;
89
90
		/** Fetch transactions */
91
		$order_transactions = array();
92
		$db_items           = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM `" . $wpdb->prefix . "dlm_order_transaction` WHERE `order_id` = %d ORDER BY `id` ASC ;", $order->get_id() ) );
93
		if ( count( $db_items ) > 0 ) {
94
			foreach ( $db_items as $db_item ) {
95
				$order_transaction = new Transaction\OrderTransaction();
96
97
				$order_transaction->set_id( $db_item->id );
98
99
				if ( ! empty( $db_item->date_created ) ) {
100
					$order_transaction->set_date_created( new \DateTimeImmutable( $db_item->date_created ) );
101
				}
102
103
				if ( ! empty( $db_item->date_modified ) ) {
104
					$order_transaction->set_date_modified( new \DateTimeImmutable( $db_item->date_modified ) );
105
				}
106
107
				$order_transaction->set_amount( $db_item->amount );
108
				$order_transaction->set_status( Services::get()->service( 'order_transaction_factory' )->make_status( $db_item->status ) );
109
				$order_transaction->set_processor( $db_item->processor );
110
				$order_transaction->set_processor_nice_name( $db_item->processor_nice_name );
111
				$order_transaction->set_processor_transaction_id( $db_item->processor_transaction_id );
112
				$order_transaction->set_processor_status( $db_item->processor_status );
113
114
				$order_transactions[] = $order_transaction;
115
			}
116
		}
117
118
		$order->set_transactions( $order_transactions );
119
120
		return $order;
121
	}
122
123
124
	/**
125
	 * Retrieve session
126
	 *
127
	 * @param array $filters
128
	 * @param int $limit
129
	 * @param int $offset
130
	 * @param string $order_by
131
	 * @param string order
132
	 *
133
	 * @return Order[]
134
	 *
135
	 * @throws \Exception
136
	 */
137
	public function retrieve( $filters = array(), $limit = 0, $offset = 0, $order_by = 'id', $order = 'DESC' ) {
138
		global $wpdb;
139
140
		// prep order
141
		$order_by = ( empty( $order_by ) ) ? 'id' : esc_sql( $order_by );
0 ignored issues
show
Bug introduced by
The function esc_sql was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

141
		$order_by = ( empty( $order_by ) ) ? 'id' : /** @scrutinizer ignore-call */ esc_sql( $order_by );
Loading history...
142
		$order    = strtoupper( $order );
143
		if ( ! in_array( $order, array( 'ASC', 'DESC' ) ) ) {
144
			$order = 'DESC';
145
		}
146
147
		// prep where statement
148
		$where_str = $this->prep_where_statement( $filters );
149
150
		$sql = "
151
		SELECT O.*, C.* 
152
		FROM `" . $wpdb->prefix . "dlm_order` O
153
		INNER JOIN `" . $wpdb->prefix . "dlm_order_customer` C ON O.id=C.order_id
154
		" . $where_str . "
155
		ORDER BY O.`" . $order_by . "` " . $order;
156
157
		$limit  = absint( $limit );
0 ignored issues
show
Bug introduced by
The function absint was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

157
		$limit  = /** @scrutinizer ignore-call */ absint( $limit );
Loading history...
158
		$offset = absint( $offset );
159
160
		if ( $limit > 0 ) {
161
			$sql .= " LIMIT " . $limit;
162
		}
163
164
		if ( $offset > 0 ) {
165
			$sql .= " OFFSET " . $offset;
166
		}
167
168
		$sql .= ";";
169
170
		// try to fetch session from database
171
		$results = $wpdb->get_results( $sql );
172
173
		// check if result if found
174
		if ( null === $results ) {
175
			throw new \Exception( 'SQL error while fetching order' );
176
		}
177
178
		// array that will hold all order objects
179
		$orders = array();
180
181
		foreach ( $results as $result ) {
182
183
			$order = new Order();
184
185
			$order->set_id( $result->id );
186
			$order->set_status( Services::get()->service( 'order_status_factory' )->make( $result->status ) );
187
			$order->set_currency( $result->currency );
188
			$order->set_hash( $result->hash );
189
190
			if ( ! empty( $result->date_created ) ) {
191
				$order->set_date_created( new \DateTimeImmutable( $result->date_created ) );
192
			}
193
194
			if ( ! empty( $result->date_modified ) ) {
195
				$order->set_date_modified( new \DateTimeImmutable( $result->date_modified ) );
196
			}
197
198
			// create and set customer
199
			$order->set_customer( new OrderCustomer(
200
				$result->first_name,
201
				$result->last_name,
202
				$result->company,
203
				$result->address_1,
204
				$result->address_2,
205
				$result->city,
206
				$result->state,
207
				$result->postcode,
208
				$result->country,
209
				$result->email,
210
				$result->phone,
211
				$result->ip_address
212
			) );
213
214
			// add order items to order object
215
			$order = $this->add_order_items_to_order( $order );
216
217
			// add transactions to order object
218
			$order = $this->add_transactions_to_order( $order );
219
220
			// add new order object to array
221
			$orders[] = $order;
222
223
		}
224
225
		return $orders;
226
227
	}
228
229
	/**
230
	 * Retrieve a single order
231
	 *
232
	 * @param $id
233
	 *
234
	 * @return Order
235
	 *
236
	 * @throws \Exception
237
	 */
238
	public function retrieve_single( $id ) {
239
		$orders = $this->retrieve( array( array( 'key' => 'id', 'value' => $id, 'operator' => '=' ) ), 1 );
240
		if ( 0 === count( $orders ) ) {
241
			throw new \Exception( 'Order not found' );
242
		}
243
244
		return $orders[0];
245
	}
246
247
	/**
248
	 * Returns number of rows for given filters
249
	 *
250
	 * @param array $filters
251
	 *
252
	 * @return int
253
	 */
254
	public function num_rows( $filters = array() ) {
255
		global $wpdb;
256
257
		// prep where statement
258
		$where_str = $this->prep_where_statement( $filters );
259
260
		$num = $wpdb->get_var( "SELECT COUNT(id) FROM `" . $wpdb->prefix . "dlm_order` {$where_str} " );
261
262
		if ( null === $num ) {
263
			$num = 0;
264
		}
265
266
		return $num;
267
	}
268
269
	/**
270
	 * Persist order
271
	 *
272
	 * @param Order $order
273
	 *
274
	 * @throws \Exception
275
	 *
276
	 * @return bool
277
	 */
278
	public function persist( $order ) {
279
		global $wpdb;
280
281
		$date_created = '';
282
		if ( null !== $order->get_date_created() ) {
283
			$date_created = $order->get_date_created()->format( 'Y-m-d H:i:s' );
284
		}
285
286
		$date_modified = '';
287
		if ( null !== $order->get_date_modified() ) {
288
			$date_modified = $order->get_date_modified()->format( 'Y-m-d H:i:s' );
289
		}
290
291
		$order_id = $order->get_id();
292
293
		$customer = $order->get_customer();
294
295
		// check if it's a new order or if we need to update an existing one
296
		if ( empty( $order_id ) ) {
297
			// new order
298
299
			// insert order
300
			$wpdb->insert(
301
				$wpdb->prefix . 'dlm_order',
302
				array(
303
					'status'        => $order->get_status()->get_key(),
304
					'date_created'  => $date_created,
305
					'date_modified' => $date_modified,
306
					'currency'      => $order->get_currency(),
307
					'hash'          => $order->get_hash()
308
				),
309
				array(
310
					'%s',
311
					'%s',
312
					'%s',
313
					'%s',
314
					'%s'
315
				)
316
			);
317
318
			// set the new id as order id
319
			$order->set_id( $wpdb->insert_id );
320
321
			// insert customer record
322
			$wpdb->insert(
323
				$wpdb->prefix . 'dlm_order_customer',
324
				array(
325
					'first_name' => $customer->get_first_name(),
326
					'last_name'  => $customer->get_last_name(),
327
					'company'    => $customer->get_company(),
328
					'address_1'  => $customer->get_address_1(),
329
					'address_2'  => $customer->get_address_2(),
330
					'city'       => $customer->get_city(),
331
					'state'      => $customer->get_state(),
332
					'postcode'   => $customer->get_postcode(),
333
					'country'    => $customer->get_country(),
334
					'email'      => $customer->get_email(),
335
					'phone'      => $customer->get_phone(),
336
					'ip_address' => $customer->get_ip_address(),
337
					'order_id'   => $order->get_id()
338
				),
339
				array(
340
					'%s',
341
					'%s',
342
					'%s',
343
					'%s',
344
					'%s',
345
					'%s',
346
					'%s',
347
					'%s',
348
					'%s',
349
					'%s',
350
					'%s',
351
					'%s',
352
					'%d'
353
				)
354
			);
355
356
		} else {
357
358
			// update an existing order
359
			$wpdb->update( $wpdb->prefix . 'dlm_order',
360
				array(
361
					'status'        => $order->get_status()->get_key(),
362
					'date_modified' => current_time( 'mysql', 1 ),
0 ignored issues
show
Bug introduced by
The function current_time was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

362
					'date_modified' => /** @scrutinizer ignore-call */ current_time( 'mysql', 1 ),
Loading history...
363
					'currency'      => $order->get_currency(),
364
					'hash'          => $order->get_hash()
365
				),
366
				array( 'id' => $order_id ),
367
				array(
368
					'%s',
369
					'%s',
370
					'%s',
371
					'%s'
372
				),
373
				array( '%d' )
374
			);
375
376
			// update customer record
377
			$wpdb->update(
378
				$wpdb->prefix . 'dlm_order_customer',
379
				array(
380
					'first_name' => $customer->get_first_name(),
381
					'last_name'  => $customer->get_last_name(),
382
					'company'    => $customer->get_company(),
383
					'address_1'  => $customer->get_address_1(),
384
					'address_2'  => $customer->get_address_2(),
385
					'city'       => $customer->get_city(),
386
					'state'      => $customer->get_state(),
387
					'postcode'   => $customer->get_postcode(),
388
					'country'    => $customer->get_country(),
389
					'email'      => $customer->get_email(),
390
					'phone'      => $customer->get_phone(),
391
					'ip_address' => $customer->get_ip_address(),
392
					'order_id'   => $order->get_id()
393
				),
394
				array( 'order_id' => $order_id ),
395
				array(
396
					'%s',
397
					'%s',
398
					'%s',
399
					'%s',
400
					'%s',
401
					'%s',
402
					'%s',
403
					'%s',
404
					'%s',
405
					'%s',
406
					'%s',
407
					'%s',
408
					'%d'
409
				),
410
				array( '%d' )
411
			);
412
413
		}
414
415
		// handle order items
416
		$order_items = $order->get_items();
417
		if ( ! empty( $order_items ) ) {
418
			foreach ( $order_items as $order_item ) {
419
420
				// check if this order item exists in DB already
421
				$order_item_id = $order_item->get_id();
422
				if ( empty( $order_item_id ) ) {
423
424
					// insert new order item
425
					$wpdb->insert(
426
						$wpdb->prefix . 'dlm_order_item',
427
						array(
428
							'order_id'    => $order->get_id(),
429
							'label'       => $order_item->get_label(),
430
							'qty'         => $order_item->get_qty(),
431
							'download_id' => $order_item->get_download_id(),
432
							'tax_class'   => $order_item->get_tax_class(),
433
							'tax_total'   => $order_item->get_tax_total(),
434
							'subtotal'    => $order_item->get_subtotal(),
435
							'total'       => $order_item->get_total()
436
						),
437
						array(
438
							'%d',
439
							'%s',
440
							'%d',
441
							'%d',
442
							'%s',
443
							'%d',
444
							'%d',
445
							'%d',
446
						)
447
					);
448
449
					$order_item->set_id( $wpdb->insert_id );
450
				} else {
451
452
					// update existing order item record
453
					$wpdb->update(
454
						$wpdb->prefix . 'dlm_order_item',
455
						array(
456
							'order_id'    => $order->get_id(),
457
							'label'       => $order_item->get_label(),
458
							'qty'         => $order_item->get_qty(),
459
							'download_id' => $order_item->get_download_id(),
460
							'tax_class'   => $order_item->get_tax_class(),
461
							'tax_total'   => $order_item->get_tax_total(),
462
							'subtotal'    => $order_item->get_subtotal(),
463
							'total'       => $order_item->get_total()
464
						),
465
						array( 'id' => $order_item_id ),
466
						array(
467
							'%d',
468
							'%s',
469
							'%d',
470
							'%d',
471
							'%s',
472
							'%d',
473
							'%d',
474
							'%d',
475
						),
476
						array( '%d' )
477
					);
478
479
				}
480
			}
481
		}
482
483
		// handle transactions
484
		$transactions = $order->get_transactions();
485
		if ( ! empty( $transactions ) ) {
486
487
			/** @var Transaction\OrderTransaction $transaction */
488
			foreach ( $transactions as $transaction ) {
489
490
				$transaction_id = $transaction->get_id();
491
492
				$transaction_date_created = null;
493
				if ( null !== $transaction->get_date_created() ) {
494
					$transaction_date_created = $transaction->get_date_created()->format( 'Y-m-d H:i:s' );
495
				}
496
497
				$transaction_date_modified = null;
498
				if ( null !== $transaction->get_date_modified() ) {
499
					$transaction_date_modified = $transaction->get_date_modified()->format( 'Y-m-d H:i:s' );
500
				}
501
502
				// check if it's a new transaction or an existing one
503
				if ( empty( $transaction_id ) ) {
504
505
					// it's a new transaction
506
507
					$wpdb->insert(
508
						$wpdb->prefix . 'dlm_order_transaction',
509
						array(
510
							'order_id'                 => $order->get_id(),
511
							'date_created'             => $transaction_date_created,
512
							'date_modified'            => $transaction_date_modified,
513
							'amount'                   => $transaction->get_amount(),
514
							'status'                   => $transaction->get_status()->get_key(),
515
							'processor'                => $transaction->get_processor(),
516
							'processor_nice_name'      => $transaction->get_processor_nice_name(),
517
							'processor_transaction_id' => $transaction->get_processor_transaction_id(),
518
							'processor_status'         => $transaction->get_processor_status()
519
						),
520
						array(
521
							'%d',
522
							'%s',
523
							'%s',
524
							'%d',
525
							'%s',
526
							'%s',
527
							'%s',
528
							'%s',
529
							'%s'
530
						)
531
					);
532
533
534
					$transaction->set_id( $wpdb->insert_id );
535
536
				} else {
537
538
					// it's an existing transaction
539
540
					$wpdb->update(
541
						$wpdb->prefix . 'dlm_order_transaction',
542
						array(
543
							'order_id'                 => $order->get_id(),
544
							'date_created'             => $transaction_date_created,
545
							'date_modified'            => $transaction_date_modified,
546
							'amount'                   => $transaction->get_amount(),
547
							'status'                   => $transaction->get_status()->get_key(),
548
							'processor'                => $transaction->get_processor(),
549
							'processor_nice_name'      => $transaction->get_processor_nice_name(),
550
							'processor_transaction_id' => $transaction->get_processor_transaction_id(),
551
							'processor_status'         => $transaction->get_processor_status()
552
						),
553
						array( 'id' => $transaction_id ),
554
						array(
555
							'%d',
556
							'%s',
557
							'%s',
558
							'%d',
559
							'%s',
560
							'%s',
561
							'%s',
562
							'%s',
563
							'%s'
564
						),
565
						array( '%d' )
566
					);
567
568
				}
569
570
			}
571
572
		}
573
574
	}
575
576
}