Completed
Branch dependabot/composer/tijsverkoy... (491ea6)
by
unknown
32:00 queued 25:42
created
core/EE_Request_Handler.core.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@
 block discarded – undo
73 73
 
74 74
     private function getCurrentPage()
75 75
     {
76
-        if (! $this->current_page instanceof CurrentPage) {
76
+        if ( ! $this->current_page instanceof CurrentPage) {
77 77
             $this->current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
78 78
         }
79 79
         return $this->current_page;
Please login to merge, or discard this patch.
Indentation   +269 added lines, -269 removed lines patch added patch discarded remove patch
@@ -16,273 +16,273 @@
 block discarded – undo
16 16
  */
17 17
 final class EE_Request_Handler implements InterminableInterface
18 18
 {
19
-    /**
20
-     * @var CurrentPage
21
-     */
22
-    private $current_page;
23
-
24
-    /**
25
-     * @var RequestInterface
26
-     */
27
-    private $request;
28
-
29
-    /**
30
-     * @var ResponseInterface
31
-     */
32
-    private $response;
33
-
34
-    /**
35
-     * whether current request is via AJAX
36
-     *
37
-     * @var boolean
38
-     */
39
-    public $ajax = false;
40
-
41
-    /**
42
-     * whether current request is via AJAX from the frontend of the site
43
-     *
44
-     * @var boolean
45
-     */
46
-    public $front_ajax = false;
47
-
48
-
49
-    /**
50
-     * @param RequestInterface  $request
51
-     * @param ResponseInterface $response
52
-     */
53
-    public function __construct(RequestInterface $request, ResponseInterface $response)
54
-    {
55
-        $this->request      = $request;
56
-        $this->response     = $response;
57
-        $this->ajax         = $this->request->isAjax();
58
-        $this->front_ajax   = $this->request->isFrontAjax();
59
-        do_action('AHEE__EE_Request_Handler__construct__complete');
60
-    }
61
-
62
-
63
-    /**
64
-     * @param WP $WP
65
-     * @return void
66
-     * @deprecated  4.10.14.p
67
-     */
68
-    public function parse_request($WP = null)
69
-    {
70
-    }
71
-
72
-
73
-    private function getCurrentPage()
74
-    {
75
-        if (! $this->current_page instanceof CurrentPage) {
76
-            $this->current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
77
-        }
78
-        return $this->current_page;
79
-    }
80
-
81
-
82
-    /**
83
-     * @param WP $WP
84
-     * @return void
85
-     * @deprecated  4.10.14.p
86
-     */
87
-    public function set_request_vars($WP = null)
88
-    {
89
-        $this->getCurrentPage()->parseQueryVars($WP);
90
-    }
91
-
92
-
93
-    /**
94
-     * @param WP $WP
95
-     * @return int
96
-     * @deprecated  4.10.14.p
97
-     */
98
-    public function get_post_id_from_request($WP = null)
99
-    {
100
-        return $this->getCurrentPage()->postId();
101
-    }
102
-
103
-
104
-    /**
105
-     * @param WP $WP
106
-     * @return string
107
-     * @deprecated  4.10.14.p
108
-     */
109
-    public function get_post_name_from_request($WP = null)
110
-    {
111
-        return $this->getCurrentPage()->postName();
112
-    }
113
-
114
-
115
-    /**
116
-     * @param WP $WP
117
-     * @return array
118
-     * @deprecated  4.10.14.p
119
-     */
120
-    public function get_post_type_from_request($WP = null)
121
-    {
122
-        return $this->getCurrentPage()->postType();
123
-    }
124
-
125
-
126
-    /**
127
-     * Just a helper method for getting the url for the displayed page.
128
-     *
129
-     * @param WP $WP
130
-     * @return string
131
-     * @deprecated  4.10.14.p
132
-     */
133
-    public function get_current_page_permalink($WP = null)
134
-    {
135
-        return $this->getCurrentPage()->getPermalink($WP);
136
-    }
137
-
138
-
139
-    /**
140
-     * @return bool
141
-     * @deprecated  4.10.14.p
142
-     */
143
-    public function test_for_espresso_page()
144
-    {
145
-        return $this->getCurrentPage()->isEspressoPage();
146
-    }
147
-
148
-
149
-    /**
150
-     * @param $key
151
-     * @param $value
152
-     * @return void
153
-     * @deprecated  4.10.14.p
154
-     */
155
-    public function set_notice($key, $value)
156
-    {
157
-        $this->response->setNotice($key, $value);
158
-    }
159
-
160
-
161
-    /**
162
-     * @param $key
163
-     * @return mixed
164
-     * @deprecated  4.10.14.p
165
-     */
166
-    public function get_notice($key)
167
-    {
168
-        return $this->response->getNotice($key);
169
-    }
170
-
171
-
172
-    /**
173
-     * @param $string
174
-     * @return void
175
-     * @deprecated  4.10.14.p
176
-     */
177
-    public function add_output($string)
178
-    {
179
-        $this->response->addOutput($string);
180
-    }
181
-
182
-
183
-    /**
184
-     * @return string
185
-     * @deprecated  4.10.14.p
186
-     */
187
-    public function get_output()
188
-    {
189
-        return $this->response->getOutput();
190
-    }
191
-
192
-
193
-    /**
194
-     * @param $item
195
-     * @param $key
196
-     * @deprecated  4.10.14.p
197
-     */
198
-    public function sanitize_text_field_for_array_walk(&$item, &$key)
199
-    {
200
-        $item = strpos($item, 'email') !== false
201
-            ? sanitize_email($item)
202
-            : sanitize_text_field($item);
203
-    }
204
-
205
-
206
-    /**
207
-     * @param null|bool $value
208
-     * @return void
209
-     * @deprecated  4.10.14.p
210
-     */
211
-    public function set_espresso_page($value = null)
212
-    {
213
-        $this->getCurrentPage()->setEspressoPage($value);
214
-    }
215
-
216
-
217
-    /**
218
-     * @return bool
219
-     * @deprecated  4.10.14.p
220
-     */
221
-    public function is_espresso_page()
222
-    {
223
-        return $this->getCurrentPage()->isEspressoPage();
224
-    }
225
-
226
-
227
-    /**
228
-     * returns sanitized contents of $_REQUEST
229
-     *
230
-     * @return array
231
-     * @deprecated  4.10.14.p
232
-     */
233
-    public function params()
234
-    {
235
-        return $this->request->requestParams();
236
-    }
237
-
238
-
239
-    /**
240
-     * @param      $key
241
-     * @param      $value
242
-     * @param bool $override_ee
243
-     * @return    void
244
-     * @deprecated  4.10.14.p
245
-     */
246
-    public function set($key, $value, $override_ee = false)
247
-    {
248
-        $this->request->setRequestParam($key, $value, $override_ee);
249
-    }
250
-
251
-
252
-    /**
253
-     * @param      $key
254
-     * @param null $default
255
-     * @return    mixed
256
-     * @deprecated  4.10.14.p
257
-     */
258
-    public function get($key, $default = null)
259
-    {
260
-        return $this->request->getRequestParam($key, $default);
261
-    }
262
-
263
-
264
-    /**
265
-     * check if param exists
266
-     *
267
-     * @param $key
268
-     * @return    boolean
269
-     * @deprecated  4.10.14.p
270
-     */
271
-    public function is_set($key)
272
-    {
273
-        return $this->request->requestParamIsSet($key);
274
-    }
275
-
276
-
277
-    /**
278
-     * remove param
279
-     *
280
-     * @param $key
281
-     * @return    void
282
-     * @deprecated  4.10.14.p
283
-     */
284
-    public function un_set($key)
285
-    {
286
-        $this->request->unSetRequestParam($key);
287
-    }
19
+	/**
20
+	 * @var CurrentPage
21
+	 */
22
+	private $current_page;
23
+
24
+	/**
25
+	 * @var RequestInterface
26
+	 */
27
+	private $request;
28
+
29
+	/**
30
+	 * @var ResponseInterface
31
+	 */
32
+	private $response;
33
+
34
+	/**
35
+	 * whether current request is via AJAX
36
+	 *
37
+	 * @var boolean
38
+	 */
39
+	public $ajax = false;
40
+
41
+	/**
42
+	 * whether current request is via AJAX from the frontend of the site
43
+	 *
44
+	 * @var boolean
45
+	 */
46
+	public $front_ajax = false;
47
+
48
+
49
+	/**
50
+	 * @param RequestInterface  $request
51
+	 * @param ResponseInterface $response
52
+	 */
53
+	public function __construct(RequestInterface $request, ResponseInterface $response)
54
+	{
55
+		$this->request      = $request;
56
+		$this->response     = $response;
57
+		$this->ajax         = $this->request->isAjax();
58
+		$this->front_ajax   = $this->request->isFrontAjax();
59
+		do_action('AHEE__EE_Request_Handler__construct__complete');
60
+	}
61
+
62
+
63
+	/**
64
+	 * @param WP $WP
65
+	 * @return void
66
+	 * @deprecated  4.10.14.p
67
+	 */
68
+	public function parse_request($WP = null)
69
+	{
70
+	}
71
+
72
+
73
+	private function getCurrentPage()
74
+	{
75
+		if (! $this->current_page instanceof CurrentPage) {
76
+			$this->current_page = LoaderFactory::getLoader()->getShared(CurrentPage::class);
77
+		}
78
+		return $this->current_page;
79
+	}
80
+
81
+
82
+	/**
83
+	 * @param WP $WP
84
+	 * @return void
85
+	 * @deprecated  4.10.14.p
86
+	 */
87
+	public function set_request_vars($WP = null)
88
+	{
89
+		$this->getCurrentPage()->parseQueryVars($WP);
90
+	}
91
+
92
+
93
+	/**
94
+	 * @param WP $WP
95
+	 * @return int
96
+	 * @deprecated  4.10.14.p
97
+	 */
98
+	public function get_post_id_from_request($WP = null)
99
+	{
100
+		return $this->getCurrentPage()->postId();
101
+	}
102
+
103
+
104
+	/**
105
+	 * @param WP $WP
106
+	 * @return string
107
+	 * @deprecated  4.10.14.p
108
+	 */
109
+	public function get_post_name_from_request($WP = null)
110
+	{
111
+		return $this->getCurrentPage()->postName();
112
+	}
113
+
114
+
115
+	/**
116
+	 * @param WP $WP
117
+	 * @return array
118
+	 * @deprecated  4.10.14.p
119
+	 */
120
+	public function get_post_type_from_request($WP = null)
121
+	{
122
+		return $this->getCurrentPage()->postType();
123
+	}
124
+
125
+
126
+	/**
127
+	 * Just a helper method for getting the url for the displayed page.
128
+	 *
129
+	 * @param WP $WP
130
+	 * @return string
131
+	 * @deprecated  4.10.14.p
132
+	 */
133
+	public function get_current_page_permalink($WP = null)
134
+	{
135
+		return $this->getCurrentPage()->getPermalink($WP);
136
+	}
137
+
138
+
139
+	/**
140
+	 * @return bool
141
+	 * @deprecated  4.10.14.p
142
+	 */
143
+	public function test_for_espresso_page()
144
+	{
145
+		return $this->getCurrentPage()->isEspressoPage();
146
+	}
147
+
148
+
149
+	/**
150
+	 * @param $key
151
+	 * @param $value
152
+	 * @return void
153
+	 * @deprecated  4.10.14.p
154
+	 */
155
+	public function set_notice($key, $value)
156
+	{
157
+		$this->response->setNotice($key, $value);
158
+	}
159
+
160
+
161
+	/**
162
+	 * @param $key
163
+	 * @return mixed
164
+	 * @deprecated  4.10.14.p
165
+	 */
166
+	public function get_notice($key)
167
+	{
168
+		return $this->response->getNotice($key);
169
+	}
170
+
171
+
172
+	/**
173
+	 * @param $string
174
+	 * @return void
175
+	 * @deprecated  4.10.14.p
176
+	 */
177
+	public function add_output($string)
178
+	{
179
+		$this->response->addOutput($string);
180
+	}
181
+
182
+
183
+	/**
184
+	 * @return string
185
+	 * @deprecated  4.10.14.p
186
+	 */
187
+	public function get_output()
188
+	{
189
+		return $this->response->getOutput();
190
+	}
191
+
192
+
193
+	/**
194
+	 * @param $item
195
+	 * @param $key
196
+	 * @deprecated  4.10.14.p
197
+	 */
198
+	public function sanitize_text_field_for_array_walk(&$item, &$key)
199
+	{
200
+		$item = strpos($item, 'email') !== false
201
+			? sanitize_email($item)
202
+			: sanitize_text_field($item);
203
+	}
204
+
205
+
206
+	/**
207
+	 * @param null|bool $value
208
+	 * @return void
209
+	 * @deprecated  4.10.14.p
210
+	 */
211
+	public function set_espresso_page($value = null)
212
+	{
213
+		$this->getCurrentPage()->setEspressoPage($value);
214
+	}
215
+
216
+
217
+	/**
218
+	 * @return bool
219
+	 * @deprecated  4.10.14.p
220
+	 */
221
+	public function is_espresso_page()
222
+	{
223
+		return $this->getCurrentPage()->isEspressoPage();
224
+	}
225
+
226
+
227
+	/**
228
+	 * returns sanitized contents of $_REQUEST
229
+	 *
230
+	 * @return array
231
+	 * @deprecated  4.10.14.p
232
+	 */
233
+	public function params()
234
+	{
235
+		return $this->request->requestParams();
236
+	}
237
+
238
+
239
+	/**
240
+	 * @param      $key
241
+	 * @param      $value
242
+	 * @param bool $override_ee
243
+	 * @return    void
244
+	 * @deprecated  4.10.14.p
245
+	 */
246
+	public function set($key, $value, $override_ee = false)
247
+	{
248
+		$this->request->setRequestParam($key, $value, $override_ee);
249
+	}
250
+
251
+
252
+	/**
253
+	 * @param      $key
254
+	 * @param null $default
255
+	 * @return    mixed
256
+	 * @deprecated  4.10.14.p
257
+	 */
258
+	public function get($key, $default = null)
259
+	{
260
+		return $this->request->getRequestParam($key, $default);
261
+	}
262
+
263
+
264
+	/**
265
+	 * check if param exists
266
+	 *
267
+	 * @param $key
268
+	 * @return    boolean
269
+	 * @deprecated  4.10.14.p
270
+	 */
271
+	public function is_set($key)
272
+	{
273
+		return $this->request->requestParamIsSet($key);
274
+	}
275
+
276
+
277
+	/**
278
+	 * remove param
279
+	 *
280
+	 * @param $key
281
+	 * @return    void
282
+	 * @deprecated  4.10.14.p
283
+	 */
284
+	public function un_set($key)
285
+	{
286
+		$this->request->unSetRequestParam($key);
287
+	}
288 288
 }
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/EEG_Paypal_Express.gateway.php 2 patches
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -148,10 +148,10 @@  discard block
 block discarded – undo
148 148
         $notify_url = null,
149 149
         $cancel_url = null
150 150
     ) {
151
-        if (! $this->validatePayment($payment)) {
151
+        if ( ! $this->validatePayment($payment)) {
152 152
             return $payment;
153 153
         }
154
-        if (! $this->validateTransaction($payment)) {
154
+        if ( ! $this->validateTransaction($payment)) {
155 155
             return $payment;
156 156
         }
157 157
         $this->token_request = new TokenRequest($this->_get_gateway_formatter());
@@ -190,11 +190,11 @@  discard block
 block discarded – undo
190 190
         // if the supplied transaction is valid, we'll retrieve the actual payment object from it
191 191
         // but we'll use a temporary payment for now that we can return with errors if things go wrong
192 192
         $payment = EE_Payment::new_instance();
193
-        if (! $this->validateTransaction($payment, $transaction)) {
193
+        if ( ! $this->validateTransaction($payment, $transaction)) {
194 194
             return $payment;
195 195
         }
196 196
         $payment = $transaction->last_payment();
197
-        if (! $this->validatePayment($payment)) {
197
+        if ( ! $this->validatePayment($payment)) {
198 198
             return $payment;
199 199
         }
200 200
         // payment appears to be good... so far
@@ -257,8 +257,8 @@  discard block
 block discarded – undo
257 257
             // EE will blow up if you change this
258 258
             'BUTTONSOURCE' => 'EventEspresso_SP',
259 259
         ];
260
-        $dtls         = array_merge($request_dtls, $request_params);
261
-        $this->_log_clean_request($dtls, $payment, $request_text . ' Request');
260
+        $dtls = array_merge($request_dtls, $request_params);
261
+        $this->_log_clean_request($dtls, $payment, $request_text.' Request');
262 262
         // Request Customer Details.
263 263
         $request_response = wp_remote_post(
264 264
             $this->_base_gateway_url,
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
             ]
273 273
         );
274 274
         // Log the response.
275
-        $this->log([$request_text . ' Response' => $request_response], $payment);
275
+        $this->log([$request_text.' Response' => $request_response], $payment);
276 276
         return $request_response;
277 277
     }
278 278
 
@@ -291,7 +291,7 @@  discard block
 block discarded – undo
291 291
         }
292 292
         $response_args = [];
293 293
         parse_str(urldecode($request_response['body']), $response_args);
294
-        if (! isset($response_args['ACK'])) {
294
+        if ( ! isset($response_args['ACK'])) {
295 295
             return ['status' => false, 'args' => $request_response];
296 296
         }
297 297
         if (
@@ -337,11 +337,11 @@  discard block
 block discarded – undo
337 337
     {
338 338
         $errors = [];
339 339
         $n      = 0;
340
-        while (isset($data_array[ "L_ERRORCODE{$n}" ])) {
341
-            $l_error_code    = $data_array[ "L_ERRORCODE{$n}" ] ?? '';
342
-            $l_severity_code = $data_array[ "L_SEVERITYCODE{$n}" ] ?? '';
343
-            $l_short_message = $data_array[ "L_SHORTMESSAGE{$n}" ] ?? '';
344
-            $l_long_message  = $data_array[ "L_LONGMESSAGE{$n}" ] ?? '';
340
+        while (isset($data_array["L_ERRORCODE{$n}"])) {
341
+            $l_error_code    = $data_array["L_ERRORCODE{$n}"] ?? '';
342
+            $l_severity_code = $data_array["L_SEVERITYCODE{$n}"] ?? '';
343
+            $l_short_message = $data_array["L_SHORTMESSAGE{$n}"] ?? '';
344
+            $l_long_message  = $data_array["L_LONGMESSAGE{$n}"] ?? '';
345 345
             if ($n === 0) {
346 346
                 $errors = [
347 347
                     'L_ERRORCODE'    => $l_error_code,
@@ -350,10 +350,10 @@  discard block
 block discarded – undo
350 350
                     'L_SEVERITYCODE' => $l_severity_code,
351 351
                 ];
352 352
             } else {
353
-                $errors['L_ERRORCODE']    .= ', ' . $l_error_code;
354
-                $errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
355
-                $errors['L_LONGMESSAGE']  .= ', ' . $l_long_message;
356
-                $errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
353
+                $errors['L_ERRORCODE']    .= ', '.$l_error_code;
354
+                $errors['L_SHORTMESSAGE'] .= ', '.$l_short_message;
355
+                $errors['L_LONGMESSAGE']  .= ', '.$l_long_message;
356
+                $errors['L_SEVERITYCODE'] .= ', '.$l_severity_code;
357 357
             }
358 358
             $n++;
359 359
         }
@@ -371,7 +371,7 @@  discard block
 block discarded – undo
371 371
     {
372 372
         $payment_details = $payment->details();
373 373
         // Check if we still have the token.
374
-        if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
374
+        if ( ! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
375 375
             $payment->set_status($this->_pay_model->failed_status());
376 376
             return null;
377 377
         }
@@ -411,7 +411,7 @@  discard block
 block discarded – undo
411 411
     private function paymentDeclined(EE_Payment $payment, array $checkout_response)
412 412
     {
413 413
         $gateway_response = isset($checkout_response['L_ERRORCODE'])
414
-            ? $checkout_response['L_ERRORCODE'] . '; ' . $checkout_response['L_SHORTMESSAGE']
414
+            ? $checkout_response['L_ERRORCODE'].'; '.$checkout_response['L_SHORTMESSAGE']
415 415
             : esc_html__('Error occurred while trying to Capture the funds.', 'event_espresso');
416 416
 
417 417
         $payment->set_gateway_response($gateway_response);
@@ -429,7 +429,7 @@  discard block
 block discarded – undo
429 429
     private function paymentFailed(EE_Payment $payment, array $customer_data)
430 430
     {
431 431
         $gateway_response = isset($customer_data['L_ERRORCODE'])
432
-            ? $customer_data['L_ERRORCODE'] . '; ' . $customer_data['L_SHORTMESSAGE']
432
+            ? $customer_data['L_ERRORCODE'].'; '.$customer_data['L_SHORTMESSAGE']
433 433
             : esc_html__('Error occurred while trying to get payment Details from PayPal.', 'event_espresso');
434 434
 
435 435
         $payment->set_gateway_response($gateway_response);
@@ -500,11 +500,11 @@  discard block
 block discarded – undo
500 500
             'Customer Details',
501 501
             $payment
502 502
         );
503
-        $customer_details_rstatus          = $this->_ppExpress_check_response($customer_details_request_response);
503
+        $customer_details_rstatus = $this->_ppExpress_check_response($customer_details_request_response);
504 504
         $customer_details = isset($customer_details_rstatus['args']) && is_array($customer_details_rstatus['args'])
505 505
             ? $customer_details_rstatus['args']
506 506
             : [];
507
-        if (! $customer_details_rstatus['status']) {
507
+        if ( ! $customer_details_rstatus['status']) {
508 508
             $this->paymentFailed($payment, $customer_details);
509 509
         }
510 510
         return $customer_details;
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
      */
521 521
     private function validatePayment(?EE_Payment $payment): bool
522 522
     {
523
-        if (! $payment instanceof EE_Payment) {
523
+        if ( ! $payment instanceof EE_Payment) {
524 524
             $payment = EE_Payment::new_instance();
525 525
             $payment->set_gateway_response(
526 526
                 esc_html__(
@@ -545,7 +545,7 @@  discard block
 block discarded – undo
545 545
     private function validateTransaction(EE_Payment $payment, ?EE_Transaction $transaction = null): bool
546 546
     {
547 547
         $transaction = $transaction ?? $payment->transaction();
548
-        if (! $transaction instanceof EE_Transaction) {
548
+        if ( ! $transaction instanceof EE_Transaction) {
549 549
             $payment->set_gateway_response(
550 550
                 esc_html__(
551 551
                     'Could not process this payment because it has no associated transaction.',
Please login to merge, or discard this patch.
Indentation   +544 added lines, -544 removed lines patch added patch discarded remove patch
@@ -12,548 +12,548 @@
 block discarded – undo
12 12
  */
13 13
 class EEG_Paypal_Express extends EE_Offsite_Gateway
14 14
 {
15
-    /**
16
-     * Merchant API Username.
17
-     *
18
-     * @var string
19
-     */
20
-    protected $_api_username;
21
-
22
-    /**
23
-     * Merchant API Password.
24
-     *
25
-     * @var string
26
-     */
27
-    protected $_api_password;
28
-
29
-    /**
30
-     * API Signature.
31
-     *
32
-     * @var string
33
-     */
34
-    protected $_api_signature;
35
-
36
-    /**
37
-     * Request Shipping address on PP checkout page.
38
-     *
39
-     * @var string
40
-     */
41
-    protected $_request_shipping_addr;
42
-
43
-    /**
44
-     * Business/personal logo.
45
-     *
46
-     * @var string
47
-     */
48
-    protected $_image_url = '';
49
-
50
-    /**
51
-     * gateway URL variable
52
-     *
53
-     * @var string
54
-     */
55
-    protected $_base_gateway_url = '';
56
-
57
-
58
-    /**
59
-     * number of decimal places to round numbers to when performing calculations
60
-     *
61
-     * @var integer
62
-     */
63
-    protected $decimal_precision = 6;
64
-
65
-    /**
66
-     * @var ItemizedOrder
67
-     * @since 5.0.0.p
68
-     */
69
-    protected $itemized_order;
70
-
71
-    /**
72
-     * @var TokenRequest
73
-     * @since 5.0.0.p
74
-     */
75
-    protected $token_request;
76
-
77
-
78
-    /**
79
-     * EEG_Paypal_Express constructor.
80
-     */
81
-    public function __construct()
82
-    {
83
-        require_once 'polyfills.php';
84
-        $this->_currencies_supported = [
85
-            'USD',
86
-            'AUD',
87
-            'BRL',
88
-            'CAD',
89
-            'CZK',
90
-            'DKK',
91
-            'EUR',
92
-            'HKD',
93
-            'HUF',
94
-            'ILS',
95
-            'JPY',
96
-            'MYR',
97
-            'MXN',
98
-            'NOK',
99
-            'NZD',
100
-            'PHP',
101
-            'PLN',
102
-            'GBP',
103
-            'RUB',
104
-            'SGD',
105
-            'SEK',
106
-            'CHF',
107
-            'TWD',
108
-            'THB',
109
-            'TRY',
110
-            'INR',
111
-        ];
112
-        parent::__construct();
113
-        $this->decimal_precision = EE_Registry::instance()->CFG->currency->dec_plc;
114
-    }
115
-
116
-
117
-    /**
118
-     * Sets the gateway URL variable based on whether debug mode is enabled or not.
119
-     *
120
-     * @param array $settings_array
121
-     */
122
-    public function set_settings(array $settings_array)
123
-    {
124
-        parent::set_settings($settings_array);
125
-        // Redirect URL.
126
-        $this->_base_gateway_url = $this->_debug_mode
127
-            ? 'https://api-3t.sandbox.paypal.com/nvp'
128
-            : 'https://api-3t.paypal.com/nvp';
129
-    }
130
-
131
-
132
-    /**
133
-     * @param EE_Payment $payment
134
-     * @param array       $billing_info
135
-     * @param string      $return_url
136
-     * @param string      $notify_url
137
-     * @param string      $cancel_url
138
-     * @return EE_Payment
139
-     * @throws EE_Error
140
-     * @throws ReflectionException
141
-     * @throws Exception
142
-     */
143
-    public function set_redirection_info(
144
-        $payment,
145
-        $billing_info = [],
146
-        $return_url = null,
147
-        $notify_url = null,
148
-        $cancel_url = null
149
-    ) {
150
-        if (! $this->validatePayment($payment)) {
151
-            return $payment;
152
-        }
153
-        if (! $this->validateTransaction($payment)) {
154
-            return $payment;
155
-        }
156
-        $this->token_request = new TokenRequest($this->_get_gateway_formatter());
157
-        $token_request_details = apply_filters(
158
-            'FHEE__EEG_Paypal_Express__set_redirection_info__arguments',
159
-            $this->token_request->generateDetails(
160
-                $payment,
161
-                $this->getOrderItems($payment),
162
-                $return_url ?? '',
163
-                $cancel_url ?? '',
164
-                $this->_image_url ?? '',
165
-                $this->_request_shipping_addr ?? ''
166
-            ),
167
-            $this
168
-        );
169
-        // Request PayPal token.
170
-        $token_request_response = $this->_ppExpress_request($token_request_details, 'Payment Token', $payment);
171
-        $token_request_status   = $this->_ppExpress_check_response($token_request_response);
172
-        $this->token_request->processResponse($payment, $token_request_status, $this->isInSandboxMode());
173
-
174
-        return $payment;
175
-    }
176
-
177
-
178
-    /**
179
-     * @param array           $update_info {
180
-     * @type string           $gateway_txn_id
181
-     * @type string           $status      an EEMI_Payment status
182
-     *                                     }
183
-     * @param EE_Transaction $transaction
184
-     * @return EE_Payment
185
-     * @throws Exception
186
-     */
187
-    public function handle_payment_update($update_info, $transaction): EE_Payment
188
-    {
189
-        // if the supplied transaction is valid, we'll retrieve the actual payment object from it
190
-        // but we'll use a temporary payment for now that we can return with errors if things go wrong
191
-        $payment = EE_Payment::new_instance();
192
-        if (! $this->validateTransaction($payment, $transaction)) {
193
-            return $payment;
194
-        }
195
-        $payment = $transaction->last_payment();
196
-        if (! $this->validatePayment($payment)) {
197
-            return $payment;
198
-        }
199
-        // payment appears to be good... so far
200
-        $this->log(['Return from Authorization' => $update_info], $payment);
201
-        $payment_token = $this->getPaymentToken($payment);
202
-        $customer_details = $this->requestCustomerDetails($payment, $payment_token);
203
-        // We got the PayerID so now we can Complete the transaction.
204
-        $this->processPayment($payment, $payment_token, $customer_details);
205
-
206
-        return $payment;
207
-    }
208
-
209
-
210
-    /**
211
-     * @throws Exception
212
-     */
213
-    private function getOrderItems(EE_Payment $payment, array $request_response_args = []): array
214
-    {
215
-        $this->itemized_order = new ItemizedOrder($this->_get_gateway_formatter());
216
-        try {
217
-            $itemized_order = $this->itemized_order->getExistingItemizedOrder($request_response_args);
218
-        } catch (Exception $exception) {
219
-            if (WP_DEBUG) {
220
-                throw $exception;
221
-            }
222
-            // Reset the list and log an error, maybe allow to try and generate a new list (below).
223
-            $itemized_order = [];
224
-            $this->log(
225
-                [
226
-                    esc_html__(
227
-                        'Could not generate a proper item list with:',
228
-                        'event_espresso'
229
-                    ) => $request_response_args,
230
-                ],
231
-                $payment
232
-            );
233
-        }
234
-        if (empty($itemized_order)) {
235
-            $itemized_order = $this->itemized_order->generateItemizedOrder($payment);
236
-        }
237
-        return $itemized_order;
238
-    }
239
-
240
-
241
-    /**
242
-     *  Make the Express checkout request.
243
-     *
244
-     * @param array       $request_params
245
-     * @param string      $request_text
246
-     * @param EE_Payment $payment
247
-     * @return array|WP_Error
248
-     */
249
-    public function _ppExpress_request(array $request_params, string $request_text, EE_Payment $payment)
250
-    {
251
-        $request_dtls = [
252
-            'VERSION'      => '204.0',
253
-            'USER'         => $this->_api_username,
254
-            'PWD'          => $this->_api_password,
255
-            'SIGNATURE'    => $this->_api_signature,
256
-            // EE will blow up if you change this
257
-            'BUTTONSOURCE' => 'EventEspresso_SP',
258
-        ];
259
-        $dtls         = array_merge($request_dtls, $request_params);
260
-        $this->_log_clean_request($dtls, $payment, $request_text . ' Request');
261
-        // Request Customer Details.
262
-        $request_response = wp_remote_post(
263
-            $this->_base_gateway_url,
264
-            [
265
-                'method'      => 'POST',
266
-                'timeout'     => 45,
267
-                'httpversion' => '1.1',
268
-                'cookies'     => [],
269
-                'headers'     => [],
270
-                'body'        => http_build_query($dtls),
271
-            ]
272
-        );
273
-        // Log the response.
274
-        $this->log([$request_text . ' Response' => $request_response], $payment);
275
-        return $request_response;
276
-    }
277
-
278
-
279
-    /**
280
-     *  Check the response status.
281
-     *
282
-     * @param mixed $request_response
283
-     * @return array
284
-     */
285
-    public function _ppExpress_check_response($request_response): array
286
-    {
287
-        if (is_wp_error($request_response) || empty($request_response['body'])) {
288
-            // If we got here then there was an error in this request.
289
-            return ['status' => false, 'args' => $request_response];
290
-        }
291
-        $response_args = [];
292
-        parse_str(urldecode($request_response['body']), $response_args);
293
-        if (! isset($response_args['ACK'])) {
294
-            return ['status' => false, 'args' => $request_response];
295
-        }
296
-        if (
297
-            (
298
-                isset($response_args['PAYERID'])
299
-                || isset($response_args['TOKEN'])
300
-                || isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
301
-                || (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
302
-            )
303
-            && in_array($response_args['ACK'], ['Success', 'SuccessWithWarning'], true)
304
-        ) {
305
-            // Response status OK, return response parameters for further processing.
306
-            return ['status' => true, 'args' => $response_args];
307
-        }
308
-        $errors = $this->_get_errors($response_args);
309
-        return ['status' => false, 'args' => $errors];
310
-    }
311
-
312
-
313
-    /**
314
-     *  Log a "Cleared" request.
315
-     *
316
-     * @param array       $request
317
-     * @param EE_Payment $payment
318
-     * @param string      $info
319
-     * @return void
320
-     */
321
-    private function _log_clean_request(array $request, EE_Payment $payment, string $info)
322
-    {
323
-        $cleaned_request_data = $request;
324
-        unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
325
-        $this->log([$info => $cleaned_request_data], $payment);
326
-    }
327
-
328
-
329
-    /**
330
-     *  Get error from the response data.
331
-     *
332
-     * @param array $data_array
333
-     * @return array
334
-     */
335
-    private function _get_errors(array $data_array): array
336
-    {
337
-        $errors = [];
338
-        $n      = 0;
339
-        while (isset($data_array[ "L_ERRORCODE{$n}" ])) {
340
-            $l_error_code    = $data_array[ "L_ERRORCODE{$n}" ] ?? '';
341
-            $l_severity_code = $data_array[ "L_SEVERITYCODE{$n}" ] ?? '';
342
-            $l_short_message = $data_array[ "L_SHORTMESSAGE{$n}" ] ?? '';
343
-            $l_long_message  = $data_array[ "L_LONGMESSAGE{$n}" ] ?? '';
344
-            if ($n === 0) {
345
-                $errors = [
346
-                    'L_ERRORCODE'    => $l_error_code,
347
-                    'L_SHORTMESSAGE' => $l_short_message,
348
-                    'L_LONGMESSAGE'  => $l_long_message,
349
-                    'L_SEVERITYCODE' => $l_severity_code,
350
-                ];
351
-            } else {
352
-                $errors['L_ERRORCODE']    .= ', ' . $l_error_code;
353
-                $errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
354
-                $errors['L_LONGMESSAGE']  .= ', ' . $l_long_message;
355
-                $errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
356
-            }
357
-            $n++;
358
-        }
359
-        return $errors;
360
-    }
361
-
362
-
363
-    /**
364
-     * @param EE_Payment $payment
365
-     * @return mixed|null
366
-     * @throws EE_Error
367
-     * @since   5.0.0.p
368
-     */
369
-    private function getPaymentToken(EE_Payment $payment)
370
-    {
371
-        $payment_details = $payment->details();
372
-        // Check if we still have the token.
373
-        if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
374
-            $payment->set_status($this->_pay_model->failed_status());
375
-            return null;
376
-        }
377
-        return $payment_details['TOKEN'];
378
-    }
379
-
380
-    /**
381
-     * @param EE_Payment $payment
382
-     * @param array      $checkout_response
383
-     * @param array      $customer_data
384
-     * @throws EE_Error
385
-     * @throws ReflectionException
386
-     * @since   5.0.0.p
387
-     */
388
-    private function paymentApproved(EE_Payment $payment, array $checkout_response, array $customer_data)
389
-    {
390
-        $primary_registrant = $payment->transaction()->primary_registration();
391
-        $primary_registration_code = $primary_registrant instanceof EE_Registration ?
392
-            $primary_registrant->reg_code()
393
-            : '';
394
-        $payment->set_extra_accntng($primary_registration_code);
395
-        $payment_amount = $checkout_response['PAYMENTINFO_0_AMT'] ?? 0;
396
-        $payment->set_amount((float) $payment_amount);
397
-        $payment->set_txn_id_chq_nmbr($checkout_response['PAYMENTINFO_0_TRANSACTIONID'] ?? null);
398
-        $payment->set_details($customer_data);
399
-        $payment->set_gateway_response($checkout_response['PAYMENTINFO_0_ACK'] ?? '');
400
-        $payment->set_status($this->_pay_model->approved_status());
401
-    }
402
-
403
-
404
-    /**
405
-     * @param EE_Payment $payment
406
-     * @param array      $checkout_response
407
-     * @throws EE_Error
408
-     * @since   5.0.0.p
409
-     */
410
-    private function paymentDeclined(EE_Payment $payment, array $checkout_response)
411
-    {
412
-        $gateway_response = isset($checkout_response['L_ERRORCODE'])
413
-            ? $checkout_response['L_ERRORCODE'] . '; ' . $checkout_response['L_SHORTMESSAGE']
414
-            : esc_html__('Error occurred while trying to Capture the funds.', 'event_espresso');
415
-
416
-        $payment->set_gateway_response($gateway_response);
417
-        $payment->set_details($checkout_response);
418
-        $payment->set_status($this->_pay_model->declined_status());
419
-    }
420
-
421
-
422
-    /**
423
-     * @param EE_Payment $payment
424
-     * @param array $customer_data
425
-     * @throws EE_Error
426
-     * @since   5.0.0.p
427
-     */
428
-    private function paymentFailed(EE_Payment $payment, array $customer_data)
429
-    {
430
-        $gateway_response = isset($customer_data['L_ERRORCODE'])
431
-            ? $customer_data['L_ERRORCODE'] . '; ' . $customer_data['L_SHORTMESSAGE']
432
-            : esc_html__('Error occurred while trying to get payment Details from PayPal.', 'event_espresso');
433
-
434
-        $payment->set_gateway_response($gateway_response);
435
-        $payment->set_details($customer_data);
436
-        $payment->set_status($this->_pay_model->failed_status());
437
-    }
438
-
439
-
440
-    /**
441
-     * @param EE_Payment $payment
442
-     * @param string     $payment_token
443
-     * @param array      $customer_details
444
-     * @return void
445
-     * @throws EE_Error
446
-     * @throws ReflectionException
447
-     * @throws Exception
448
-     * @since   5.0.0.p
449
-     */
450
-    private function processPayment(EE_Payment $payment, string $payment_token, array $customer_details)
451
-    {
452
-        $checkout_request_dtls = [
453
-            'METHOD'                         => 'DoExpressCheckoutPayment',
454
-            'PAYERID'                        => $customer_details['PAYERID'],
455
-            'TOKEN'                          => $payment_token,
456
-            'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
457
-            'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
458
-            'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
459
-        ];
460
-        // Include itemized list.
461
-        $itemized_list         = $this->getOrderItems($payment, $customer_details);
462
-        $checkout_request_dtls = array_merge($checkout_request_dtls, $itemized_list);
463
-        // Payment Checkout/Capture.
464
-        $checkout_request_response = $this->_ppExpress_request(
465
-            $checkout_request_dtls,
466
-            'Do Payment',
467
-            $payment
468
-        );
469
-        $checkout_request_status   = $this->_ppExpress_check_response($checkout_request_response);
470
-        $checkout_response         =
471
-            isset($checkout_request_status['args']) && is_array($checkout_request_status['args'])
472
-                ? $checkout_request_status['args']
473
-                : [];
474
-        if ($checkout_request_status['status']) {
475
-            // All is well, payment approved.
476
-            $this->paymentApproved($payment, $checkout_response, $customer_details);
477
-        } else {
478
-            $this->paymentDeclined($payment, $checkout_response);
479
-        }
480
-    }
481
-
482
-
483
-    /**
484
-     * @param EE_Payment $payment
485
-     * @param string $payment_token
486
-     * @return array
487
-     * @throws EE_Error
488
-     * @since   5.0.0.p
489
-     */
490
-    private function requestCustomerDetails(EE_Payment $payment, string $payment_token): array
491
-    {
492
-        $customer_details_request_dtls = [
493
-            'METHOD' => 'GetExpressCheckoutDetails',
494
-            'TOKEN'  => $payment_token,
495
-        ];
496
-        // Request Customer Details.
497
-        $customer_details_request_response = $this->_ppExpress_request(
498
-            $customer_details_request_dtls,
499
-            'Customer Details',
500
-            $payment
501
-        );
502
-        $customer_details_rstatus          = $this->_ppExpress_check_response($customer_details_request_response);
503
-        $customer_details = isset($customer_details_rstatus['args']) && is_array($customer_details_rstatus['args'])
504
-            ? $customer_details_rstatus['args']
505
-            : [];
506
-        if (! $customer_details_rstatus['status']) {
507
-            $this->paymentFailed($payment, $customer_details);
508
-        }
509
-        return $customer_details;
510
-    }
511
-
512
-
513
-
514
-    /**
515
-     * @param EE_Payment|null $payment
516
-     * @return bool
517
-     * @throws EE_Error
518
-     * @since   5.0.0.p
519
-     */
520
-    private function validatePayment(?EE_Payment $payment): bool
521
-    {
522
-        if (! $payment instanceof EE_Payment) {
523
-            $payment = EE_Payment::new_instance();
524
-            $payment->set_gateway_response(
525
-                esc_html__(
526
-                    'An error occurred while trying to process the payment.',
527
-                    'event_espresso'
528
-                )
529
-            );
530
-            $payment->set_status($this->_pay_model->failed_status());
531
-            return false;
532
-        }
533
-        return true;
534
-    }
535
-
536
-
537
-    /**
538
-     * @param EE_Payment          $payment
539
-     * @param EE_Transaction|null $transaction
540
-     * @return bool
541
-     * @throws EE_Error
542
-     * @since   5.0.0.p
543
-     */
544
-    private function validateTransaction(EE_Payment $payment, ?EE_Transaction $transaction = null): bool
545
-    {
546
-        $transaction = $transaction ?? $payment->transaction();
547
-        if (! $transaction instanceof EE_Transaction) {
548
-            $payment->set_gateway_response(
549
-                esc_html__(
550
-                    'Could not process this payment because it has no associated transaction.',
551
-                    'event_espresso'
552
-                )
553
-            );
554
-            $payment->set_status($this->_pay_model->failed_status());
555
-            return false;
556
-        }
557
-        return true;
558
-    }
15
+	/**
16
+	 * Merchant API Username.
17
+	 *
18
+	 * @var string
19
+	 */
20
+	protected $_api_username;
21
+
22
+	/**
23
+	 * Merchant API Password.
24
+	 *
25
+	 * @var string
26
+	 */
27
+	protected $_api_password;
28
+
29
+	/**
30
+	 * API Signature.
31
+	 *
32
+	 * @var string
33
+	 */
34
+	protected $_api_signature;
35
+
36
+	/**
37
+	 * Request Shipping address on PP checkout page.
38
+	 *
39
+	 * @var string
40
+	 */
41
+	protected $_request_shipping_addr;
42
+
43
+	/**
44
+	 * Business/personal logo.
45
+	 *
46
+	 * @var string
47
+	 */
48
+	protected $_image_url = '';
49
+
50
+	/**
51
+	 * gateway URL variable
52
+	 *
53
+	 * @var string
54
+	 */
55
+	protected $_base_gateway_url = '';
56
+
57
+
58
+	/**
59
+	 * number of decimal places to round numbers to when performing calculations
60
+	 *
61
+	 * @var integer
62
+	 */
63
+	protected $decimal_precision = 6;
64
+
65
+	/**
66
+	 * @var ItemizedOrder
67
+	 * @since 5.0.0.p
68
+	 */
69
+	protected $itemized_order;
70
+
71
+	/**
72
+	 * @var TokenRequest
73
+	 * @since 5.0.0.p
74
+	 */
75
+	protected $token_request;
76
+
77
+
78
+	/**
79
+	 * EEG_Paypal_Express constructor.
80
+	 */
81
+	public function __construct()
82
+	{
83
+		require_once 'polyfills.php';
84
+		$this->_currencies_supported = [
85
+			'USD',
86
+			'AUD',
87
+			'BRL',
88
+			'CAD',
89
+			'CZK',
90
+			'DKK',
91
+			'EUR',
92
+			'HKD',
93
+			'HUF',
94
+			'ILS',
95
+			'JPY',
96
+			'MYR',
97
+			'MXN',
98
+			'NOK',
99
+			'NZD',
100
+			'PHP',
101
+			'PLN',
102
+			'GBP',
103
+			'RUB',
104
+			'SGD',
105
+			'SEK',
106
+			'CHF',
107
+			'TWD',
108
+			'THB',
109
+			'TRY',
110
+			'INR',
111
+		];
112
+		parent::__construct();
113
+		$this->decimal_precision = EE_Registry::instance()->CFG->currency->dec_plc;
114
+	}
115
+
116
+
117
+	/**
118
+	 * Sets the gateway URL variable based on whether debug mode is enabled or not.
119
+	 *
120
+	 * @param array $settings_array
121
+	 */
122
+	public function set_settings(array $settings_array)
123
+	{
124
+		parent::set_settings($settings_array);
125
+		// Redirect URL.
126
+		$this->_base_gateway_url = $this->_debug_mode
127
+			? 'https://api-3t.sandbox.paypal.com/nvp'
128
+			: 'https://api-3t.paypal.com/nvp';
129
+	}
130
+
131
+
132
+	/**
133
+	 * @param EE_Payment $payment
134
+	 * @param array       $billing_info
135
+	 * @param string      $return_url
136
+	 * @param string      $notify_url
137
+	 * @param string      $cancel_url
138
+	 * @return EE_Payment
139
+	 * @throws EE_Error
140
+	 * @throws ReflectionException
141
+	 * @throws Exception
142
+	 */
143
+	public function set_redirection_info(
144
+		$payment,
145
+		$billing_info = [],
146
+		$return_url = null,
147
+		$notify_url = null,
148
+		$cancel_url = null
149
+	) {
150
+		if (! $this->validatePayment($payment)) {
151
+			return $payment;
152
+		}
153
+		if (! $this->validateTransaction($payment)) {
154
+			return $payment;
155
+		}
156
+		$this->token_request = new TokenRequest($this->_get_gateway_formatter());
157
+		$token_request_details = apply_filters(
158
+			'FHEE__EEG_Paypal_Express__set_redirection_info__arguments',
159
+			$this->token_request->generateDetails(
160
+				$payment,
161
+				$this->getOrderItems($payment),
162
+				$return_url ?? '',
163
+				$cancel_url ?? '',
164
+				$this->_image_url ?? '',
165
+				$this->_request_shipping_addr ?? ''
166
+			),
167
+			$this
168
+		);
169
+		// Request PayPal token.
170
+		$token_request_response = $this->_ppExpress_request($token_request_details, 'Payment Token', $payment);
171
+		$token_request_status   = $this->_ppExpress_check_response($token_request_response);
172
+		$this->token_request->processResponse($payment, $token_request_status, $this->isInSandboxMode());
173
+
174
+		return $payment;
175
+	}
176
+
177
+
178
+	/**
179
+	 * @param array           $update_info {
180
+	 * @type string           $gateway_txn_id
181
+	 * @type string           $status      an EEMI_Payment status
182
+	 *                                     }
183
+	 * @param EE_Transaction $transaction
184
+	 * @return EE_Payment
185
+	 * @throws Exception
186
+	 */
187
+	public function handle_payment_update($update_info, $transaction): EE_Payment
188
+	{
189
+		// if the supplied transaction is valid, we'll retrieve the actual payment object from it
190
+		// but we'll use a temporary payment for now that we can return with errors if things go wrong
191
+		$payment = EE_Payment::new_instance();
192
+		if (! $this->validateTransaction($payment, $transaction)) {
193
+			return $payment;
194
+		}
195
+		$payment = $transaction->last_payment();
196
+		if (! $this->validatePayment($payment)) {
197
+			return $payment;
198
+		}
199
+		// payment appears to be good... so far
200
+		$this->log(['Return from Authorization' => $update_info], $payment);
201
+		$payment_token = $this->getPaymentToken($payment);
202
+		$customer_details = $this->requestCustomerDetails($payment, $payment_token);
203
+		// We got the PayerID so now we can Complete the transaction.
204
+		$this->processPayment($payment, $payment_token, $customer_details);
205
+
206
+		return $payment;
207
+	}
208
+
209
+
210
+	/**
211
+	 * @throws Exception
212
+	 */
213
+	private function getOrderItems(EE_Payment $payment, array $request_response_args = []): array
214
+	{
215
+		$this->itemized_order = new ItemizedOrder($this->_get_gateway_formatter());
216
+		try {
217
+			$itemized_order = $this->itemized_order->getExistingItemizedOrder($request_response_args);
218
+		} catch (Exception $exception) {
219
+			if (WP_DEBUG) {
220
+				throw $exception;
221
+			}
222
+			// Reset the list and log an error, maybe allow to try and generate a new list (below).
223
+			$itemized_order = [];
224
+			$this->log(
225
+				[
226
+					esc_html__(
227
+						'Could not generate a proper item list with:',
228
+						'event_espresso'
229
+					) => $request_response_args,
230
+				],
231
+				$payment
232
+			);
233
+		}
234
+		if (empty($itemized_order)) {
235
+			$itemized_order = $this->itemized_order->generateItemizedOrder($payment);
236
+		}
237
+		return $itemized_order;
238
+	}
239
+
240
+
241
+	/**
242
+	 *  Make the Express checkout request.
243
+	 *
244
+	 * @param array       $request_params
245
+	 * @param string      $request_text
246
+	 * @param EE_Payment $payment
247
+	 * @return array|WP_Error
248
+	 */
249
+	public function _ppExpress_request(array $request_params, string $request_text, EE_Payment $payment)
250
+	{
251
+		$request_dtls = [
252
+			'VERSION'      => '204.0',
253
+			'USER'         => $this->_api_username,
254
+			'PWD'          => $this->_api_password,
255
+			'SIGNATURE'    => $this->_api_signature,
256
+			// EE will blow up if you change this
257
+			'BUTTONSOURCE' => 'EventEspresso_SP',
258
+		];
259
+		$dtls         = array_merge($request_dtls, $request_params);
260
+		$this->_log_clean_request($dtls, $payment, $request_text . ' Request');
261
+		// Request Customer Details.
262
+		$request_response = wp_remote_post(
263
+			$this->_base_gateway_url,
264
+			[
265
+				'method'      => 'POST',
266
+				'timeout'     => 45,
267
+				'httpversion' => '1.1',
268
+				'cookies'     => [],
269
+				'headers'     => [],
270
+				'body'        => http_build_query($dtls),
271
+			]
272
+		);
273
+		// Log the response.
274
+		$this->log([$request_text . ' Response' => $request_response], $payment);
275
+		return $request_response;
276
+	}
277
+
278
+
279
+	/**
280
+	 *  Check the response status.
281
+	 *
282
+	 * @param mixed $request_response
283
+	 * @return array
284
+	 */
285
+	public function _ppExpress_check_response($request_response): array
286
+	{
287
+		if (is_wp_error($request_response) || empty($request_response['body'])) {
288
+			// If we got here then there was an error in this request.
289
+			return ['status' => false, 'args' => $request_response];
290
+		}
291
+		$response_args = [];
292
+		parse_str(urldecode($request_response['body']), $response_args);
293
+		if (! isset($response_args['ACK'])) {
294
+			return ['status' => false, 'args' => $request_response];
295
+		}
296
+		if (
297
+			(
298
+				isset($response_args['PAYERID'])
299
+				|| isset($response_args['TOKEN'])
300
+				|| isset($response_args['PAYMENTINFO_0_TRANSACTIONID'])
301
+				|| (isset($response_args['PAYMENTSTATUS']) && $response_args['PAYMENTSTATUS'] === 'Completed')
302
+			)
303
+			&& in_array($response_args['ACK'], ['Success', 'SuccessWithWarning'], true)
304
+		) {
305
+			// Response status OK, return response parameters for further processing.
306
+			return ['status' => true, 'args' => $response_args];
307
+		}
308
+		$errors = $this->_get_errors($response_args);
309
+		return ['status' => false, 'args' => $errors];
310
+	}
311
+
312
+
313
+	/**
314
+	 *  Log a "Cleared" request.
315
+	 *
316
+	 * @param array       $request
317
+	 * @param EE_Payment $payment
318
+	 * @param string      $info
319
+	 * @return void
320
+	 */
321
+	private function _log_clean_request(array $request, EE_Payment $payment, string $info)
322
+	{
323
+		$cleaned_request_data = $request;
324
+		unset($cleaned_request_data['PWD'], $cleaned_request_data['USER'], $cleaned_request_data['SIGNATURE']);
325
+		$this->log([$info => $cleaned_request_data], $payment);
326
+	}
327
+
328
+
329
+	/**
330
+	 *  Get error from the response data.
331
+	 *
332
+	 * @param array $data_array
333
+	 * @return array
334
+	 */
335
+	private function _get_errors(array $data_array): array
336
+	{
337
+		$errors = [];
338
+		$n      = 0;
339
+		while (isset($data_array[ "L_ERRORCODE{$n}" ])) {
340
+			$l_error_code    = $data_array[ "L_ERRORCODE{$n}" ] ?? '';
341
+			$l_severity_code = $data_array[ "L_SEVERITYCODE{$n}" ] ?? '';
342
+			$l_short_message = $data_array[ "L_SHORTMESSAGE{$n}" ] ?? '';
343
+			$l_long_message  = $data_array[ "L_LONGMESSAGE{$n}" ] ?? '';
344
+			if ($n === 0) {
345
+				$errors = [
346
+					'L_ERRORCODE'    => $l_error_code,
347
+					'L_SHORTMESSAGE' => $l_short_message,
348
+					'L_LONGMESSAGE'  => $l_long_message,
349
+					'L_SEVERITYCODE' => $l_severity_code,
350
+				];
351
+			} else {
352
+				$errors['L_ERRORCODE']    .= ', ' . $l_error_code;
353
+				$errors['L_SHORTMESSAGE'] .= ', ' . $l_short_message;
354
+				$errors['L_LONGMESSAGE']  .= ', ' . $l_long_message;
355
+				$errors['L_SEVERITYCODE'] .= ', ' . $l_severity_code;
356
+			}
357
+			$n++;
358
+		}
359
+		return $errors;
360
+	}
361
+
362
+
363
+	/**
364
+	 * @param EE_Payment $payment
365
+	 * @return mixed|null
366
+	 * @throws EE_Error
367
+	 * @since   5.0.0.p
368
+	 */
369
+	private function getPaymentToken(EE_Payment $payment)
370
+	{
371
+		$payment_details = $payment->details();
372
+		// Check if we still have the token.
373
+		if (! isset($payment_details['TOKEN']) || empty($payment_details['TOKEN'])) {
374
+			$payment->set_status($this->_pay_model->failed_status());
375
+			return null;
376
+		}
377
+		return $payment_details['TOKEN'];
378
+	}
379
+
380
+	/**
381
+	 * @param EE_Payment $payment
382
+	 * @param array      $checkout_response
383
+	 * @param array      $customer_data
384
+	 * @throws EE_Error
385
+	 * @throws ReflectionException
386
+	 * @since   5.0.0.p
387
+	 */
388
+	private function paymentApproved(EE_Payment $payment, array $checkout_response, array $customer_data)
389
+	{
390
+		$primary_registrant = $payment->transaction()->primary_registration();
391
+		$primary_registration_code = $primary_registrant instanceof EE_Registration ?
392
+			$primary_registrant->reg_code()
393
+			: '';
394
+		$payment->set_extra_accntng($primary_registration_code);
395
+		$payment_amount = $checkout_response['PAYMENTINFO_0_AMT'] ?? 0;
396
+		$payment->set_amount((float) $payment_amount);
397
+		$payment->set_txn_id_chq_nmbr($checkout_response['PAYMENTINFO_0_TRANSACTIONID'] ?? null);
398
+		$payment->set_details($customer_data);
399
+		$payment->set_gateway_response($checkout_response['PAYMENTINFO_0_ACK'] ?? '');
400
+		$payment->set_status($this->_pay_model->approved_status());
401
+	}
402
+
403
+
404
+	/**
405
+	 * @param EE_Payment $payment
406
+	 * @param array      $checkout_response
407
+	 * @throws EE_Error
408
+	 * @since   5.0.0.p
409
+	 */
410
+	private function paymentDeclined(EE_Payment $payment, array $checkout_response)
411
+	{
412
+		$gateway_response = isset($checkout_response['L_ERRORCODE'])
413
+			? $checkout_response['L_ERRORCODE'] . '; ' . $checkout_response['L_SHORTMESSAGE']
414
+			: esc_html__('Error occurred while trying to Capture the funds.', 'event_espresso');
415
+
416
+		$payment->set_gateway_response($gateway_response);
417
+		$payment->set_details($checkout_response);
418
+		$payment->set_status($this->_pay_model->declined_status());
419
+	}
420
+
421
+
422
+	/**
423
+	 * @param EE_Payment $payment
424
+	 * @param array $customer_data
425
+	 * @throws EE_Error
426
+	 * @since   5.0.0.p
427
+	 */
428
+	private function paymentFailed(EE_Payment $payment, array $customer_data)
429
+	{
430
+		$gateway_response = isset($customer_data['L_ERRORCODE'])
431
+			? $customer_data['L_ERRORCODE'] . '; ' . $customer_data['L_SHORTMESSAGE']
432
+			: esc_html__('Error occurred while trying to get payment Details from PayPal.', 'event_espresso');
433
+
434
+		$payment->set_gateway_response($gateway_response);
435
+		$payment->set_details($customer_data);
436
+		$payment->set_status($this->_pay_model->failed_status());
437
+	}
438
+
439
+
440
+	/**
441
+	 * @param EE_Payment $payment
442
+	 * @param string     $payment_token
443
+	 * @param array      $customer_details
444
+	 * @return void
445
+	 * @throws EE_Error
446
+	 * @throws ReflectionException
447
+	 * @throws Exception
448
+	 * @since   5.0.0.p
449
+	 */
450
+	private function processPayment(EE_Payment $payment, string $payment_token, array $customer_details)
451
+	{
452
+		$checkout_request_dtls = [
453
+			'METHOD'                         => 'DoExpressCheckoutPayment',
454
+			'PAYERID'                        => $customer_details['PAYERID'],
455
+			'TOKEN'                          => $payment_token,
456
+			'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
457
+			'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
458
+			'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
459
+		];
460
+		// Include itemized list.
461
+		$itemized_list         = $this->getOrderItems($payment, $customer_details);
462
+		$checkout_request_dtls = array_merge($checkout_request_dtls, $itemized_list);
463
+		// Payment Checkout/Capture.
464
+		$checkout_request_response = $this->_ppExpress_request(
465
+			$checkout_request_dtls,
466
+			'Do Payment',
467
+			$payment
468
+		);
469
+		$checkout_request_status   = $this->_ppExpress_check_response($checkout_request_response);
470
+		$checkout_response         =
471
+			isset($checkout_request_status['args']) && is_array($checkout_request_status['args'])
472
+				? $checkout_request_status['args']
473
+				: [];
474
+		if ($checkout_request_status['status']) {
475
+			// All is well, payment approved.
476
+			$this->paymentApproved($payment, $checkout_response, $customer_details);
477
+		} else {
478
+			$this->paymentDeclined($payment, $checkout_response);
479
+		}
480
+	}
481
+
482
+
483
+	/**
484
+	 * @param EE_Payment $payment
485
+	 * @param string $payment_token
486
+	 * @return array
487
+	 * @throws EE_Error
488
+	 * @since   5.0.0.p
489
+	 */
490
+	private function requestCustomerDetails(EE_Payment $payment, string $payment_token): array
491
+	{
492
+		$customer_details_request_dtls = [
493
+			'METHOD' => 'GetExpressCheckoutDetails',
494
+			'TOKEN'  => $payment_token,
495
+		];
496
+		// Request Customer Details.
497
+		$customer_details_request_response = $this->_ppExpress_request(
498
+			$customer_details_request_dtls,
499
+			'Customer Details',
500
+			$payment
501
+		);
502
+		$customer_details_rstatus          = $this->_ppExpress_check_response($customer_details_request_response);
503
+		$customer_details = isset($customer_details_rstatus['args']) && is_array($customer_details_rstatus['args'])
504
+			? $customer_details_rstatus['args']
505
+			: [];
506
+		if (! $customer_details_rstatus['status']) {
507
+			$this->paymentFailed($payment, $customer_details);
508
+		}
509
+		return $customer_details;
510
+	}
511
+
512
+
513
+
514
+	/**
515
+	 * @param EE_Payment|null $payment
516
+	 * @return bool
517
+	 * @throws EE_Error
518
+	 * @since   5.0.0.p
519
+	 */
520
+	private function validatePayment(?EE_Payment $payment): bool
521
+	{
522
+		if (! $payment instanceof EE_Payment) {
523
+			$payment = EE_Payment::new_instance();
524
+			$payment->set_gateway_response(
525
+				esc_html__(
526
+					'An error occurred while trying to process the payment.',
527
+					'event_espresso'
528
+				)
529
+			);
530
+			$payment->set_status($this->_pay_model->failed_status());
531
+			return false;
532
+		}
533
+		return true;
534
+	}
535
+
536
+
537
+	/**
538
+	 * @param EE_Payment          $payment
539
+	 * @param EE_Transaction|null $transaction
540
+	 * @return bool
541
+	 * @throws EE_Error
542
+	 * @since   5.0.0.p
543
+	 */
544
+	private function validateTransaction(EE_Payment $payment, ?EE_Transaction $transaction = null): bool
545
+	{
546
+		$transaction = $transaction ?? $payment->transaction();
547
+		if (! $transaction instanceof EE_Transaction) {
548
+			$payment->set_gateway_response(
549
+				esc_html__(
550
+					'Could not process this payment because it has no associated transaction.',
551
+					'event_espresso'
552
+				)
553
+			);
554
+			$payment->set_status($this->_pay_model->failed_status());
555
+			return false;
556
+		}
557
+		return true;
558
+	}
559 559
 }
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/ItemizedOrder.php 2 patches
Spacing   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
                     strpos($arg_key, 'PAYMENTREQUEST_') !== false
82 82
                     && strpos($arg_key, 'NOTIFYURL') === false
83 83
                 ) {
84
-                    $this->order_items[ $arg_key ] = $arg_val;
84
+                    $this->order_items[$arg_key] = $arg_val;
85 85
                 }
86 86
             }
87 87
             // If we only get a few Items then something is not right.
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
         // Digital item is sold.
181 181
         $this->order_items['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
182 182
         // Item's sales S/H and tax amount.
183
-        $this->order_items['PAYMENTREQUEST_0_ITEMAMT']     = $this->gateway_data_formatter->formatCurrency(
183
+        $this->order_items['PAYMENTREQUEST_0_ITEMAMT'] = $this->gateway_data_formatter->formatCurrency(
184 184
             $this->payment->amount(),
185 185
             $this->decimal_precision
186 186
         );
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
                 if (EEH_Money::compare_floats($line_item->pretaxTotal(), '0.00', '==')) {
207 207
                     continue;
208 208
                 }
209
-                $unit_price         = $this->gateway_data_formatter->formatCurrency(
209
+                $unit_price = $this->gateway_data_formatter->formatCurrency(
210 210
                     $line_item->unit_price(),
211 211
                     $this->decimal_precision
212 212
                 );
@@ -217,25 +217,25 @@  discard block
 block discarded – undo
217 217
                     $line_item_quantity = 1;
218 218
                 }
219 219
                 // Item Name.
220
-                $this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
220
+                $this->order_items["L_PAYMENTREQUEST_0_NAME{$item_num}"] = mb_strcut(
221 221
                     $this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
222 222
                     0,
223 223
                     127
224 224
                 );
225 225
                 // Item description.
226
-                $this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = mb_strcut(
226
+                $this->order_items["L_PAYMENTREQUEST_0_DESC{$item_num}"] = mb_strcut(
227 227
                     $this->gateway_data_formatter->formatLineItemDesc($line_item, $this->payment),
228 228
                     0,
229 229
                     127
230 230
                 );
231 231
                 // Cost of individual item.
232
-                $this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $unit_price;
232
+                $this->order_items["L_PAYMENTREQUEST_0_AMT{$item_num}"] = $unit_price;
233 233
                 // Item Number.
234
-                $this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
234
+                $this->order_items["L_PAYMENTREQUEST_0_NUMBER{$item_num}"] = $item_num + 1;
235 235
                 // Item quantity.
236
-                $this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = $line_item_quantity;
236
+                $this->order_items["L_PAYMENTREQUEST_0_QTY{$item_num}"] = $line_item_quantity;
237 237
                 // Digital item is sold.
238
-                $this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
238
+                $this->order_items["L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}"] = 'Physical';
239 239
                 // add item total to order sum
240 240
                 $this->itemized_order_sum += $unit_price * $line_item_quantity;
241 241
                 ++$item_num;
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
         // add the difference as an extra line item.
282 282
         if (EEH_Money::compare_floats($itemized_order_sum_difference, 0, '!=')) {
283 283
             // Item Name.
284
-            $this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
284
+            $this->order_items["L_PAYMENTREQUEST_0_NAME{$item_num}"] = mb_strcut(
285 285
                 esc_html__(
286 286
                     'Other (promotion/surcharge/cancellation)',
287 287
                     'event_espresso'
@@ -290,18 +290,18 @@  discard block
 block discarded – undo
290 290
                 127
291 291
             );
292 292
             // Item description.
293
-            $this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = '';
293
+            $this->order_items["L_PAYMENTREQUEST_0_DESC{$item_num}"] = '';
294 294
             // Cost of individual item.
295
-            $this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $this->gateway_data_formatter->formatCurrency(
295
+            $this->order_items["L_PAYMENTREQUEST_0_AMT{$item_num}"] = $this->gateway_data_formatter->formatCurrency(
296 296
                 $itemized_order_sum_difference,
297 297
                 $this->decimal_precision
298 298
             );
299 299
             // Item Number.
300
-            $this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
300
+            $this->order_items["L_PAYMENTREQUEST_0_NUMBER{$item_num}"] = $item_num + 1;
301 301
             // Item quantity.
302
-            $this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = 1;
302
+            $this->order_items["L_PAYMENTREQUEST_0_QTY{$item_num}"] = 1;
303 303
             // Digital item is sold.
304
-            $this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
304
+            $this->order_items["L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}"] = 'Physical';
305 305
         }
306 306
     }
307 307
 }
Please login to merge, or discard this patch.
Indentation   +265 added lines, -265 removed lines patch added patch discarded remove patch
@@ -14,292 +14,292 @@
 block discarded – undo
14 14
 
15 15
 class ItemizedOrder
16 16
 {
17
-    /**
18
-     * number of decimal places to round numbers to when performing calculations
19
-     *
20
-     * @var integer
21
-     */
22
-    protected $decimal_precision = 6;
17
+	/**
18
+	 * number of decimal places to round numbers to when performing calculations
19
+	 *
20
+	 * @var integer
21
+	 */
22
+	protected $decimal_precision = 6;
23 23
 
24
-    /**
25
-     * @var GatewayDataFormatterInterface
26
-     */
27
-    protected $gateway_data_formatter;
24
+	/**
25
+	 * @var GatewayDataFormatterInterface
26
+	 */
27
+	protected $gateway_data_formatter;
28 28
 
29
-    /**
30
-     * keeps track of exactly how much the itemized order amount equals
31
-     *
32
-     * @var float
33
-     */
34
-    private $itemized_order_sum = 0.00;
29
+	/**
30
+	 * keeps track of exactly how much the itemized order amount equals
31
+	 *
32
+	 * @var float
33
+	 */
34
+	private $itemized_order_sum = 0.00;
35 35
 
36
-    /**
37
-     * @var array
38
-     */
39
-    private $order_items;
36
+	/**
37
+	 * @var array
38
+	 */
39
+	private $order_items;
40 40
 
41
-    /**
42
-     * the payment being processed
43
-     *
44
-     * @var EE_Payment
45
-     */
46
-    protected $payment;
41
+	/**
42
+	 * the payment being processed
43
+	 *
44
+	 * @var EE_Payment
45
+	 */
46
+	protected $payment;
47 47
 
48
-    /**
49
-     * @var EE_Transaction
50
-     */
51
-    private $transaction;
48
+	/**
49
+	 * @var EE_Transaction
50
+	 */
51
+	private $transaction;
52 52
 
53 53
 
54
-    /**
55
-     * @param GatewayDataFormatterInterface $gateway_data_formatter
56
-     */
57
-    public function __construct(GatewayDataFormatterInterface $gateway_data_formatter)
58
-    {
59
-        $this->decimal_precision      = EE_Registry::instance()->CFG->currency->dec_plc;
60
-        $this->gateway_data_formatter = $gateway_data_formatter;
61
-        $this->order_items            = [];
62
-    }
54
+	/**
55
+	 * @param GatewayDataFormatterInterface $gateway_data_formatter
56
+	 */
57
+	public function __construct(GatewayDataFormatterInterface $gateway_data_formatter)
58
+	{
59
+		$this->decimal_precision      = EE_Registry::instance()->CFG->currency->dec_plc;
60
+		$this->gateway_data_formatter = $gateway_data_formatter;
61
+		$this->order_items            = [];
62
+	}
63 63
 
64 64
 
65
-    /**
66
-     * @param array $request_response_args
67
-     * @return array
68
-     */
69
-    public function getExistingItemizedOrder(array $request_response_args): array
70
-    {
71
-        // If we have data from a previous communication with PP (on this transaction) we may use that for our list...
72
-        if (
73
-            ! empty($request_response_args)
74
-            && array_key_exists('L_PAYMENTREQUEST_0_AMT0', $request_response_args)
75
-            && array_key_exists('PAYMENTREQUEST_0_ITEMAMT', $request_response_args)
76
-        ) {
77
-            foreach ($request_response_args as $arg_key => $arg_val) {
78
-                if (
79
-                    strpos($arg_key, 'PAYMENTREQUEST_') !== false
80
-                    && strpos($arg_key, 'NOTIFYURL') === false
81
-                ) {
82
-                    $this->order_items[ $arg_key ] = $arg_val;
83
-                }
84
-            }
85
-            // If we only get a few Items then something is not right.
86
-            if (count($this->order_items) < 3) {
87
-                throw new RuntimeException(
88
-                    sprintf(
89
-                        esc_html__(
90
-                            'Unable to continue with the checkout because a proper purchase list could not be generated. The purchased list we could have sent was %1$s',
91
-                            'event_espresso'
92
-                        ),
93
-                        wp_json_encode($this->order_items)
94
-                    )
95
-                );
96
-            }
97
-        }
98
-        return $this->order_items;
99
-    }
65
+	/**
66
+	 * @param array $request_response_args
67
+	 * @return array
68
+	 */
69
+	public function getExistingItemizedOrder(array $request_response_args): array
70
+	{
71
+		// If we have data from a previous communication with PP (on this transaction) we may use that for our list...
72
+		if (
73
+			! empty($request_response_args)
74
+			&& array_key_exists('L_PAYMENTREQUEST_0_AMT0', $request_response_args)
75
+			&& array_key_exists('PAYMENTREQUEST_0_ITEMAMT', $request_response_args)
76
+		) {
77
+			foreach ($request_response_args as $arg_key => $arg_val) {
78
+				if (
79
+					strpos($arg_key, 'PAYMENTREQUEST_') !== false
80
+					&& strpos($arg_key, 'NOTIFYURL') === false
81
+				) {
82
+					$this->order_items[ $arg_key ] = $arg_val;
83
+				}
84
+			}
85
+			// If we only get a few Items then something is not right.
86
+			if (count($this->order_items) < 3) {
87
+				throw new RuntimeException(
88
+					sprintf(
89
+						esc_html__(
90
+							'Unable to continue with the checkout because a proper purchase list could not be generated. The purchased list we could have sent was %1$s',
91
+							'event_espresso'
92
+						),
93
+						wp_json_encode($this->order_items)
94
+					)
95
+				);
96
+			}
97
+		}
98
+		return $this->order_items;
99
+	}
100 100
 
101 101
 
102
-    /**
103
-     *  Make a list of items that are in the giver transaction.
104
-     *
105
-     * @param EE_Payment $payment
106
-     * @return array
107
-     * @throws EE_Error
108
-     * @throws ReflectionException
109
-     */
110
-    public function generateItemizedOrder(EE_Payment $payment): array
111
-    {
112
-        $this->payment     = $payment;
113
-        $this->transaction = $this->payment->transaction();
114
-        // reset order items
115
-        $this->order_items = [];
116
-        if ($this->paymentIsForTransactionTotal()) {
117
-            $this->itemizeOrderForFullPayment();
118
-        } else {
119
-            $this->handlePartialPayment();
120
-        }
121
-        return $this->order_items;
122
-    }
102
+	/**
103
+	 *  Make a list of items that are in the giver transaction.
104
+	 *
105
+	 * @param EE_Payment $payment
106
+	 * @return array
107
+	 * @throws EE_Error
108
+	 * @throws ReflectionException
109
+	 */
110
+	public function generateItemizedOrder(EE_Payment $payment): array
111
+	{
112
+		$this->payment     = $payment;
113
+		$this->transaction = $this->payment->transaction();
114
+		// reset order items
115
+		$this->order_items = [];
116
+		if ($this->paymentIsForTransactionTotal()) {
117
+			$this->itemizeOrderForFullPayment();
118
+		} else {
119
+			$this->handlePartialPayment();
120
+		}
121
+		return $this->order_items;
122
+	}
123 123
 
124 124
 
125
-    /**
126
-     * @return bool
127
-     * @throws ReflectionException
128
-     * @throws EE_Error
129
-     */
130
-    private function paymentIsForTransactionTotal(): bool
131
-    {
132
-        return EEH_Money::compare_floats($this->payment->amount(), $this->transaction->total(), '==');
133
-    }
125
+	/**
126
+	 * @return bool
127
+	 * @throws ReflectionException
128
+	 * @throws EE_Error
129
+	 */
130
+	private function paymentIsForTransactionTotal(): bool
131
+	{
132
+		return EEH_Money::compare_floats($this->payment->amount(), $this->transaction->total(), '==');
133
+	}
134 134
 
135 135
 
136
-    /**
137
-     * @return void
138
-     * @throws EE_Error
139
-     * @throws ReflectionException
140
-     */
141
-    private function itemizeOrderForFullPayment()
142
-    {
143
-        $item_num        = 0;
144
-        $total_line_item = $this->transaction->total_line_item();
145
-        $item_num        = $this->addOrderItemsForLineItems($total_line_item, $item_num);
146
-        $this->addOrderItemsForAdditionalCharges($total_line_item);
147
-        $this->handleItemizedOrderSumDifference($total_line_item, $item_num);
148
-    }
136
+	/**
137
+	 * @return void
138
+	 * @throws EE_Error
139
+	 * @throws ReflectionException
140
+	 */
141
+	private function itemizeOrderForFullPayment()
142
+	{
143
+		$item_num        = 0;
144
+		$total_line_item = $this->transaction->total_line_item();
145
+		$item_num        = $this->addOrderItemsForLineItems($total_line_item, $item_num);
146
+		$this->addOrderItemsForAdditionalCharges($total_line_item);
147
+		$this->handleItemizedOrderSumDifference($total_line_item, $item_num);
148
+	}
149 149
 
150 150
 
151
-    /**
152
-     * @return void
153
-     * @throws EE_Error
154
-     */
155
-    private function handlePartialPayment()
156
-    {
157
-        // Item Name.
158
-        $this->order_items['L_PAYMENTREQUEST_0_NAME0'] = mb_strcut(
159
-            $this->gateway_data_formatter->formatPartialPaymentLineItemName($this->payment),
160
-            0,
161
-            127
162
-        );
163
-        // Item description.
164
-        $this->order_items['L_PAYMENTREQUEST_0_DESC0'] = mb_strcut(
165
-            $this->gateway_data_formatter->formatPartialPaymentLineItemDesc($this->payment),
166
-            0,
167
-            127
168
-        );
169
-        // Cost of individual item.
170
-        $this->order_items['L_PAYMENTREQUEST_0_AMT0'] = $this->gateway_data_formatter->formatCurrency(
171
-            $this->payment->amount(),
172
-            $this->decimal_precision
173
-        );
174
-        // Item Number.
175
-        $this->order_items['L_PAYMENTREQUEST_0_NUMBER0'] = 1;
176
-        // Item quantity.
177
-        $this->order_items['L_PAYMENTREQUEST_0_QTY0'] = 1;
178
-        // Digital item is sold.
179
-        $this->order_items['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
180
-        // Item's sales S/H and tax amount.
181
-        $this->order_items['PAYMENTREQUEST_0_ITEMAMT']     = $this->gateway_data_formatter->formatCurrency(
182
-            $this->payment->amount(),
183
-            $this->decimal_precision
184
-        );
185
-        $this->order_items['PAYMENTREQUEST_0_TAXAMT']      = '0';
186
-        $this->order_items['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
187
-        $this->order_items['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
188
-    }
151
+	/**
152
+	 * @return void
153
+	 * @throws EE_Error
154
+	 */
155
+	private function handlePartialPayment()
156
+	{
157
+		// Item Name.
158
+		$this->order_items['L_PAYMENTREQUEST_0_NAME0'] = mb_strcut(
159
+			$this->gateway_data_formatter->formatPartialPaymentLineItemName($this->payment),
160
+			0,
161
+			127
162
+		);
163
+		// Item description.
164
+		$this->order_items['L_PAYMENTREQUEST_0_DESC0'] = mb_strcut(
165
+			$this->gateway_data_formatter->formatPartialPaymentLineItemDesc($this->payment),
166
+			0,
167
+			127
168
+		);
169
+		// Cost of individual item.
170
+		$this->order_items['L_PAYMENTREQUEST_0_AMT0'] = $this->gateway_data_formatter->formatCurrency(
171
+			$this->payment->amount(),
172
+			$this->decimal_precision
173
+		);
174
+		// Item Number.
175
+		$this->order_items['L_PAYMENTREQUEST_0_NUMBER0'] = 1;
176
+		// Item quantity.
177
+		$this->order_items['L_PAYMENTREQUEST_0_QTY0'] = 1;
178
+		// Digital item is sold.
179
+		$this->order_items['L_PAYMENTREQUEST_0_ITEMCATEGORY0'] = 'Physical';
180
+		// Item's sales S/H and tax amount.
181
+		$this->order_items['PAYMENTREQUEST_0_ITEMAMT']     = $this->gateway_data_formatter->formatCurrency(
182
+			$this->payment->amount(),
183
+			$this->decimal_precision
184
+		);
185
+		$this->order_items['PAYMENTREQUEST_0_TAXAMT']      = '0';
186
+		$this->order_items['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
187
+		$this->order_items['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
188
+	}
189 189
 
190 190
 
191
-    /**
192
-     * @param EE_Line_Item $total_line_item
193
-     * @param int          $item_num
194
-     * @return int
195
-     * @throws EE_Error
196
-     * @throws ReflectionException
197
-     */
198
-    private function addOrderItemsForLineItems(EE_Line_Item $total_line_item, int $item_num): int
199
-    {
200
-        // Go through each item in the list.
201
-        foreach ($total_line_item->get_items() as $line_item) {
202
-            if ($line_item instanceof EE_Line_Item) {
203
-                // PayPal doesn't like line items with 0.00 amount, so we may skip those.
204
-                if (EEH_Money::compare_floats($line_item->pretaxTotal(), '0.00', '==')) {
205
-                    continue;
206
-                }
207
-                $unit_price         = $this->gateway_data_formatter->formatCurrency(
208
-                    $line_item->unit_price(),
209
-                    $this->decimal_precision
210
-                );
211
-                $line_item_quantity = $line_item->quantity();
212
-                // This is a discount.
213
-                if ($line_item->is_percent()) {
214
-                    $unit_price         = $line_item->pretaxTotal();
215
-                    $line_item_quantity = 1;
216
-                }
217
-                // Item Name.
218
-                $this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
219
-                    $this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
220
-                    0,
221
-                    127
222
-                );
223
-                // Item description.
224
-                $this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = mb_strcut(
225
-                    $this->gateway_data_formatter->formatLineItemDesc($line_item, $this->payment),
226
-                    0,
227
-                    127
228
-                );
229
-                // Cost of individual item.
230
-                $this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $unit_price;
231
-                // Item Number.
232
-                $this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
233
-                // Item quantity.
234
-                $this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = $line_item_quantity;
235
-                // Digital item is sold.
236
-                $this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
237
-                // add item total to order sum
238
-                $this->itemized_order_sum += $unit_price * $line_item_quantity;
239
-                ++$item_num;
240
-            }
241
-        }
242
-        return $item_num;
243
-    }
191
+	/**
192
+	 * @param EE_Line_Item $total_line_item
193
+	 * @param int          $item_num
194
+	 * @return int
195
+	 * @throws EE_Error
196
+	 * @throws ReflectionException
197
+	 */
198
+	private function addOrderItemsForLineItems(EE_Line_Item $total_line_item, int $item_num): int
199
+	{
200
+		// Go through each item in the list.
201
+		foreach ($total_line_item->get_items() as $line_item) {
202
+			if ($line_item instanceof EE_Line_Item) {
203
+				// PayPal doesn't like line items with 0.00 amount, so we may skip those.
204
+				if (EEH_Money::compare_floats($line_item->pretaxTotal(), '0.00', '==')) {
205
+					continue;
206
+				}
207
+				$unit_price         = $this->gateway_data_formatter->formatCurrency(
208
+					$line_item->unit_price(),
209
+					$this->decimal_precision
210
+				);
211
+				$line_item_quantity = $line_item->quantity();
212
+				// This is a discount.
213
+				if ($line_item->is_percent()) {
214
+					$unit_price         = $line_item->pretaxTotal();
215
+					$line_item_quantity = 1;
216
+				}
217
+				// Item Name.
218
+				$this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
219
+					$this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
220
+					0,
221
+					127
222
+				);
223
+				// Item description.
224
+				$this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = mb_strcut(
225
+					$this->gateway_data_formatter->formatLineItemDesc($line_item, $this->payment),
226
+					0,
227
+					127
228
+				);
229
+				// Cost of individual item.
230
+				$this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $unit_price;
231
+				// Item Number.
232
+				$this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
233
+				// Item quantity.
234
+				$this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = $line_item_quantity;
235
+				// Digital item is sold.
236
+				$this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
237
+				// add item total to order sum
238
+				$this->itemized_order_sum += $unit_price * $line_item_quantity;
239
+				++$item_num;
240
+			}
241
+		}
242
+		return $item_num;
243
+	}
244 244
 
245 245
 
246
-    /**
247
-     * @param EE_Line_Item $total_line_item
248
-     * @return void
249
-     * @throws EE_Error
250
-     * @throws ReflectionException
251
-     */
252
-    private function addOrderItemsForAdditionalCharges(EE_Line_Item $total_line_item)
253
-    {
254
-        // Item's sales S/H and tax amount.
255
-        $this->order_items['PAYMENTREQUEST_0_ITEMAMT']     = $total_line_item->get_items_total();
256
-        $this->order_items['PAYMENTREQUEST_0_TAXAMT']      = $total_line_item->get_total_tax();
257
-        $this->order_items['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
258
-        $this->order_items['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
259
-    }
246
+	/**
247
+	 * @param EE_Line_Item $total_line_item
248
+	 * @return void
249
+	 * @throws EE_Error
250
+	 * @throws ReflectionException
251
+	 */
252
+	private function addOrderItemsForAdditionalCharges(EE_Line_Item $total_line_item)
253
+	{
254
+		// Item's sales S/H and tax amount.
255
+		$this->order_items['PAYMENTREQUEST_0_ITEMAMT']     = $total_line_item->get_items_total();
256
+		$this->order_items['PAYMENTREQUEST_0_TAXAMT']      = $total_line_item->get_total_tax();
257
+		$this->order_items['PAYMENTREQUEST_0_SHIPPINGAMT'] = '0';
258
+		$this->order_items['PAYMENTREQUEST_0_HANDLINGAMT'] = '0';
259
+	}
260 260
 
261 261
 
262
-    /**
263
-     * @param EE_Line_Item $total_line_item
264
-     * @param int          $item_num
265
-     * @return void
266
-     * @throws EE_Error
267
-     * @throws ReflectionException
268
-     */
269
-    private function handleItemizedOrderSumDifference(EE_Line_Item $total_line_item, int $item_num)
270
-    {
271
-        // calculate the difference between the TXN total and the itemized order sum
272
-        $itemized_order_sum_difference = round(
273
-            $this->transaction->total()
274
-            - $this->itemized_order_sum
275
-            - $total_line_item->get_total_tax(),
276
-            $this->decimal_precision
277
-        );
278
-        // If we were not able to recognize some item like promotion, surcharge or cancellation,
279
-        // add the difference as an extra line item.
280
-        if (EEH_Money::compare_floats($itemized_order_sum_difference, 0, '!=')) {
281
-            // Item Name.
282
-            $this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
283
-                esc_html__(
284
-                    'Other (promotion/surcharge/cancellation)',
285
-                    'event_espresso'
286
-                ),
287
-                0,
288
-                127
289
-            );
290
-            // Item description.
291
-            $this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = '';
292
-            // Cost of individual item.
293
-            $this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $this->gateway_data_formatter->formatCurrency(
294
-                $itemized_order_sum_difference,
295
-                $this->decimal_precision
296
-            );
297
-            // Item Number.
298
-            $this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
299
-            // Item quantity.
300
-            $this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = 1;
301
-            // Digital item is sold.
302
-            $this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
303
-        }
304
-    }
262
+	/**
263
+	 * @param EE_Line_Item $total_line_item
264
+	 * @param int          $item_num
265
+	 * @return void
266
+	 * @throws EE_Error
267
+	 * @throws ReflectionException
268
+	 */
269
+	private function handleItemizedOrderSumDifference(EE_Line_Item $total_line_item, int $item_num)
270
+	{
271
+		// calculate the difference between the TXN total and the itemized order sum
272
+		$itemized_order_sum_difference = round(
273
+			$this->transaction->total()
274
+			- $this->itemized_order_sum
275
+			- $total_line_item->get_total_tax(),
276
+			$this->decimal_precision
277
+		);
278
+		// If we were not able to recognize some item like promotion, surcharge or cancellation,
279
+		// add the difference as an extra line item.
280
+		if (EEH_Money::compare_floats($itemized_order_sum_difference, 0, '!=')) {
281
+			// Item Name.
282
+			$this->order_items[ "L_PAYMENTREQUEST_0_NAME{$item_num}" ] = mb_strcut(
283
+				esc_html__(
284
+					'Other (promotion/surcharge/cancellation)',
285
+					'event_espresso'
286
+				),
287
+				0,
288
+				127
289
+			);
290
+			// Item description.
291
+			$this->order_items[ "L_PAYMENTREQUEST_0_DESC{$item_num}" ] = '';
292
+			// Cost of individual item.
293
+			$this->order_items[ "L_PAYMENTREQUEST_0_AMT{$item_num}" ] = $this->gateway_data_formatter->formatCurrency(
294
+				$itemized_order_sum_difference,
295
+				$this->decimal_precision
296
+			);
297
+			// Item Number.
298
+			$this->order_items[ "L_PAYMENTREQUEST_0_NUMBER{$item_num}" ] = $item_num + 1;
299
+			// Item quantity.
300
+			$this->order_items[ "L_PAYMENTREQUEST_0_QTY{$item_num}" ] = 1;
301
+			// Digital item is sold.
302
+			$this->order_items[ "L_PAYMENTREQUEST_0_ITEMCATEGORY{$item_num}" ] = 'Physical';
303
+		}
304
+	}
305 305
 }
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/TokenRequest.php 2 patches
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -13,124 +13,124 @@
 block discarded – undo
13 13
 class TokenRequest
14 14
 {
15 15
 
16
-    /**
17
-     * @var GatewayDataFormatterInterface
18
-     */
19
-    protected $gateway_data_formatter;
16
+	/**
17
+	 * @var GatewayDataFormatterInterface
18
+	 */
19
+	protected $gateway_data_formatter;
20 20
 
21 21
 
22
-    /**
23
-     * @param GatewayDataFormatterInterface $gateway_data_formatter
24
-     */
25
-    public function __construct(GatewayDataFormatterInterface $gateway_data_formatter)
26
-    {
27
-        $this->gateway_data_formatter = $gateway_data_formatter;
28
-    }
22
+	/**
23
+	 * @param GatewayDataFormatterInterface $gateway_data_formatter
24
+	 */
25
+	public function __construct(GatewayDataFormatterInterface $gateway_data_formatter)
26
+	{
27
+		$this->gateway_data_formatter = $gateway_data_formatter;
28
+	}
29 29
 
30 30
 
31
-    /**
32
-     * @param EE_Payment $payment
33
-     * @param array      $itemized_order
34
-     * @param string     $return_url
35
-     * @param string     $cancel_url
36
-     * @param string     $logo_image_url
37
-     * @param bool       $request_shipping_address
38
-     * @return array
39
-     * @throws EE_Error
40
-     * @throws ReflectionException
41
-     */
42
-    public function generateDetails(
43
-        EE_Payment $payment,
44
-        array $itemized_order = [],
45
-        string $return_url = '',
46
-        string $cancel_url = '',
47
-        string $logo_image_url = '',
48
-        bool $request_shipping_address = false
49
-    ): array {
50
-        $locale = explode('-', get_bloginfo('language'));
51
-        // Gather request parameters.
52
-        $token_request_details = [
53
-            'METHOD'                         => 'SetExpressCheckout',
54
-            'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
55
-            'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
56
-            'PAYMENTREQUEST_0_DESC'          => mb_strcut(
57
-                $this->gateway_data_formatter->formatOrderDescription($payment),
58
-                0,
59
-                127
60
-            ),
61
-            'RETURNURL'                      => $return_url,
62
-            'CANCELURL'                      => $cancel_url,
63
-            'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
64
-            // Buyer does not need to create a PayPal account to check out.
65
-            // This is referred to as PayPal Account Optional.
66
-            'SOLUTIONTYPE'                   => 'Sole',
67
-            // Locale of the pages displayed by PayPal during Express Checkout.
68
-            'LOCALECODE'                     => $locale[1],
69
-        ];
70
-        $token_request_details = array_merge($token_request_details, $itemized_order);
71
-        if (! $request_shipping_address) {
72
-            // Do not request shipping details on the PP Checkout page.
73
-            $token_request_details['NOSHIPPING']         = '1';
74
-            $token_request_details['REQCONFIRMSHIPPING'] = '0';
75
-        } else {
76
-            // Automatically filling out shipping and contact information.
77
-            $transaction          = $payment->transaction();
78
-            $primary_registration = $transaction->primary_registration();
79
-            $primary_attendee     = $primary_registration instanceof EE_Registration
80
-                ? $primary_registration->attendee()
81
-                : false;
82
-            if ($primary_attendee instanceof EE_Attendee) {
83
-                // If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
84
-                $token_request_details['NOSHIPPING']                         = '2';
85
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOSTREET']      = $primary_attendee->address();
86
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOSTREET2']     = $primary_attendee->address2();
87
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOCITY']        = $primary_attendee->city();
88
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOSTATE']       = $primary_attendee->state_abbrev();
89
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = $primary_attendee->country_ID();
90
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOZIP']         = $primary_attendee->zip();
91
-                $token_request_details['PAYMENTREQUEST_0_EMAIL']             = $primary_attendee->email();
92
-                $token_request_details['PAYMENTREQUEST_0_SHIPTOPHONENUM']    = $primary_attendee->phone();
93
-            }
94
-        }
95
-        // Used a business/personal logo on the PayPal page.
96
-        if (! empty($logo_image_url)) {
97
-            $token_request_details['LOGOIMG'] = $logo_image_url;
98
-        }
99
-        return $token_request_details;
100
-    }
31
+	/**
32
+	 * @param EE_Payment $payment
33
+	 * @param array      $itemized_order
34
+	 * @param string     $return_url
35
+	 * @param string     $cancel_url
36
+	 * @param string     $logo_image_url
37
+	 * @param bool       $request_shipping_address
38
+	 * @return array
39
+	 * @throws EE_Error
40
+	 * @throws ReflectionException
41
+	 */
42
+	public function generateDetails(
43
+		EE_Payment $payment,
44
+		array $itemized_order = [],
45
+		string $return_url = '',
46
+		string $cancel_url = '',
47
+		string $logo_image_url = '',
48
+		bool $request_shipping_address = false
49
+	): array {
50
+		$locale = explode('-', get_bloginfo('language'));
51
+		// Gather request parameters.
52
+		$token_request_details = [
53
+			'METHOD'                         => 'SetExpressCheckout',
54
+			'PAYMENTREQUEST_0_AMT'           => $payment->amount(),
55
+			'PAYMENTREQUEST_0_CURRENCYCODE'  => $payment->currency_code(),
56
+			'PAYMENTREQUEST_0_DESC'          => mb_strcut(
57
+				$this->gateway_data_formatter->formatOrderDescription($payment),
58
+				0,
59
+				127
60
+			),
61
+			'RETURNURL'                      => $return_url,
62
+			'CANCELURL'                      => $cancel_url,
63
+			'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
64
+			// Buyer does not need to create a PayPal account to check out.
65
+			// This is referred to as PayPal Account Optional.
66
+			'SOLUTIONTYPE'                   => 'Sole',
67
+			// Locale of the pages displayed by PayPal during Express Checkout.
68
+			'LOCALECODE'                     => $locale[1],
69
+		];
70
+		$token_request_details = array_merge($token_request_details, $itemized_order);
71
+		if (! $request_shipping_address) {
72
+			// Do not request shipping details on the PP Checkout page.
73
+			$token_request_details['NOSHIPPING']         = '1';
74
+			$token_request_details['REQCONFIRMSHIPPING'] = '0';
75
+		} else {
76
+			// Automatically filling out shipping and contact information.
77
+			$transaction          = $payment->transaction();
78
+			$primary_registration = $transaction->primary_registration();
79
+			$primary_attendee     = $primary_registration instanceof EE_Registration
80
+				? $primary_registration->attendee()
81
+				: false;
82
+			if ($primary_attendee instanceof EE_Attendee) {
83
+				// If you do not pass the shipping address, PayPal obtains it from the buyer's account profile.
84
+				$token_request_details['NOSHIPPING']                         = '2';
85
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOSTREET']      = $primary_attendee->address();
86
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOSTREET2']     = $primary_attendee->address2();
87
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOCITY']        = $primary_attendee->city();
88
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOSTATE']       = $primary_attendee->state_abbrev();
89
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOCOUNTRYCODE'] = $primary_attendee->country_ID();
90
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOZIP']         = $primary_attendee->zip();
91
+				$token_request_details['PAYMENTREQUEST_0_EMAIL']             = $primary_attendee->email();
92
+				$token_request_details['PAYMENTREQUEST_0_SHIPTOPHONENUM']    = $primary_attendee->phone();
93
+			}
94
+		}
95
+		// Used a business/personal logo on the PayPal page.
96
+		if (! empty($logo_image_url)) {
97
+			$token_request_details['LOGOIMG'] = $logo_image_url;
98
+		}
99
+		return $token_request_details;
100
+	}
101 101
 
102 102
 
103
-    /**
104
-     * @param EE_Payment $payment
105
-     * @param array      $token_request_status
106
-     * @param bool       $is_in_sandbox_mode
107
-     * @throws EE_Error
108
-     * @throws ReflectionException
109
-     */
110
-    public function processResponse(EE_Payment $payment, array $token_request_status, bool $is_in_sandbox_mode)
111
-    {
112
-        $response_args = (isset($token_request_status['args']) && is_array($token_request_status['args']))
113
-            ? $token_request_status['args']
114
-            : [];
115
-        if ($token_request_status['status']) {
116
-            // We got the Token so we may continue with the payment and redirect the client.
117
-            $payment->set_details($response_args);
118
-            $gateway_url = $is_in_sandbox_mode ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';
119
-            $token       = $response_args['TOKEN'];
120
-            $payment->set_redirect_url(
121
-                "{$gateway_url}/checkoutnow?useraction=commit&cmd=_express-checkout&token={$token}"
122
-            );
123
-            return;
124
-        }
125
-        $gateway_response = isset($response_args['L_ERRORCODE'])
126
-            ? $response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']
127
-            : esc_html__(
128
-                'Error occurred while trying to setup the Express Checkout.',
129
-                'event_espresso'
130
-            );
103
+	/**
104
+	 * @param EE_Payment $payment
105
+	 * @param array      $token_request_status
106
+	 * @param bool       $is_in_sandbox_mode
107
+	 * @throws EE_Error
108
+	 * @throws ReflectionException
109
+	 */
110
+	public function processResponse(EE_Payment $payment, array $token_request_status, bool $is_in_sandbox_mode)
111
+	{
112
+		$response_args = (isset($token_request_status['args']) && is_array($token_request_status['args']))
113
+			? $token_request_status['args']
114
+			: [];
115
+		if ($token_request_status['status']) {
116
+			// We got the Token so we may continue with the payment and redirect the client.
117
+			$payment->set_details($response_args);
118
+			$gateway_url = $is_in_sandbox_mode ? 'https://www.sandbox.paypal.com' : 'https://www.paypal.com';
119
+			$token       = $response_args['TOKEN'];
120
+			$payment->set_redirect_url(
121
+				"{$gateway_url}/checkoutnow?useraction=commit&cmd=_express-checkout&token={$token}"
122
+			);
123
+			return;
124
+		}
125
+		$gateway_response = isset($response_args['L_ERRORCODE'])
126
+			? $response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']
127
+			: esc_html__(
128
+				'Error occurred while trying to setup the Express Checkout.',
129
+				'event_espresso'
130
+			);
131 131
 
132
-        $payment->set_gateway_response($gateway_response);
133
-        $payment->set_details($response_args);
134
-        $payment->set_status(EEM_Payment::instance()->failed_status());
135
-    }
132
+		$payment->set_gateway_response($gateway_response);
133
+		$payment->set_details($response_args);
134
+		$payment->set_status(EEM_Payment::instance()->failed_status());
135
+	}
136 136
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
             'LOCALECODE'                     => $locale[1],
69 69
         ];
70 70
         $token_request_details = array_merge($token_request_details, $itemized_order);
71
-        if (! $request_shipping_address) {
71
+        if ( ! $request_shipping_address) {
72 72
             // Do not request shipping details on the PP Checkout page.
73 73
             $token_request_details['NOSHIPPING']         = '1';
74 74
             $token_request_details['REQCONFIRMSHIPPING'] = '0';
@@ -93,7 +93,7 @@  discard block
 block discarded – undo
93 93
             }
94 94
         }
95 95
         // Used a business/personal logo on the PayPal page.
96
-        if (! empty($logo_image_url)) {
96
+        if ( ! empty($logo_image_url)) {
97 97
             $token_request_details['LOGOIMG'] = $logo_image_url;
98 98
         }
99 99
         return $token_request_details;
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
             return;
124 124
         }
125 125
         $gateway_response = isset($response_args['L_ERRORCODE'])
126
-            ? $response_args['L_ERRORCODE'] . '; ' . $response_args['L_SHORTMESSAGE']
126
+            ? $response_args['L_ERRORCODE'].'; '.$response_args['L_SHORTMESSAGE']
127 127
             : esc_html__(
128 128
                 'Error occurred while trying to setup the Express Checkout.',
129 129
                 'event_espresso'
Please login to merge, or discard this patch.
payment_methods/Paypal_Express/polyfills.php 2 patches
Indentation   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -1,18 +1,18 @@
 block discarded – undo
1 1
 <?php
2 2
 
3 3
 if (! function_exists('mb_strcut')) {
4
-    /**
5
-     * Quickfix to address https://events.codebasehq.com/projects/event-espresso/tickets/11089 ASAP
6
-     * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
7
-     * (namely, that we might send too many characters to PayPal; however in this case they just issue a warning but nothing breaks)
8
-     *
9
-     * @param $string
10
-     * @param $start
11
-     * @param $length
12
-     * @return string
13
-     */
14
-    function mb_strcut($string, $start, $length = null): string
15
-    {
16
-        return mb_substr($string, $start, $length);
17
-    }
4
+	/**
5
+	 * Quickfix to address https://events.codebasehq.com/projects/event-espresso/tickets/11089 ASAP
6
+	 * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
7
+	 * (namely, that we might send too many characters to PayPal; however in this case they just issue a warning but nothing breaks)
8
+	 *
9
+	 * @param $string
10
+	 * @param $start
11
+	 * @param $length
12
+	 * @return string
13
+	 */
14
+	function mb_strcut($string, $start, $length = null): string
15
+	{
16
+		return mb_substr($string, $start, $length);
17
+	}
18 18
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@
 block discarded – undo
1 1
 <?php
2 2
 
3
-if (! function_exists('mb_strcut')) {
3
+if ( ! function_exists('mb_strcut')) {
4 4
     /**
5 5
      * Quickfix to address https://events.codebasehq.com/projects/event-espresso/tickets/11089 ASAP
6 6
      * Very simple mimic of mb_substr (which WP ensures exists in wp-includes/compat.php). Still has all the problems of mb_substr
Please login to merge, or discard this patch.
payment_methods/Paypal_Standard/ItemizedOrder.php 2 patches
Indentation   +251 added lines, -251 removed lines patch added patch discarded remove patch
@@ -14,282 +14,282 @@
 block discarded – undo
14 14
 
15 15
 class ItemizedOrder
16 16
 {
17
-    /**
18
-     * @var float
19
-     */
20
-    private $existing_shipping_charges = 0.00;
17
+	/**
18
+	 * @var float
19
+	 */
20
+	private $existing_shipping_charges = 0.00;
21 21
 
22
-    /**
23
-     * keeps track of exactly how much the itemized order amount equals
24
-     *
25
-     * @var float
26
-     */
27
-    private $itemized_order_sum = 0.00;
22
+	/**
23
+	 * keeps track of exactly how much the itemized order amount equals
24
+	 *
25
+	 * @var float
26
+	 */
27
+	private $itemized_order_sum = 0.00;
28 28
 
29
-    /**
30
-     * @var GatewayDataFormatterInterface
31
-     */
32
-    protected $gateway_data_formatter;
29
+	/**
30
+	 * @var GatewayDataFormatterInterface
31
+	 */
32
+	protected $gateway_data_formatter;
33 33
 
34
-    /**
35
-     * @var array
36
-     */
37
-    private $order_items;
34
+	/**
35
+	 * @var array
36
+	 */
37
+	private $order_items;
38 38
 
39
-    /**
40
-     * the payment being processed
41
-     *
42
-     * @var EE_Payment
43
-     */
44
-    protected $payment;
39
+	/**
40
+	 * the payment being processed
41
+	 *
42
+	 * @var EE_Payment
43
+	 */
44
+	protected $payment;
45 45
 
46
-    /**
47
-     * @var EEG_Paypal_Standard
48
-     */
49
-    protected $paypal_gateway;
46
+	/**
47
+	 * @var EEG_Paypal_Standard
48
+	 */
49
+	protected $paypal_gateway;
50 50
 
51
-    /**
52
-     * @var float
53
-     */
54
-    private $total_discounts = 0.00;
51
+	/**
52
+	 * @var float
53
+	 */
54
+	private $total_discounts = 0.00;
55 55
 
56
-    /**
57
-     * @var EE_Transaction
58
-     */
59
-    private $transaction;
56
+	/**
57
+	 * @var EE_Transaction
58
+	 */
59
+	private $transaction;
60 60
 
61 61
 
62
-    /**
63
-     * @param GatewayDataFormatterInterface $gateway_data_formatter
64
-     * @param EEG_Paypal_Standard           $paypal_gateway
65
-     */
66
-    public function __construct(GatewayDataFormatterInterface $gateway_data_formatter, EEG_Paypal_Standard $paypal_gateway)
67
-    {
68
-        $this->gateway_data_formatter = $gateway_data_formatter;
69
-        $this->paypal_gateway = $paypal_gateway;
70
-    }
62
+	/**
63
+	 * @param GatewayDataFormatterInterface $gateway_data_formatter
64
+	 * @param EEG_Paypal_Standard           $paypal_gateway
65
+	 */
66
+	public function __construct(GatewayDataFormatterInterface $gateway_data_formatter, EEG_Paypal_Standard $paypal_gateway)
67
+	{
68
+		$this->gateway_data_formatter = $gateway_data_formatter;
69
+		$this->paypal_gateway = $paypal_gateway;
70
+	}
71 71
 
72 72
 
73
-    /**
74
-     * @param EE_Payment $payment
75
-     * @param string     $return_url    URL to send the user to after payment on the payment provider's website
76
-     * @param string     $notify_url    URL to send the instant payment notification
77
-     * @param string     $cancel_url    URL to send the user to after a cancelled payment attempt
78
-     *                                  on the payment provider's website
79
-     * @return array
80
-     * @throws EE_Error
81
-     * @throws ReflectionException
82
-     */
83
-    public function generateItemizedOrderForPayment(
84
-        EE_Payment $payment,
85
-        string $return_url = '',
86
-        string $notify_url = '',
87
-        string $cancel_url = ''
88
-    ): array {
89
-        $this->payment         = $payment;
90
-        $this->transaction     = $this->payment->transaction();
91
-        $this->total_discounts = $this->transaction->paid();
92
-        $total_line_item       = $this->transaction->total_line_item();
73
+	/**
74
+	 * @param EE_Payment $payment
75
+	 * @param string     $return_url    URL to send the user to after payment on the payment provider's website
76
+	 * @param string     $notify_url    URL to send the instant payment notification
77
+	 * @param string     $cancel_url    URL to send the user to after a cancelled payment attempt
78
+	 *                                  on the payment provider's website
79
+	 * @return array
80
+	 * @throws EE_Error
81
+	 * @throws ReflectionException
82
+	 */
83
+	public function generateItemizedOrderForPayment(
84
+		EE_Payment $payment,
85
+		string $return_url = '',
86
+		string $notify_url = '',
87
+		string $cancel_url = ''
88
+	): array {
89
+		$this->payment         = $payment;
90
+		$this->transaction     = $this->payment->transaction();
91
+		$this->total_discounts = $this->transaction->paid();
92
+		$total_line_item       = $this->transaction->total_line_item();
93 93
 
94
-        // only itemize the order if we're paying for the rest of the order's amount
95
-        $item_num = 1;
96
-        $item_num = $this->paymentIsForTransactionTotal()
97
-            ? $this->itemizeOrderForFullPayment($total_line_item, $item_num)
98
-            : $this->handlePartialPayment($item_num);
94
+		// only itemize the order if we're paying for the rest of the order's amount
95
+		$item_num = 1;
96
+		$item_num = $this->paymentIsForTransactionTotal()
97
+			? $this->itemizeOrderForFullPayment($total_line_item, $item_num)
98
+			: $this->handlePartialPayment($item_num);
99 99
 
100
-        if ($this->paypal_gateway->isInSandboxMode()) {
101
-            $this->addSandboxModeArgs($item_num, $notify_url, $return_url);
102
-        }
103
-        $this->addGeneralOrderItems($cancel_url, $notify_url, $return_url);
104
-        return $this->order_items;
105
-    }
100
+		if ($this->paypal_gateway->isInSandboxMode()) {
101
+			$this->addSandboxModeArgs($item_num, $notify_url, $return_url);
102
+		}
103
+		$this->addGeneralOrderItems($cancel_url, $notify_url, $return_url);
104
+		return $this->order_items;
105
+	}
106 106
 
107 107
 
108
-    /**
109
-     * @return bool
110
-     * @throws ReflectionException
111
-     * @throws EE_Error
112
-     */
113
-    private function paymentIsForTransactionTotal(): bool
114
-    {
115
-        return EEH_Money::compare_floats($this->payment->amount(), $this->transaction->total(), '==');
116
-    }
108
+	/**
109
+	 * @return bool
110
+	 * @throws ReflectionException
111
+	 * @throws EE_Error
112
+	 */
113
+	private function paymentIsForTransactionTotal(): bool
114
+	{
115
+		return EEH_Money::compare_floats($this->payment->amount(), $this->transaction->total(), '==');
116
+	}
117 117
 
118 118
 
119
-    /**
120
-     * if the payment is for the remaining transaction amount,
121
-     * keep track of exactly how much the itemized order amount equals
122
-     *
123
-     * @param EE_Line_Item $total_line_item
124
-     * @param int          $item_num
125
-     * @return int
126
-     * @throws EE_Error
127
-     * @throws ReflectionException
128
-     */
129
-    private function itemizeOrderForFullPayment(EE_Line_Item $total_line_item, int $item_num): int
130
-    {
131
-        $this->payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true);
132
-        // this payment is for the remaining transaction amount, so let's show all the line items
133
-        $item_num = $this->addOrderItemsForLineItems($total_line_item, $item_num);
134
-        // and make adjustments as needed
135
-        $item_num = $this->handleItemizedOrderSumDifference($total_line_item, $item_num);
136
-        // add our taxes to the order if we're NOT using PayPal's
137
-        if (! $this->paypal_gateway->paypalTaxes()) {
138
-            $this->order_items['tax_cart'] = $total_line_item->get_total_tax();
139
-        }
140
-        return $item_num;
141
-    }
119
+	/**
120
+	 * if the payment is for the remaining transaction amount,
121
+	 * keep track of exactly how much the itemized order amount equals
122
+	 *
123
+	 * @param EE_Line_Item $total_line_item
124
+	 * @param int          $item_num
125
+	 * @return int
126
+	 * @throws EE_Error
127
+	 * @throws ReflectionException
128
+	 */
129
+	private function itemizeOrderForFullPayment(EE_Line_Item $total_line_item, int $item_num): int
130
+	{
131
+		$this->payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, true);
132
+		// this payment is for the remaining transaction amount, so let's show all the line items
133
+		$item_num = $this->addOrderItemsForLineItems($total_line_item, $item_num);
134
+		// and make adjustments as needed
135
+		$item_num = $this->handleItemizedOrderSumDifference($total_line_item, $item_num);
136
+		// add our taxes to the order if we're NOT using PayPal's
137
+		if (! $this->paypal_gateway->paypalTaxes()) {
138
+			$this->order_items['tax_cart'] = $total_line_item->get_total_tax();
139
+		}
140
+		return $item_num;
141
+	}
142 142
 
143 143
 
144
-    /**
145
-     * @param int $item_num
146
-     * @return int
147
-     * @throws EE_Error
148
-     * @throws ReflectionException
149
-     */
150
-    private function handlePartialPayment(int $item_num): int
151
-    {
152
-        $this->payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, false);
153
-        // partial payment that's not for the remaining amount, so we can't send an itemized list
154
-        $this->order_items[ "item_name_{$item_num}" ] = substr(
155
-            $this->gateway_data_formatter->formatPartialPaymentLineItemName($this->payment),
156
-            0,
157
-            127
158
-        );
159
-        $this->order_items[ "amount_{$item_num}" ]    = $this->payment->amount();
160
-        $this->order_items[ "shipping_{$item_num}" ]  = '0';
161
-        $this->order_items[ "shipping2_{$item_num}" ] = '0';
162
-        $this->order_items['tax_cart']              = '0';
163
-        $item_num++;
164
-        return $item_num;
165
-    }
144
+	/**
145
+	 * @param int $item_num
146
+	 * @return int
147
+	 * @throws EE_Error
148
+	 * @throws ReflectionException
149
+	 */
150
+	private function handlePartialPayment(int $item_num): int
151
+	{
152
+		$this->payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, false);
153
+		// partial payment that's not for the remaining amount, so we can't send an itemized list
154
+		$this->order_items[ "item_name_{$item_num}" ] = substr(
155
+			$this->gateway_data_formatter->formatPartialPaymentLineItemName($this->payment),
156
+			0,
157
+			127
158
+		);
159
+		$this->order_items[ "amount_{$item_num}" ]    = $this->payment->amount();
160
+		$this->order_items[ "shipping_{$item_num}" ]  = '0';
161
+		$this->order_items[ "shipping2_{$item_num}" ] = '0';
162
+		$this->order_items['tax_cart']              = '0';
163
+		$item_num++;
164
+		return $item_num;
165
+	}
166 166
 
167 167
 
168
-    /**
169
-     * @param EE_Line_Item $total_line_item
170
-     * @param int          $item_num
171
-     * @return int
172
-     * @throws EE_Error
173
-     * @throws ReflectionException
174
-     */
175
-    private function addOrderItemsForLineItems(EE_Line_Item $total_line_item, int $item_num): int
176
-    {
177
-        foreach ($total_line_item->get_items() as $line_item) {
178
-            if ($line_item instanceof EE_Line_Item) {
179
-                // it's some kind of discount
180
-                if (EEH_Money::compare_floats($line_item->pretaxTotal(), 0.00, '<')) {
181
-                    $this->total_discounts    += abs($line_item->pretaxTotal());
182
-                    $this->itemized_order_sum += $line_item->pretaxTotal();
183
-                    continue;
184
-                }
185
-                // dont include shipping again.
186
-                if (strpos($line_item->code(), 'paypal_shipping_') === 0) {
187
-                    $this->existing_shipping_charges = $line_item->pretaxTotal();
188
-                    continue;
189
-                }
190
-                $this->order_items[ "item_name_{$item_num}" ] = substr(
191
-                    $this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
192
-                    0,
193
-                    127
194
-                );
195
-                $this->order_items[ "amount_{$item_num}" ]    = $line_item->unit_price();
196
-                $this->order_items[ "quantity_{$item_num}" ]  = $line_item->quantity();
197
-                // if we're not letting PayPal calculate shipping, tell them its 0
198
-                if (! $this->paypal_gateway->paypalShipping()) {
199
-                    $this->order_items[ "shipping_{$item_num}" ]  = '0';
200
-                    $this->order_items[ "shipping2_{$item_num}" ] = '0';
201
-                }
202
-                $this->itemized_order_sum += $line_item->pretaxTotal();
203
-                $item_num++;
204
-            }
205
-        }
206
-        return $item_num;
207
-    }
168
+	/**
169
+	 * @param EE_Line_Item $total_line_item
170
+	 * @param int          $item_num
171
+	 * @return int
172
+	 * @throws EE_Error
173
+	 * @throws ReflectionException
174
+	 */
175
+	private function addOrderItemsForLineItems(EE_Line_Item $total_line_item, int $item_num): int
176
+	{
177
+		foreach ($total_line_item->get_items() as $line_item) {
178
+			if ($line_item instanceof EE_Line_Item) {
179
+				// it's some kind of discount
180
+				if (EEH_Money::compare_floats($line_item->pretaxTotal(), 0.00, '<')) {
181
+					$this->total_discounts    += abs($line_item->pretaxTotal());
182
+					$this->itemized_order_sum += $line_item->pretaxTotal();
183
+					continue;
184
+				}
185
+				// dont include shipping again.
186
+				if (strpos($line_item->code(), 'paypal_shipping_') === 0) {
187
+					$this->existing_shipping_charges = $line_item->pretaxTotal();
188
+					continue;
189
+				}
190
+				$this->order_items[ "item_name_{$item_num}" ] = substr(
191
+					$this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
192
+					0,
193
+					127
194
+				);
195
+				$this->order_items[ "amount_{$item_num}" ]    = $line_item->unit_price();
196
+				$this->order_items[ "quantity_{$item_num}" ]  = $line_item->quantity();
197
+				// if we're not letting PayPal calculate shipping, tell them its 0
198
+				if (! $this->paypal_gateway->paypalShipping()) {
199
+					$this->order_items[ "shipping_{$item_num}" ]  = '0';
200
+					$this->order_items[ "shipping2_{$item_num}" ] = '0';
201
+				}
202
+				$this->itemized_order_sum += $line_item->pretaxTotal();
203
+				$item_num++;
204
+			}
205
+		}
206
+		return $item_num;
207
+	}
208 208
 
209 209
 
210
-    /**
211
-     * @param EE_Line_Item $total_line_item
212
-     * @param int          $item_num
213
-     * @return int
214
-     * @throws EE_Error
215
-     * @throws ReflectionException
216
-     */
217
-    private function handleItemizedOrderSumDifference(EE_Line_Item $total_line_item, int $item_num): int
218
-    {
219
-        $taxes_li = EEH_Line_Item::get_taxes_subtotal($total_line_item);
220
-        // calculate the difference between the TXN total and the itemized order sum
221
-        $itemized_order_sum_difference = round(
222
-            $this->transaction->total()
223
-            - $this->itemized_order_sum
224
-            - $taxes_li->total()
225
-            - $this->existing_shipping_charges,
226
-            2
227
-        );
228
-        // ideally the itemized order sum equals the transaction total, but if not (which is weird),
229
-        // and the itemized sum is LESS than the transaction total...
230
-        if (EEH_Money::compare_floats($itemized_order_sum_difference, 0.00, '<')) {
231
-            // add the difference to the discounts
232
-            $this->total_discounts += abs($itemized_order_sum_difference);
233
-        } elseif (EEH_Money::compare_floats($itemized_order_sum_difference, 0.00, '>')) {
234
-            // the itemized order sum is MORE than the transaction total
235
-            $this->order_items[ "item_name_{$item_num}" ] = substr(
236
-                esc_html__('additional charges', 'event_espresso'),
237
-                0,
238
-                127
239
-            );
240
-            $this->order_items[ "amount_{$item_num}" ]    = $this->gateway_data_formatter->formatCurrency(
241
-                $itemized_order_sum_difference
242
-            );
243
-            $this->order_items[ "quantity_{$item_num}" ]  = 1;
244
-            $item_num++;
245
-        }
246
-        if (EEH_Money::compare_floats($this->total_discounts, 0.00, '>')) {
247
-            $this->order_items['discount_amount_cart'] = $this->gateway_data_formatter->formatCurrency(
248
-                $this->total_discounts
249
-            );
250
-        }
251
-        return $item_num;
252
-    }
210
+	/**
211
+	 * @param EE_Line_Item $total_line_item
212
+	 * @param int          $item_num
213
+	 * @return int
214
+	 * @throws EE_Error
215
+	 * @throws ReflectionException
216
+	 */
217
+	private function handleItemizedOrderSumDifference(EE_Line_Item $total_line_item, int $item_num): int
218
+	{
219
+		$taxes_li = EEH_Line_Item::get_taxes_subtotal($total_line_item);
220
+		// calculate the difference between the TXN total and the itemized order sum
221
+		$itemized_order_sum_difference = round(
222
+			$this->transaction->total()
223
+			- $this->itemized_order_sum
224
+			- $taxes_li->total()
225
+			- $this->existing_shipping_charges,
226
+			2
227
+		);
228
+		// ideally the itemized order sum equals the transaction total, but if not (which is weird),
229
+		// and the itemized sum is LESS than the transaction total...
230
+		if (EEH_Money::compare_floats($itemized_order_sum_difference, 0.00, '<')) {
231
+			// add the difference to the discounts
232
+			$this->total_discounts += abs($itemized_order_sum_difference);
233
+		} elseif (EEH_Money::compare_floats($itemized_order_sum_difference, 0.00, '>')) {
234
+			// the itemized order sum is MORE than the transaction total
235
+			$this->order_items[ "item_name_{$item_num}" ] = substr(
236
+				esc_html__('additional charges', 'event_espresso'),
237
+				0,
238
+				127
239
+			);
240
+			$this->order_items[ "amount_{$item_num}" ]    = $this->gateway_data_formatter->formatCurrency(
241
+				$itemized_order_sum_difference
242
+			);
243
+			$this->order_items[ "quantity_{$item_num}" ]  = 1;
244
+			$item_num++;
245
+		}
246
+		if (EEH_Money::compare_floats($this->total_discounts, 0.00, '>')) {
247
+			$this->order_items['discount_amount_cart'] = $this->gateway_data_formatter->formatCurrency(
248
+				$this->total_discounts
249
+			);
250
+		}
251
+		return $item_num;
252
+	}
253 253
 
254 254
 
255
-    /**
256
-     * @param int    $item_num
257
-     * @param string $notify_url
258
-     * @param string $return_url
259
-     */
260
-    private function addSandboxModeArgs(int $item_num, string $notify_url, string $return_url)
261
-    {
262
-        $this->order_items[ "item_name_{$item_num}" ] = 'DEBUG INFO (this item only added in sandbox mode';
263
-        $this->order_items[ "amount_{$item_num}" ]    = 0;
264
-        $this->order_items[ "on0_{$item_num}" ]       = 'NOTIFY URL';
265
-        $this->order_items[ "os0_{$item_num}" ]       = $notify_url;
266
-        $this->order_items[ "on1_{$item_num}" ]       = 'RETURN URL';
267
-        $this->order_items[ "os1_{$item_num}" ]       = $return_url;
268
-        $this->order_items[ "shipping_{$item_num}" ]  = '0';
269
-        $this->order_items[ "shipping2_{$item_num}" ] = '0';
270
-        // $this->order_items['option_index_' . $item_num] = 1; // <-- dunno if this is needed ?
271
-    }
255
+	/**
256
+	 * @param int    $item_num
257
+	 * @param string $notify_url
258
+	 * @param string $return_url
259
+	 */
260
+	private function addSandboxModeArgs(int $item_num, string $notify_url, string $return_url)
261
+	{
262
+		$this->order_items[ "item_name_{$item_num}" ] = 'DEBUG INFO (this item only added in sandbox mode';
263
+		$this->order_items[ "amount_{$item_num}" ]    = 0;
264
+		$this->order_items[ "on0_{$item_num}" ]       = 'NOTIFY URL';
265
+		$this->order_items[ "os0_{$item_num}" ]       = $notify_url;
266
+		$this->order_items[ "on1_{$item_num}" ]       = 'RETURN URL';
267
+		$this->order_items[ "os1_{$item_num}" ]       = $return_url;
268
+		$this->order_items[ "shipping_{$item_num}" ]  = '0';
269
+		$this->order_items[ "shipping2_{$item_num}" ] = '0';
270
+		// $this->order_items['option_index_' . $item_num] = 1; // <-- dunno if this is needed ?
271
+	}
272 272
 
273 273
 
274
-    /**
275
-     * @param string $cancel_url
276
-     * @param string $notify_url
277
-     * @param string $return_url
278
-     */
279
-    private function addGeneralOrderItems(string $cancel_url, string $notify_url, string $return_url)
280
-    {
281
-        $this->order_items['business']      = $this->paypal_gateway->paypalId();
282
-        $this->order_items['return']        = $return_url;
283
-        $this->order_items['cancel_return'] = $cancel_url;
284
-        $this->order_items['notify_url']    = $notify_url;
285
-        $this->order_items['cmd']           = '_cart';
286
-        $this->order_items['upload']        = 1;
287
-        $this->order_items['currency_code'] = $this->payment->currency_code();
288
-        $this->order_items['rm']            = 2;// makes the user return with method=POST
289
-        $this->order_items['no_shipping']   = $this->paypal_gateway->shippingDetails();
290
-        $this->order_items['bn']            = 'EventEspresso_SP';// EE will blow up if you change this
291
-        if ($this->paypal_gateway->imageUrl()) {
292
-            $this->order_items['image_url'] = $this->paypal_gateway->imageUrl();
293
-        }
294
-    }
274
+	/**
275
+	 * @param string $cancel_url
276
+	 * @param string $notify_url
277
+	 * @param string $return_url
278
+	 */
279
+	private function addGeneralOrderItems(string $cancel_url, string $notify_url, string $return_url)
280
+	{
281
+		$this->order_items['business']      = $this->paypal_gateway->paypalId();
282
+		$this->order_items['return']        = $return_url;
283
+		$this->order_items['cancel_return'] = $cancel_url;
284
+		$this->order_items['notify_url']    = $notify_url;
285
+		$this->order_items['cmd']           = '_cart';
286
+		$this->order_items['upload']        = 1;
287
+		$this->order_items['currency_code'] = $this->payment->currency_code();
288
+		$this->order_items['rm']            = 2;// makes the user return with method=POST
289
+		$this->order_items['no_shipping']   = $this->paypal_gateway->shippingDetails();
290
+		$this->order_items['bn']            = 'EventEspresso_SP';// EE will blow up if you change this
291
+		if ($this->paypal_gateway->imageUrl()) {
292
+			$this->order_items['image_url'] = $this->paypal_gateway->imageUrl();
293
+		}
294
+	}
295 295
 }
Please login to merge, or discard this patch.
Spacing   +25 added lines, -25 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
         // and make adjustments as needed
135 135
         $item_num = $this->handleItemizedOrderSumDifference($total_line_item, $item_num);
136 136
         // add our taxes to the order if we're NOT using PayPal's
137
-        if (! $this->paypal_gateway->paypalTaxes()) {
137
+        if ( ! $this->paypal_gateway->paypalTaxes()) {
138 138
             $this->order_items['tax_cart'] = $total_line_item->get_total_tax();
139 139
         }
140 140
         return $item_num;
@@ -151,15 +151,15 @@  discard block
 block discarded – undo
151 151
     {
152 152
         $this->payment->update_extra_meta(EEG_Paypal_Standard::itemized_payment_option_name, false);
153 153
         // partial payment that's not for the remaining amount, so we can't send an itemized list
154
-        $this->order_items[ "item_name_{$item_num}" ] = substr(
154
+        $this->order_items["item_name_{$item_num}"] = substr(
155 155
             $this->gateway_data_formatter->formatPartialPaymentLineItemName($this->payment),
156 156
             0,
157 157
             127
158 158
         );
159
-        $this->order_items[ "amount_{$item_num}" ]    = $this->payment->amount();
160
-        $this->order_items[ "shipping_{$item_num}" ]  = '0';
161
-        $this->order_items[ "shipping2_{$item_num}" ] = '0';
162
-        $this->order_items['tax_cart']              = '0';
159
+        $this->order_items["amount_{$item_num}"]    = $this->payment->amount();
160
+        $this->order_items["shipping_{$item_num}"]  = '0';
161
+        $this->order_items["shipping2_{$item_num}"] = '0';
162
+        $this->order_items['tax_cart'] = '0';
163 163
         $item_num++;
164 164
         return $item_num;
165 165
     }
@@ -187,17 +187,17 @@  discard block
 block discarded – undo
187 187
                     $this->existing_shipping_charges = $line_item->pretaxTotal();
188 188
                     continue;
189 189
                 }
190
-                $this->order_items[ "item_name_{$item_num}" ] = substr(
190
+                $this->order_items["item_name_{$item_num}"] = substr(
191 191
                     $this->gateway_data_formatter->formatLineItemName($line_item, $this->payment),
192 192
                     0,
193 193
                     127
194 194
                 );
195
-                $this->order_items[ "amount_{$item_num}" ]    = $line_item->unit_price();
196
-                $this->order_items[ "quantity_{$item_num}" ]  = $line_item->quantity();
195
+                $this->order_items["amount_{$item_num}"]    = $line_item->unit_price();
196
+                $this->order_items["quantity_{$item_num}"]  = $line_item->quantity();
197 197
                 // if we're not letting PayPal calculate shipping, tell them its 0
198
-                if (! $this->paypal_gateway->paypalShipping()) {
199
-                    $this->order_items[ "shipping_{$item_num}" ]  = '0';
200
-                    $this->order_items[ "shipping2_{$item_num}" ] = '0';
198
+                if ( ! $this->paypal_gateway->paypalShipping()) {
199
+                    $this->order_items["shipping_{$item_num}"]  = '0';
200
+                    $this->order_items["shipping2_{$item_num}"] = '0';
201 201
                 }
202 202
                 $this->itemized_order_sum += $line_item->pretaxTotal();
203 203
                 $item_num++;
@@ -232,15 +232,15 @@  discard block
 block discarded – undo
232 232
             $this->total_discounts += abs($itemized_order_sum_difference);
233 233
         } elseif (EEH_Money::compare_floats($itemized_order_sum_difference, 0.00, '>')) {
234 234
             // the itemized order sum is MORE than the transaction total
235
-            $this->order_items[ "item_name_{$item_num}" ] = substr(
235
+            $this->order_items["item_name_{$item_num}"] = substr(
236 236
                 esc_html__('additional charges', 'event_espresso'),
237 237
                 0,
238 238
                 127
239 239
             );
240
-            $this->order_items[ "amount_{$item_num}" ]    = $this->gateway_data_formatter->formatCurrency(
240
+            $this->order_items["amount_{$item_num}"]    = $this->gateway_data_formatter->formatCurrency(
241 241
                 $itemized_order_sum_difference
242 242
             );
243
-            $this->order_items[ "quantity_{$item_num}" ]  = 1;
243
+            $this->order_items["quantity_{$item_num}"]  = 1;
244 244
             $item_num++;
245 245
         }
246 246
         if (EEH_Money::compare_floats($this->total_discounts, 0.00, '>')) {
@@ -259,14 +259,14 @@  discard block
 block discarded – undo
259 259
      */
260 260
     private function addSandboxModeArgs(int $item_num, string $notify_url, string $return_url)
261 261
     {
262
-        $this->order_items[ "item_name_{$item_num}" ] = 'DEBUG INFO (this item only added in sandbox mode';
263
-        $this->order_items[ "amount_{$item_num}" ]    = 0;
264
-        $this->order_items[ "on0_{$item_num}" ]       = 'NOTIFY URL';
265
-        $this->order_items[ "os0_{$item_num}" ]       = $notify_url;
266
-        $this->order_items[ "on1_{$item_num}" ]       = 'RETURN URL';
267
-        $this->order_items[ "os1_{$item_num}" ]       = $return_url;
268
-        $this->order_items[ "shipping_{$item_num}" ]  = '0';
269
-        $this->order_items[ "shipping2_{$item_num}" ] = '0';
262
+        $this->order_items["item_name_{$item_num}"] = 'DEBUG INFO (this item only added in sandbox mode';
263
+        $this->order_items["amount_{$item_num}"]    = 0;
264
+        $this->order_items["on0_{$item_num}"]       = 'NOTIFY URL';
265
+        $this->order_items["os0_{$item_num}"]       = $notify_url;
266
+        $this->order_items["on1_{$item_num}"]       = 'RETURN URL';
267
+        $this->order_items["os1_{$item_num}"]       = $return_url;
268
+        $this->order_items["shipping_{$item_num}"]  = '0';
269
+        $this->order_items["shipping2_{$item_num}"] = '0';
270 270
         // $this->order_items['option_index_' . $item_num] = 1; // <-- dunno if this is needed ?
271 271
     }
272 272
 
@@ -285,9 +285,9 @@  discard block
 block discarded – undo
285 285
         $this->order_items['cmd']           = '_cart';
286 286
         $this->order_items['upload']        = 1;
287 287
         $this->order_items['currency_code'] = $this->payment->currency_code();
288
-        $this->order_items['rm']            = 2;// makes the user return with method=POST
288
+        $this->order_items['rm']            = 2; // makes the user return with method=POST
289 289
         $this->order_items['no_shipping']   = $this->paypal_gateway->shippingDetails();
290
-        $this->order_items['bn']            = 'EventEspresso_SP';// EE will blow up if you change this
290
+        $this->order_items['bn']            = 'EventEspresso_SP'; // EE will blow up if you change this
291 291
         if ($this->paypal_gateway->imageUrl()) {
292 292
             $this->order_items['image_url'] = $this->paypal_gateway->imageUrl();
293 293
         }
Please login to merge, or discard this patch.
ticket_selector_caff/templates/ticket_selector_price_details.template.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -6,17 +6,17 @@  discard block
 block discarded – undo
6 6
  * @var EE_Ticket $ticket
7 7
  */
8 8
 
9
-if (! function_exists('espressoSubtotalRow')) {
9
+if ( ! function_exists('espressoSubtotalRow')) {
10 10
     function espressoSubtotalRow(float $running_total, bool $show = true): string
11 11
     {
12 12
         return $show
13 13
             ? '
14 14
                 <tr>
15 15
                     <td colspan="2" class="jst-rght small-text sbttl">
16
-                        <b>' . esc_html__('subtotal', 'event_espresso') . '</b>
16
+                        <b>' . esc_html__('subtotal', 'event_espresso').'</b>
17 17
                     </td>
18
-                    <td data-th="' . esc_html__('subtotal', 'event_espresso') . '" class="jst-rght small-text">
19
-                        <b>' . EEH_Template::format_currency($running_total) . '</b>
18
+                    <td data-th="' . esc_html__('subtotal', 'event_espresso').'" class="jst-rght small-text">
19
+                        <b>' . EEH_Template::format_currency($running_total).'</b>
20 20
                     </td>
21 21
                 </tr>
22 22
             '
@@ -80,9 +80,9 @@  discard block
 block discarded – undo
80 80
                         $new_sub_total = $price_mod->is_discount()
81 81
                             ? $new_sub_total * -1
82 82
                             : $new_sub_total;
83
-                        $description   = $price_mod->desc() . ' ';
84
-                        $description   .= $price_mod->is_percent()
85
-                            ? $price_mod->amount() . '%'
83
+                        $description   = $price_mod->desc().' ';
84
+                        $description .= $price_mod->is_percent()
85
+                            ? $price_mod->amount().'%'
86 86
                             : EEH_Template::format_currency($price_mod->amount());
87 87
                         ?>
88 88
                         <tr>
Please login to merge, or discard this patch.
Indentation   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -10,10 +10,10 @@  discard block
 block discarded – undo
10 10
  */
11 11
 
12 12
 if (! function_exists('espressoSubtotalRow')) {
13
-    function espressoSubtotalRow(float $running_total, bool $show = true): string
14
-    {
15
-        return $show
16
-            ? '
13
+	function espressoSubtotalRow(float $running_total, bool $show = true): string
14
+	{
15
+		return $show
16
+			? '
17 17
                 <tr>
18 18
                     <td colspan="2" class="jst-rght small-text sbttl">
19 19
                         <b>' . esc_html__('subtotal', 'event_espresso') . '</b>
@@ -23,18 +23,18 @@  discard block
 block discarded – undo
23 23
                     </td>
24 24
                 </tr>
25 25
             '
26
-            : '';
27
-    }
26
+			: '';
27
+	}
28 28
 }
29 29
 
30 30
 if ($display_ticket_price) { ?>
31 31
     <section class="tckt-slctr-tkt-price-sctn">
32 32
         <h5><?php echo esc_html(
33
-            apply_filters(
34
-                'FHEE__ticket_selector_chart_template__ticket_details_price_breakdown_heading',
35
-                __('Price', 'event_espresso')
36
-            )
37
-        ); ?></h5>
33
+			apply_filters(
34
+				'FHEE__ticket_selector_chart_template__ticket_details_price_breakdown_heading',
35
+				__('Price', 'event_espresso')
36
+			)
37
+		); ?></h5>
38 38
         <div class="tckt-slctr-tkt-details-tbl-wrap-dv">
39 39
             <table class="tckt-slctr-tkt-details-tbl">
40 40
                 <thead>
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
                 </thead>
55 55
                 <tbody>
56 56
                     <?php
57
-                    if ($ticket->base_price() instanceof EE_Price) { ?>
57
+					if ($ticket->base_price() instanceof EE_Price) { ?>
58 58
                         <tr>
59 59
                             <td data-th="<?php esc_html_e('Name', 'event_espresso'); ?>" class="small-text" colspan="2">
60 60
                                 <b>
@@ -66,34 +66,34 @@  discard block
 block discarded – undo
66 66
                             </td>
67 67
                         </tr>
68 68
                         <?php
69
-                        $running_total = $ticket->base_price()->amount();
70
-                    } else {
71
-                        $running_total = 0;
72
-                    }
73
-                    $pretax_total     = $running_total;
74
-                    $display_subtotal = true;
75
-                    // now add price modifiers
76
-                    foreach ($ticket->price_modifiers() as $price_mod) {
77
-                        if ($price_mod->is_tax()) {
78
-                            echo wp_kses(
79
-                                espressoSubtotalRow($running_total, $display_subtotal),
80
-                                AllowedTags::getAllowedTags()
81
-                            );
82
-                            $display_subtotal = false;
83
-                            $new_sub_total    = $pretax_total * ($price_mod->amount() / 100);
84
-                        } elseif ($price_mod->is_percent()) {
85
-                            $new_sub_total = $running_total * ($price_mod->amount() / 100);
86
-                        } else {
87
-                            $new_sub_total = $price_mod->amount();
88
-                        }
89
-                        $new_sub_total = $price_mod->is_discount()
90
-                            ? $new_sub_total * -1
91
-                            : $new_sub_total;
92
-                        $description   = $price_mod->desc() . ' ';
93
-                        $description   .= $price_mod->is_percent()
94
-                            ? $price_mod->amount() . '%'
95
-                            : EEH_Template::format_currency($price_mod->amount());
96
-                        ?>
69
+						$running_total = $ticket->base_price()->amount();
70
+					} else {
71
+						$running_total = 0;
72
+					}
73
+					$pretax_total     = $running_total;
74
+					$display_subtotal = true;
75
+					// now add price modifiers
76
+					foreach ($ticket->price_modifiers() as $price_mod) {
77
+						if ($price_mod->is_tax()) {
78
+							echo wp_kses(
79
+								espressoSubtotalRow($running_total, $display_subtotal),
80
+								AllowedTags::getAllowedTags()
81
+							);
82
+							$display_subtotal = false;
83
+							$new_sub_total    = $pretax_total * ($price_mod->amount() / 100);
84
+						} elseif ($price_mod->is_percent()) {
85
+							$new_sub_total = $running_total * ($price_mod->amount() / 100);
86
+						} else {
87
+							$new_sub_total = $price_mod->amount();
88
+						}
89
+						$new_sub_total = $price_mod->is_discount()
90
+							? $new_sub_total * -1
91
+							: $new_sub_total;
92
+						$description   = $price_mod->desc() . ' ';
93
+						$description   .= $price_mod->is_percent()
94
+							? $price_mod->amount() . '%'
95
+							: EEH_Template::format_currency($price_mod->amount());
96
+						?>
97 97
                         <tr>
98 98
                             <td data-th="<?php esc_html_e('Name', 'event_espresso'); ?>"
99 99
                                 class="jst-rght small-text"
@@ -105,20 +105,20 @@  discard block
 block discarded – undo
105 105
                             </td>
106 106
                             <td data-th="<?php esc_html_e('Amount', 'event_espresso'); ?>" class="jst-rght small-text">
107 107
                                 <?php echo wp_kses(
108
-                                    EEH_Template::format_currency($new_sub_total),
109
-                                    AllowedTags::getAllowedTags()
110
-                                ); ?>
108
+									EEH_Template::format_currency($new_sub_total),
109
+									AllowedTags::getAllowedTags()
110
+								); ?>
111 111
                             </td>
112 112
                             <?php $pretax_total += ! $price_mod->is_tax() ? $new_sub_total : 0; ?>
113 113
                             <?php $running_total += $new_sub_total; ?>
114 114
                         </tr>
115 115
                     <?php } ?>
116 116
                     <?php if ($ticket->taxable()) {
117
-                        echo wp_kses(
118
-                            espressoSubtotalRow($running_total),
119
-                            AllowedTags::getAllowedTags()
120
-                        );
121
-                        foreach ($ticket->get_ticket_taxes_for_admin() as $tax) { ?>
117
+						echo wp_kses(
118
+							espressoSubtotalRow($running_total),
119
+							AllowedTags::getAllowedTags()
120
+						);
121
+						foreach ($ticket->get_ticket_taxes_for_admin() as $tax) { ?>
122 122
                             <tr>
123 123
                                 <td data-th="<?php esc_html_e('Name', 'event_espresso'); ?>"
124 124
                                     class="jst-rght small-text"
@@ -135,9 +135,9 @@  discard block
 block discarded – undo
135 135
                                     class="jst-rght small-text"
136 136
                                 >
137 137
                                     <?php echo wp_kses(
138
-                                        EEH_Template::format_currency($tax_amount),
139
-                                        AllowedTags::getAllowedTags()
140
-                                    ); ?>
138
+										EEH_Template::format_currency($tax_amount),
139
+										AllowedTags::getAllowedTags()
140
+									); ?>
141 141
                                 </td>
142 142
                                 <?php $running_total += $tax_amount; ?>
143 143
                             </tr>
@@ -147,24 +147,24 @@  discard block
 block discarded – undo
147 147
                         <td colspan="2" class="jst-rght small-text ttl-lbl-td">
148 148
                             <b>
149 149
                                 <?php echo esc_html(
150
-                                    apply_filters(
151
-                                        'FHEE__ticket_selector_chart_template__ticket_details_total_price',
152
-                                        __('Total', 'event_espresso')
153
-                                    )
154
-                                ); ?>
150
+									apply_filters(
151
+										'FHEE__ticket_selector_chart_template__ticket_details_total_price',
152
+										__('Total', 'event_espresso')
153
+									)
154
+								); ?>
155 155
                             </b>
156 156
                         </td>
157 157
                         <td data-th="<?php echo esc_html(
158
-                            apply_filters(
159
-                                'FHEE__ticket_selector_chart_template__ticket_details_total_price',
160
-                                __('Total', 'event_espresso')
161
-                            )
162
-                        ); ?>" class="jst-rght small-text"
158
+							apply_filters(
159
+								'FHEE__ticket_selector_chart_template__ticket_details_total_price',
160
+								__('Total', 'event_espresso')
161
+							)
162
+						); ?>" class="jst-rght small-text"
163 163
                         >
164 164
                             <b><?php echo wp_kses(
165
-                                EEH_Template::format_currency($running_total),
166
-                                AllowedTags::getAllowedTags()
167
-                            ); ?></b>
165
+								EEH_Template::format_currency($running_total),
166
+								AllowedTags::getAllowedTags()
167
+							); ?></b>
168 168
                         </td>
169 169
                     </tr>
170 170
                 </tbody>
Please login to merge, or discard this patch.
modules/ticket_selector/TicketSelector.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -118,13 +118,13 @@
 block discarded – undo
118 118
     public function getHiddenInputs()
119 119
     {
120 120
         $html = '<input type="hidden" name="noheader" value="true"/>';
121
-        $html .= '<input type="hidden" name="tkt-slctr-return-url-' . $this->event->ID() . '"';
122
-        $html .= ' value="' . EEH_URL::current_url() . $this->template_args['anchor_id'] . '"/>';
123
-        $html .= '<input type="hidden" name="tkt-slctr-rows-' . $this->event->ID();
124
-        $html .= '" value="' . $this->ticket_rows . '"/>';
125
-        $html .= '<input type="hidden" name="tkt-slctr-max-atndz-' . $this->event->ID();
126
-        $html .= '" value="' . $this->template_args['max_atndz'] . '"/>';
127
-        $html .= '<input type="hidden" name="tkt-slctr-event-id" value="' . $this->event->ID() . '"/>';
121
+        $html .= '<input type="hidden" name="tkt-slctr-return-url-'.$this->event->ID().'"';
122
+        $html .= ' value="'.EEH_URL::current_url().$this->template_args['anchor_id'].'"/>';
123
+        $html .= '<input type="hidden" name="tkt-slctr-rows-'.$this->event->ID();
124
+        $html .= '" value="'.$this->ticket_rows.'"/>';
125
+        $html .= '<input type="hidden" name="tkt-slctr-max-atndz-'.$this->event->ID();
126
+        $html .= '" value="'.$this->template_args['max_atndz'].'"/>';
127
+        $html .= '<input type="hidden" name="tkt-slctr-event-id" value="'.$this->event->ID().'"/>';
128 128
         return $html;
129 129
     }
130 130
 }
Please login to merge, or discard this patch.
Indentation   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -19,111 +19,111 @@
 block discarded – undo
19 19
  */
20 20
 abstract class TicketSelector
21 21
 {
22
-    /**
23
-     * @var EE_Event
24
-     */
25
-    protected $event;
26
-
27
-    /**
28
-     * @var EE_Ticket[]
29
-     */
30
-    protected $tickets;
31
-
32
-    /**
33
-     * @var int
34
-     */
35
-    protected $max_attendees;
36
-
37
-    /**
38
-     * @var array
39
-     */
40
-    protected $template_args;
41
-
42
-    /**
43
-     * @var int
44
-     */
45
-    protected $ticket_rows = 0;
46
-
47
-
48
-    /**
49
-     * TicketSelectorSimple constructor.
50
-     *
51
-     * @param EE_Event    $event
52
-     * @param EE_Ticket[] $tickets
53
-     * @param int          $max_attendees
54
-     * @param array        $template_args
55
-     */
56
-    public function __construct(EE_Event $event, array $tickets, $max_attendees, array $template_args)
57
-    {
58
-        $this->event = $event;
59
-        $this->tickets = $tickets;
60
-        $this->max_attendees = $max_attendees;
61
-        $this->template_args = $template_args;
62
-        $this->addTemplateArgs();
63
-    }
64
-
65
-
66
-    /**
67
-     * sets any and all template args that are required for this Ticket Selector
68
-     *
69
-     * @return void
70
-     */
71
-    abstract protected function addTemplateArgs();
72
-
73
-
74
-    /**
75
-     * loadTicketSelectorTemplate
76
-     *
77
-     * @return string
78
-     */
79
-    protected function loadTicketSelectorTemplate()
80
-    {
81
-        try {
82
-            $this->template_args['hidden_inputs'] = $this->getHiddenInputs();
83
-            return EEH_Template::locate_template(
84
-                apply_filters(
85
-                    'FHEE__EE_Ticket_Selector__display_ticket_selector__template_path',
86
-                    $this->template_args['template_path'],
87
-                    $this->event
88
-                ),
89
-                $this->template_args
90
-            );
91
-        } catch (Exception $e) {
92
-            EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
93
-        }
94
-        return '';
95
-    }
96
-
97
-
98
-    /**
99
-     * The __toString method allows a class to decide how it will react when it is converted to a string.
100
-     *
101
-     * @return string
102
-     * @link http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring
103
-     */
104
-    public function __toString()
105
-    {
106
-        return $this->loadTicketSelectorTemplate();
107
-    }
108
-
109
-
110
-    /**
111
-     * getHiddenInputs
112
-     *
113
-     * @return string
114
-     * @throws EE_Error
115
-     * @throws ReflectionException
116
-     */
117
-    public function getHiddenInputs()
118
-    {
119
-        $html = '<input type="hidden" name="noheader" value="true"/>';
120
-        $html .= '<input type="hidden" name="tkt-slctr-return-url-' . $this->event->ID() . '"';
121
-        $html .= ' value="' . EEH_URL::current_url() . $this->template_args['anchor_id'] . '"/>';
122
-        $html .= '<input type="hidden" name="tkt-slctr-rows-' . $this->event->ID();
123
-        $html .= '" value="' . $this->ticket_rows . '"/>';
124
-        $html .= '<input type="hidden" name="tkt-slctr-max-atndz-' . $this->event->ID();
125
-        $html .= '" value="' . $this->template_args['max_atndz'] . '"/>';
126
-        $html .= '<input type="hidden" name="tkt-slctr-event-id" value="' . $this->event->ID() . '"/>';
127
-        return $html;
128
-    }
22
+	/**
23
+	 * @var EE_Event
24
+	 */
25
+	protected $event;
26
+
27
+	/**
28
+	 * @var EE_Ticket[]
29
+	 */
30
+	protected $tickets;
31
+
32
+	/**
33
+	 * @var int
34
+	 */
35
+	protected $max_attendees;
36
+
37
+	/**
38
+	 * @var array
39
+	 */
40
+	protected $template_args;
41
+
42
+	/**
43
+	 * @var int
44
+	 */
45
+	protected $ticket_rows = 0;
46
+
47
+
48
+	/**
49
+	 * TicketSelectorSimple constructor.
50
+	 *
51
+	 * @param EE_Event    $event
52
+	 * @param EE_Ticket[] $tickets
53
+	 * @param int          $max_attendees
54
+	 * @param array        $template_args
55
+	 */
56
+	public function __construct(EE_Event $event, array $tickets, $max_attendees, array $template_args)
57
+	{
58
+		$this->event = $event;
59
+		$this->tickets = $tickets;
60
+		$this->max_attendees = $max_attendees;
61
+		$this->template_args = $template_args;
62
+		$this->addTemplateArgs();
63
+	}
64
+
65
+
66
+	/**
67
+	 * sets any and all template args that are required for this Ticket Selector
68
+	 *
69
+	 * @return void
70
+	 */
71
+	abstract protected function addTemplateArgs();
72
+
73
+
74
+	/**
75
+	 * loadTicketSelectorTemplate
76
+	 *
77
+	 * @return string
78
+	 */
79
+	protected function loadTicketSelectorTemplate()
80
+	{
81
+		try {
82
+			$this->template_args['hidden_inputs'] = $this->getHiddenInputs();
83
+			return EEH_Template::locate_template(
84
+				apply_filters(
85
+					'FHEE__EE_Ticket_Selector__display_ticket_selector__template_path',
86
+					$this->template_args['template_path'],
87
+					$this->event
88
+				),
89
+				$this->template_args
90
+			);
91
+		} catch (Exception $e) {
92
+			EE_Error::add_error($e->getMessage(), __FILE__, __FUNCTION__, __LINE__);
93
+		}
94
+		return '';
95
+	}
96
+
97
+
98
+	/**
99
+	 * The __toString method allows a class to decide how it will react when it is converted to a string.
100
+	 *
101
+	 * @return string
102
+	 * @link http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.tostring
103
+	 */
104
+	public function __toString()
105
+	{
106
+		return $this->loadTicketSelectorTemplate();
107
+	}
108
+
109
+
110
+	/**
111
+	 * getHiddenInputs
112
+	 *
113
+	 * @return string
114
+	 * @throws EE_Error
115
+	 * @throws ReflectionException
116
+	 */
117
+	public function getHiddenInputs()
118
+	{
119
+		$html = '<input type="hidden" name="noheader" value="true"/>';
120
+		$html .= '<input type="hidden" name="tkt-slctr-return-url-' . $this->event->ID() . '"';
121
+		$html .= ' value="' . EEH_URL::current_url() . $this->template_args['anchor_id'] . '"/>';
122
+		$html .= '<input type="hidden" name="tkt-slctr-rows-' . $this->event->ID();
123
+		$html .= '" value="' . $this->ticket_rows . '"/>';
124
+		$html .= '<input type="hidden" name="tkt-slctr-max-atndz-' . $this->event->ID();
125
+		$html .= '" value="' . $this->template_args['max_atndz'] . '"/>';
126
+		$html .= '<input type="hidden" name="tkt-slctr-event-id" value="' . $this->event->ID() . '"/>';
127
+		return $html;
128
+	}
129 129
 }
Please login to merge, or discard this patch.
core/services/request/RequestParams.php 2 patches
Spacing   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -17,13 +17,13 @@  discard block
 block discarded – undo
17 17
      * Used for matches() and parameterDrillDown()
18 18
      * 'bool' will return true or false if match is found or not
19 19
      */
20
-    const RETURN_BOOL  = 'bool';
20
+    const RETURN_BOOL = 'bool';
21 21
 
22 22
     /**
23 23
      * Used for matches() and parameterDrillDown()
24 24
      * 'key' will return the first key found that matches the supplied pattern
25 25
      */
26
-    const RETURN_KEY   = 'key';
26
+    const RETURN_KEY = 'key';
27 27
 
28 28
     /**
29 29
      * Used for matches() and parameterDrillDown()
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
     {
114 114
         // don't allow "ee" to be overwritten unless explicitly instructed to do so
115 115
         if ($override_ee || $key !== 'ee' || empty($this->request['ee'])) {
116
-            $this->request[ $key ] = $value;
116
+            $this->request[$key] = $value;
117 117
         }
118 118
     }
119 119
 
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
             preg_quote($pattern, '/')
238 238
         );
239 239
         foreach ($request_params as $key => $request_param) {
240
-            if (preg_match('/^' . $pattern . '$/is', $key)) {
240
+            if (preg_match('/^'.$pattern.'$/is', $key)) {
241 241
                 // return value for request param
242 242
                 if ($return === self::RETURN_VALUE) {
243 243
                     return $request_param;
@@ -299,30 +299,30 @@  discard block
 block discarded – undo
299 299
                 $key      = $real_key ?: $key;
300 300
             }
301 301
             // check if top level key exists
302
-            if (isset($request_params[ $key ])) {
302
+            if (isset($request_params[$key])) {
303 303
                 // build a new key to pass along like: 'second[third]'
304 304
                 // or just 'second' depending on depth of keys
305 305
                 $key_string = array_shift($keys);
306
-                if (! empty($keys)) {
307
-                    $key_string .= '[' . implode('][', $keys) . ']';
306
+                if ( ! empty($keys)) {
307
+                    $key_string .= '['.implode('][', $keys).']';
308 308
                 }
309 309
                 return $this->parameterDrillDown(
310 310
                     $key_string,
311 311
                     $default,
312 312
                     $callback,
313 313
                     $return,
314
-                    $request_params[ $key ]
314
+                    $request_params[$key]
315 315
                 );
316 316
             }
317 317
         }
318 318
         if ($callback === 'is_set') {
319
-            return isset($request_params[ $key ]);
319
+            return isset($request_params[$key]);
320 320
         }
321 321
         if ($callback === 'match') {
322 322
             return $this->match($key, $request_params, $default, $return);
323 323
         }
324
-        return isset($request_params[ $key ])
325
-            ? $request_params[ $key ]
324
+        return isset($request_params[$key])
325
+            ? $request_params[$key]
326 326
             : $default;
327 327
     }
328 328
 
@@ -336,12 +336,12 @@  discard block
 block discarded – undo
336 336
     public function unSetRequestParam($key, $unset_from_global_too = false)
337 337
     {
338 338
         // because unset may not actually remove var
339
-        $this->get[ $key ]     = null;
340
-        $this->post[ $key ]    = null;
341
-        $this->request[ $key ] = null;
342
-        unset($this->get[ $key ], $this->post[ $key ], $this->request[ $key ]);
339
+        $this->get[$key]     = null;
340
+        $this->post[$key]    = null;
341
+        $this->request[$key] = null;
342
+        unset($this->get[$key], $this->post[$key], $this->request[$key]);
343 343
         if ($unset_from_global_too) {
344
-            unset($_GET[ $key ], $_POST[ $key ], $_REQUEST[ $key ]);
344
+            unset($_GET[$key], $_POST[$key], $_REQUEST[$key]);
345 345
         }
346 346
     }
347 347
 
Please login to merge, or discard this patch.
Indentation   +353 added lines, -353 removed lines patch added patch discarded remove patch
@@ -13,357 +13,357 @@
 block discarded – undo
13 13
  */
14 14
 class RequestParams
15 15
 {
16
-    /**
17
-     * Used for matches() and parameterDrillDown()
18
-     * 'bool' will return true or false if match is found or not
19
-     */
20
-    const RETURN_BOOL  = 'bool';
21
-
22
-    /**
23
-     * Used for matches() and parameterDrillDown()
24
-     * 'key' will return the first key found that matches the supplied pattern
25
-     */
26
-    const RETURN_KEY   = 'key';
27
-
28
-    /**
29
-     * Used for matches() and parameterDrillDown()
30
-     * 'value' will return the value for the first request parameter
31
-     */
32
-    const RETURN_VALUE = 'value';
33
-
34
-    /**
35
-     * $_GET parameters
36
-     *
37
-     * @var array
38
-     */
39
-    protected $get;
40
-
41
-    /**
42
-     * $_POST parameters
43
-     *
44
-     * @var array
45
-     */
46
-    protected $post;
47
-
48
-    /**
49
-     * $_REQUEST parameters
50
-     *
51
-     * @var array
52
-     */
53
-    protected $request;
54
-
55
-    /**
56
-     * @var RequestSanitizer
57
-     */
58
-    protected $sanitizer;
59
-
60
-
61
-    /**
62
-     * RequestParams constructor.
63
-     *
64
-     * @param RequestSanitizer $sanitizer
65
-     * @param array            $get
66
-     * @param array            $post
67
-     */
68
-    public function __construct(RequestSanitizer $sanitizer, array $get = [], array $post = [])
69
-    {
70
-        $this->sanitizer = $sanitizer;
71
-        $this->get       = $get;
72
-        $this->post      = $post;
73
-        $this->request   = array_merge($this->get, $this->post);
74
-    }
75
-
76
-
77
-    /**
78
-     * @return array
79
-     */
80
-    public function getParams()
81
-    {
82
-        return $this->get;
83
-    }
84
-
85
-
86
-    /**
87
-     * @return array
88
-     */
89
-    public function postParams()
90
-    {
91
-        return $this->post;
92
-    }
93
-
94
-
95
-    /**
96
-     * returns contents of $_REQUEST
97
-     *
98
-     * @return array
99
-     */
100
-    public function requestParams()
101
-    {
102
-        return $this->request;
103
-    }
104
-
105
-
106
-    /**
107
-     * @param string     $key
108
-     * @param mixed|null $value
109
-     * @param bool       $override_ee
110
-     * @return    void
111
-     */
112
-    public function setRequestParam($key, $value, $override_ee = false)
113
-    {
114
-        // don't allow "ee" to be overwritten unless explicitly instructed to do so
115
-        if ($override_ee || $key !== 'ee' || empty($this->request['ee'])) {
116
-            $this->request[ $key ] = $value;
117
-        }
118
-    }
119
-
120
-
121
-    /**
122
-     * merges the incoming array of parameters into the existing request parameters
123
-     *
124
-     * @param array $request_params
125
-     * @return void
126
-     * @since   4.10.24.p
127
-     */
128
-    public function mergeRequestParams(array $request_params)
129
-    {
130
-        $this->request = array_merge($this->request, $request_params);
131
-    }
132
-
133
-
134
-    /**
135
-     * returns   the value for a request param if the given key exists
136
-     *
137
-     * @param string     $key
138
-     * @param mixed|null $default
139
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc.
140
-     *                              DataType::ARRAY should only be used to indicate an array containing mixed types,
141
-     *                              ideally another data type should be selected to indicate the contents of the array,
142
-     *                              and then $is_array should be set to true. ie: an array of integers would be:
143
-     *                                  $type = DataType::INT
144
-     *                                  $is_array = true
145
-     * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
146
-     * @param string     $delimiter for CSV type strings that should be returned as an array
147
-     * @return array|bool|float|int|string
148
-     */
149
-    public function getRequestParam($key, $default = null, $type = DataType::STRING, $is_array = false, $delimiter = '')
150
-    {
151
-        // ensure $is_array is true if the data type is set as such
152
-        $is_array = $type === DataType::ARRAY ? true : $is_array;
153
-        $param = $this->sanitizer->clean(
154
-            $this->parameterDrillDown($key, $default, 'get'),
155
-            $type,
156
-            $is_array,
157
-            $delimiter
158
-        );
159
-        // don't convert final return value to something else if an array is expected
160
-        $type = $is_array ? DataType::ARRAY : $type;
161
-        return DataType::setDataType($param, $type);
162
-    }
163
-
164
-
165
-    /**
166
-     * check if param exists
167
-     *
168
-     * @param string $key
169
-     * @return bool
170
-     */
171
-    public function requestParamIsSet($key)
172
-    {
173
-        return (bool) $this->parameterDrillDown($key);
174
-    }
175
-
176
-
177
-    /**
178
-     * check if a request parameter exists whose key that matches the supplied wildcard pattern
179
-     * and return the value for the first match found
180
-     * wildcards can be either of the following:
181
-     *      ? to represent a single character of any type
182
-     *      * to represent one or more characters of any type
183
-     *
184
-     * @param string     $pattern
185
-     * @param mixed|null $default
186
-     * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
187
-     * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
188
-     * @param string     $delimiter for CSV type strings that should be returned as an array
189
-     * @return array|bool|float|int|string
190
-     */
191
-    public function getMatch($pattern, $default = null, $type = DataType::STRING, $is_array = false, $delimiter = '')
192
-    {
193
-        $param = $this->sanitizer->clean(
194
-            $this->parameterDrillDown($pattern, $default, 'match'),
195
-            $type,
196
-            $is_array,
197
-            $delimiter
198
-        );
199
-        $type = $is_array ? 'array' : $type;
200
-        return DataType::setDataType($param, $type);
201
-    }
202
-
203
-
204
-    /**
205
-     * check if a request parameter exists whose key matches the supplied wildcard pattern
206
-     * wildcards can be either of the following:
207
-     *      ? to represent a single character of any type
208
-     *      * to represent one or more characters of any type
209
-     * returns true if a match is found or false if not
210
-     *
211
-     * @param string $pattern
212
-     * @return bool
213
-     */
214
-    public function matches($pattern)
215
-    {
216
-        return (bool) $this->parameterDrillDown($pattern, false, 'match', self::RETURN_BOOL);
217
-    }
218
-
219
-
220
-    /**
221
-     * @see https://stackoverflow.com/questions/6163055/php-string-matching-with-wildcard
222
-     * @param string $pattern               A string including wildcards to be converted to a regex pattern
223
-     *                                      and used to search through the current request's parameter keys
224
-     * @param array  $request_params        The array of request parameters to search through
225
-     * @param mixed  $default               [optional] The value to be returned if no match is found.
226
-     *                                      Default is null
227
-     * @param string $return                [optional] Controls what kind of value is returned.
228
-     *                                      Options are the RETURN_* constants:
229
-     *                                      RETURN_BOOL will return true or false if match is found or not
230
-     *                                      RETURN_KEY will return the first key found that matches the supplied pattern
231
-     *                                      RETURN_VALUE will return the value for the first request parameter
232
-     *                                      whose key matches the supplied pattern
233
-     *                                      Default is 'value'
234
-     * @return boolean|string
235
-     */
236
-    private function match($pattern, array $request_params, $default = null, $return = self::RETURN_VALUE)
237
-    {
238
-        $return = in_array($return, [self::RETURN_BOOL, self::RETURN_KEY, self::RETURN_VALUE], true)
239
-            ? $return
240
-            : 'is_set';
241
-        // replace wildcard chars with regex chars
242
-        $pattern = str_replace(
243
-            ['\*', '\?'],
244
-            ['.*', '.'],
245
-            preg_quote($pattern, '/')
246
-        );
247
-        foreach ($request_params as $key => $request_param) {
248
-            if (preg_match('/^' . $pattern . '$/is', $key)) {
249
-                // return value for request param
250
-                if ($return === self::RETURN_VALUE) {
251
-                    return $request_param;
252
-                }
253
-                // or actual key or true just to indicate it was found
254
-                return $return === self::RETURN_KEY ? $key : true;
255
-            }
256
-        }
257
-        // match not found so return default value or false
258
-        return $return === self::RETURN_VALUE ? $default : false;
259
-    }
260
-
261
-
262
-    /**
263
-     * the supplied key can be a simple string to represent a "top-level" request parameter
264
-     * or represent a key for a request parameter that is nested deeper within the request parameter array,
265
-     * by using square brackets to surround keys for deeper array elements.
266
-     * For example :
267
-     * if the supplied $key was: "first[second][third]"
268
-     * then this will attempt to drill down into the request parameter array to find a value.
269
-     * Given the following request parameters:
270
-     *  array(
271
-     *      'first' => array(
272
-     *          'second' => array(
273
-     *              'third' => 'has a value'
274
-     *          )
275
-     *      )
276
-     *  )
277
-     * would return true if default parameters were set
278
-     *
279
-     * @param string $callback
280
-     * @param        $key
281
-     * @param null   $default
282
-     * @param string $return
283
-     * @param mixed  $request_params
284
-     * @return bool|mixed|null
285
-     */
286
-    private function parameterDrillDown(
287
-        $key,
288
-        $default = null,
289
-        $callback = 'is_set',
290
-        $return = self::RETURN_VALUE,
291
-        $request_params = []
292
-    ) {
293
-        $callback       = in_array($callback, ['is_set', 'get', 'match'], true)
294
-            ? $callback
295
-            : 'is_set';
296
-        $request_params = ! empty($request_params)
297
-            ? $request_params
298
-            : $this->request;
299
-        // does incoming key represent an array like 'first[second][third]'  ?
300
-        if (strpos($key, '[') !== false) {
301
-            // turn it into an actual array
302
-            $key  = str_replace(']', '', $key);
303
-            $keys = explode('[', $key);
304
-            $key  = array_shift($keys);
305
-            if ($callback === 'match') {
306
-                $real_key = $this->match($key, $request_params, $default, self::RETURN_KEY);
307
-                $key      = $real_key ?: $key;
308
-            }
309
-            // check if top level key exists
310
-            if (isset($request_params[ $key ])) {
311
-                // build a new key to pass along like: 'second[third]'
312
-                // or just 'second' depending on depth of keys
313
-                $key_string = array_shift($keys);
314
-                if (! empty($keys)) {
315
-                    $key_string .= '[' . implode('][', $keys) . ']';
316
-                }
317
-                return $this->parameterDrillDown(
318
-                    $key_string,
319
-                    $default,
320
-                    $callback,
321
-                    $return,
322
-                    $request_params[ $key ]
323
-                );
324
-            }
325
-        }
326
-        if ($callback === 'is_set') {
327
-            return isset($request_params[ $key ]);
328
-        }
329
-        if ($callback === 'match') {
330
-            return $this->match($key, $request_params, $default, $return);
331
-        }
332
-        return isset($request_params[ $key ])
333
-            ? $request_params[ $key ]
334
-            : $default;
335
-    }
336
-
337
-
338
-    /**
339
-     * remove param
340
-     *
341
-     * @param      $key
342
-     * @param bool $unset_from_global_too
343
-     */
344
-    public function unSetRequestParam($key, $unset_from_global_too = false)
345
-    {
346
-        // because unset may not actually remove var
347
-        $this->get[ $key ]     = null;
348
-        $this->post[ $key ]    = null;
349
-        $this->request[ $key ] = null;
350
-        unset($this->get[ $key ], $this->post[ $key ], $this->request[ $key ]);
351
-        if ($unset_from_global_too) {
352
-            unset($_GET[ $key ], $_POST[ $key ], $_REQUEST[ $key ]);
353
-        }
354
-    }
355
-
356
-
357
-    /**
358
-     * remove params
359
-     *
360
-     * @param array $keys
361
-     * @param bool  $unset_from_global_too
362
-     */
363
-    public function unSetRequestParams(array $keys, $unset_from_global_too = false)
364
-    {
365
-        foreach ($keys as $key) {
366
-            $this->unSetRequestParam($key, $unset_from_global_too);
367
-        }
368
-    }
16
+	/**
17
+	 * Used for matches() and parameterDrillDown()
18
+	 * 'bool' will return true or false if match is found or not
19
+	 */
20
+	const RETURN_BOOL  = 'bool';
21
+
22
+	/**
23
+	 * Used for matches() and parameterDrillDown()
24
+	 * 'key' will return the first key found that matches the supplied pattern
25
+	 */
26
+	const RETURN_KEY   = 'key';
27
+
28
+	/**
29
+	 * Used for matches() and parameterDrillDown()
30
+	 * 'value' will return the value for the first request parameter
31
+	 */
32
+	const RETURN_VALUE = 'value';
33
+
34
+	/**
35
+	 * $_GET parameters
36
+	 *
37
+	 * @var array
38
+	 */
39
+	protected $get;
40
+
41
+	/**
42
+	 * $_POST parameters
43
+	 *
44
+	 * @var array
45
+	 */
46
+	protected $post;
47
+
48
+	/**
49
+	 * $_REQUEST parameters
50
+	 *
51
+	 * @var array
52
+	 */
53
+	protected $request;
54
+
55
+	/**
56
+	 * @var RequestSanitizer
57
+	 */
58
+	protected $sanitizer;
59
+
60
+
61
+	/**
62
+	 * RequestParams constructor.
63
+	 *
64
+	 * @param RequestSanitizer $sanitizer
65
+	 * @param array            $get
66
+	 * @param array            $post
67
+	 */
68
+	public function __construct(RequestSanitizer $sanitizer, array $get = [], array $post = [])
69
+	{
70
+		$this->sanitizer = $sanitizer;
71
+		$this->get       = $get;
72
+		$this->post      = $post;
73
+		$this->request   = array_merge($this->get, $this->post);
74
+	}
75
+
76
+
77
+	/**
78
+	 * @return array
79
+	 */
80
+	public function getParams()
81
+	{
82
+		return $this->get;
83
+	}
84
+
85
+
86
+	/**
87
+	 * @return array
88
+	 */
89
+	public function postParams()
90
+	{
91
+		return $this->post;
92
+	}
93
+
94
+
95
+	/**
96
+	 * returns contents of $_REQUEST
97
+	 *
98
+	 * @return array
99
+	 */
100
+	public function requestParams()
101
+	{
102
+		return $this->request;
103
+	}
104
+
105
+
106
+	/**
107
+	 * @param string     $key
108
+	 * @param mixed|null $value
109
+	 * @param bool       $override_ee
110
+	 * @return    void
111
+	 */
112
+	public function setRequestParam($key, $value, $override_ee = false)
113
+	{
114
+		// don't allow "ee" to be overwritten unless explicitly instructed to do so
115
+		if ($override_ee || $key !== 'ee' || empty($this->request['ee'])) {
116
+			$this->request[ $key ] = $value;
117
+		}
118
+	}
119
+
120
+
121
+	/**
122
+	 * merges the incoming array of parameters into the existing request parameters
123
+	 *
124
+	 * @param array $request_params
125
+	 * @return void
126
+	 * @since   4.10.24.p
127
+	 */
128
+	public function mergeRequestParams(array $request_params)
129
+	{
130
+		$this->request = array_merge($this->request, $request_params);
131
+	}
132
+
133
+
134
+	/**
135
+	 * returns   the value for a request param if the given key exists
136
+	 *
137
+	 * @param string     $key
138
+	 * @param mixed|null $default
139
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc.
140
+	 *                              DataType::ARRAY should only be used to indicate an array containing mixed types,
141
+	 *                              ideally another data type should be selected to indicate the contents of the array,
142
+	 *                              and then $is_array should be set to true. ie: an array of integers would be:
143
+	 *                                  $type = DataType::INT
144
+	 *                                  $is_array = true
145
+	 * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
146
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
147
+	 * @return array|bool|float|int|string
148
+	 */
149
+	public function getRequestParam($key, $default = null, $type = DataType::STRING, $is_array = false, $delimiter = '')
150
+	{
151
+		// ensure $is_array is true if the data type is set as such
152
+		$is_array = $type === DataType::ARRAY ? true : $is_array;
153
+		$param = $this->sanitizer->clean(
154
+			$this->parameterDrillDown($key, $default, 'get'),
155
+			$type,
156
+			$is_array,
157
+			$delimiter
158
+		);
159
+		// don't convert final return value to something else if an array is expected
160
+		$type = $is_array ? DataType::ARRAY : $type;
161
+		return DataType::setDataType($param, $type);
162
+	}
163
+
164
+
165
+	/**
166
+	 * check if param exists
167
+	 *
168
+	 * @param string $key
169
+	 * @return bool
170
+	 */
171
+	public function requestParamIsSet($key)
172
+	{
173
+		return (bool) $this->parameterDrillDown($key);
174
+	}
175
+
176
+
177
+	/**
178
+	 * check if a request parameter exists whose key that matches the supplied wildcard pattern
179
+	 * and return the value for the first match found
180
+	 * wildcards can be either of the following:
181
+	 *      ? to represent a single character of any type
182
+	 *      * to represent one or more characters of any type
183
+	 *
184
+	 * @param string     $pattern
185
+	 * @param mixed|null $default
186
+	 * @param string     $type      the expected data type for the parameter's value, ie: string, int, bool, etc
187
+	 * @param bool       $is_array  if true, then parameter value will be treated as an array of $type
188
+	 * @param string     $delimiter for CSV type strings that should be returned as an array
189
+	 * @return array|bool|float|int|string
190
+	 */
191
+	public function getMatch($pattern, $default = null, $type = DataType::STRING, $is_array = false, $delimiter = '')
192
+	{
193
+		$param = $this->sanitizer->clean(
194
+			$this->parameterDrillDown($pattern, $default, 'match'),
195
+			$type,
196
+			$is_array,
197
+			$delimiter
198
+		);
199
+		$type = $is_array ? 'array' : $type;
200
+		return DataType::setDataType($param, $type);
201
+	}
202
+
203
+
204
+	/**
205
+	 * check if a request parameter exists whose key matches the supplied wildcard pattern
206
+	 * wildcards can be either of the following:
207
+	 *      ? to represent a single character of any type
208
+	 *      * to represent one or more characters of any type
209
+	 * returns true if a match is found or false if not
210
+	 *
211
+	 * @param string $pattern
212
+	 * @return bool
213
+	 */
214
+	public function matches($pattern)
215
+	{
216
+		return (bool) $this->parameterDrillDown($pattern, false, 'match', self::RETURN_BOOL);
217
+	}
218
+
219
+
220
+	/**
221
+	 * @see https://stackoverflow.com/questions/6163055/php-string-matching-with-wildcard
222
+	 * @param string $pattern               A string including wildcards to be converted to a regex pattern
223
+	 *                                      and used to search through the current request's parameter keys
224
+	 * @param array  $request_params        The array of request parameters to search through
225
+	 * @param mixed  $default               [optional] The value to be returned if no match is found.
226
+	 *                                      Default is null
227
+	 * @param string $return                [optional] Controls what kind of value is returned.
228
+	 *                                      Options are the RETURN_* constants:
229
+	 *                                      RETURN_BOOL will return true or false if match is found or not
230
+	 *                                      RETURN_KEY will return the first key found that matches the supplied pattern
231
+	 *                                      RETURN_VALUE will return the value for the first request parameter
232
+	 *                                      whose key matches the supplied pattern
233
+	 *                                      Default is 'value'
234
+	 * @return boolean|string
235
+	 */
236
+	private function match($pattern, array $request_params, $default = null, $return = self::RETURN_VALUE)
237
+	{
238
+		$return = in_array($return, [self::RETURN_BOOL, self::RETURN_KEY, self::RETURN_VALUE], true)
239
+			? $return
240
+			: 'is_set';
241
+		// replace wildcard chars with regex chars
242
+		$pattern = str_replace(
243
+			['\*', '\?'],
244
+			['.*', '.'],
245
+			preg_quote($pattern, '/')
246
+		);
247
+		foreach ($request_params as $key => $request_param) {
248
+			if (preg_match('/^' . $pattern . '$/is', $key)) {
249
+				// return value for request param
250
+				if ($return === self::RETURN_VALUE) {
251
+					return $request_param;
252
+				}
253
+				// or actual key or true just to indicate it was found
254
+				return $return === self::RETURN_KEY ? $key : true;
255
+			}
256
+		}
257
+		// match not found so return default value or false
258
+		return $return === self::RETURN_VALUE ? $default : false;
259
+	}
260
+
261
+
262
+	/**
263
+	 * the supplied key can be a simple string to represent a "top-level" request parameter
264
+	 * or represent a key for a request parameter that is nested deeper within the request parameter array,
265
+	 * by using square brackets to surround keys for deeper array elements.
266
+	 * For example :
267
+	 * if the supplied $key was: "first[second][third]"
268
+	 * then this will attempt to drill down into the request parameter array to find a value.
269
+	 * Given the following request parameters:
270
+	 *  array(
271
+	 *      'first' => array(
272
+	 *          'second' => array(
273
+	 *              'third' => 'has a value'
274
+	 *          )
275
+	 *      )
276
+	 *  )
277
+	 * would return true if default parameters were set
278
+	 *
279
+	 * @param string $callback
280
+	 * @param        $key
281
+	 * @param null   $default
282
+	 * @param string $return
283
+	 * @param mixed  $request_params
284
+	 * @return bool|mixed|null
285
+	 */
286
+	private function parameterDrillDown(
287
+		$key,
288
+		$default = null,
289
+		$callback = 'is_set',
290
+		$return = self::RETURN_VALUE,
291
+		$request_params = []
292
+	) {
293
+		$callback       = in_array($callback, ['is_set', 'get', 'match'], true)
294
+			? $callback
295
+			: 'is_set';
296
+		$request_params = ! empty($request_params)
297
+			? $request_params
298
+			: $this->request;
299
+		// does incoming key represent an array like 'first[second][third]'  ?
300
+		if (strpos($key, '[') !== false) {
301
+			// turn it into an actual array
302
+			$key  = str_replace(']', '', $key);
303
+			$keys = explode('[', $key);
304
+			$key  = array_shift($keys);
305
+			if ($callback === 'match') {
306
+				$real_key = $this->match($key, $request_params, $default, self::RETURN_KEY);
307
+				$key      = $real_key ?: $key;
308
+			}
309
+			// check if top level key exists
310
+			if (isset($request_params[ $key ])) {
311
+				// build a new key to pass along like: 'second[third]'
312
+				// or just 'second' depending on depth of keys
313
+				$key_string = array_shift($keys);
314
+				if (! empty($keys)) {
315
+					$key_string .= '[' . implode('][', $keys) . ']';
316
+				}
317
+				return $this->parameterDrillDown(
318
+					$key_string,
319
+					$default,
320
+					$callback,
321
+					$return,
322
+					$request_params[ $key ]
323
+				);
324
+			}
325
+		}
326
+		if ($callback === 'is_set') {
327
+			return isset($request_params[ $key ]);
328
+		}
329
+		if ($callback === 'match') {
330
+			return $this->match($key, $request_params, $default, $return);
331
+		}
332
+		return isset($request_params[ $key ])
333
+			? $request_params[ $key ]
334
+			: $default;
335
+	}
336
+
337
+
338
+	/**
339
+	 * remove param
340
+	 *
341
+	 * @param      $key
342
+	 * @param bool $unset_from_global_too
343
+	 */
344
+	public function unSetRequestParam($key, $unset_from_global_too = false)
345
+	{
346
+		// because unset may not actually remove var
347
+		$this->get[ $key ]     = null;
348
+		$this->post[ $key ]    = null;
349
+		$this->request[ $key ] = null;
350
+		unset($this->get[ $key ], $this->post[ $key ], $this->request[ $key ]);
351
+		if ($unset_from_global_too) {
352
+			unset($_GET[ $key ], $_POST[ $key ], $_REQUEST[ $key ]);
353
+		}
354
+	}
355
+
356
+
357
+	/**
358
+	 * remove params
359
+	 *
360
+	 * @param array $keys
361
+	 * @param bool  $unset_from_global_too
362
+	 */
363
+	public function unSetRequestParams(array $keys, $unset_from_global_too = false)
364
+	{
365
+		foreach ($keys as $key) {
366
+			$this->unSetRequestParam($key, $unset_from_global_too);
367
+		}
368
+	}
369 369
 }
Please login to merge, or discard this patch.