PaymentContext.php
| 1 | <?php |
| 2 | namespace Automattic\WooCommerce\StoreApi\Payments; |
| 3 | |
| 4 | /** |
| 5 | * PaymentContext class. |
| 6 | */ |
| 7 | class PaymentContext { |
| 8 | /** |
| 9 | * Payment method ID. |
| 10 | * |
| 11 | * @var string |
| 12 | */ |
| 13 | protected $payment_method = ''; |
| 14 | |
| 15 | /** |
| 16 | * Order object for the order being paid. |
| 17 | * |
| 18 | * @var \WC_Order |
| 19 | */ |
| 20 | protected $order; |
| 21 | |
| 22 | /** |
| 23 | * Holds data to send to the payment gateway to support payment. |
| 24 | * |
| 25 | * @var array Key value pairs. |
| 26 | */ |
| 27 | protected $payment_data = []; |
| 28 | |
| 29 | /** |
| 30 | * Magic getter for protected properties. |
| 31 | * |
| 32 | * @param string $name Property name. |
| 33 | */ |
| 34 | public function __get( $name ) { |
| 35 | if ( in_array( $name, [ 'payment_method', 'order', 'payment_data' ], true ) ) { |
| 36 | return $this->$name; |
| 37 | } |
| 38 | return null; |
| 39 | } |
| 40 | |
| 41 | /** |
| 42 | * Set the chosen payment method ID context. |
| 43 | * |
| 44 | * @param string $payment_method Payment method ID. |
| 45 | */ |
| 46 | public function set_payment_method( $payment_method ) { |
| 47 | $this->payment_method = (string) $payment_method; |
| 48 | } |
| 49 | |
| 50 | /** |
| 51 | * Retrieve the payment method instance for the current set payment method. |
| 52 | * |
| 53 | * @return \WC_Payment_Gateway|null An instance of the payment gateway if it exists. |
| 54 | */ |
| 55 | public function get_payment_method_instance() { |
| 56 | $available_gateways = WC()->payment_gateways->get_available_payment_gateways(); |
| 57 | if ( ! isset( $available_gateways[ $this->payment_method ] ) ) { |
| 58 | return; |
| 59 | } |
| 60 | return $available_gateways[ $this->payment_method ]; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Set the order context. |
| 65 | * |
| 66 | * @param \WC_Order $order Order object. |
| 67 | */ |
| 68 | public function set_order( \WC_Order $order ) { |
| 69 | $this->order = $order; |
| 70 | } |
| 71 | |
| 72 | /** |
| 73 | * Set payment data context. |
| 74 | * |
| 75 | * @param array $payment_data Array of key value pairs of data. |
| 76 | */ |
| 77 | public function set_payment_data( $payment_data = [] ) { |
| 78 | $this->payment_data = []; |
| 79 | |
| 80 | foreach ( $payment_data as $key => $value ) { |
| 81 | $this->payment_data[ (string) $key ] = (string) $value; |
| 82 | } |
| 83 | } |
| 84 | } |
| 85 |