PluginProbe
Pay with Vipps and MobilePay for WooCommerce / 6.1.0
Pay with Vipps and MobilePay for WooCommerce v6.1.0
6.2.1 6.2.0 6.1.10 6.1.9 6.1.8 6.1.7 6.1.6 6.1.5 6.1.4 6.1.3 6.1.2 6.1.1 6.1.0 6.0.5 6.0.4 6.0.3 6.0.2 6.0.1 6.0.0 5.4.3 5.4.2 5.4.1 5.4.0 5.3.4 trunk All 183 releases
woo-vipps / recurring / includes / models / WC_Vipps_Model.php

WC_Vipps_Model.php in Pay with Vipps and MobilePay for WooCommerce 6.1.0, at recurring/includes/models/WC_Vipps_Model.php

82 lines 1.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 defined( 'ABSPATH' ) || exit;
4
5 abstract class WC_Vipps_Model {
6 protected array $required_fields = [];
7
8 public function __construct( array $data = [] ) {
9 $this->from_array( $data );
10 }
11
12 private function from_array( array $data ): void {
13 foreach ( $data as $key => $value ) {
14 $snake_case_key = $this->camel_to_snake( $key );
15 $func_name = "set_$snake_case_key";
16
17 if ( ! method_exists( get_class( $this ), $func_name ) || $value === null ) {
18 continue;
19 }
20
21 $this->{$func_name}( $value );
22 }
23 }
24
25 private function camel_to_snake( $input ): string {
26 return strtolower( preg_replace( '/(?<!^)[A-Z]/', '_$0', $input ) );
27 }
28
29 abstract function to_array( bool $check_required = false ): array;
30
31 protected function _set_value( $name, $value, $class = null ): self {
32 if ( is_array( $value ) && $class ) {
33 $this->{$name} = new $class( $value );
34 } else {
35 $this->{$name} = $value;
36 }
37
38 return $this;
39 }
40
41 /**
42 * @throws WC_Vipps_Recurring_Missing_Value_Exception
43 */
44 protected function check_required( ?string $keyed_by = null ): void {
45 $class = get_class( $this );
46
47 $fields = ! $keyed_by ? $this->required_fields : $this->required_fields[ $keyed_by ];
48
49 foreach ( $fields as $value ) {
50 if ( $this->{$value} === null ) {
51 throw new WC_Vipps_Recurring_Missing_Value_Exception( "Incorrect usage. Required value $value is missing in $class." );
52 }
53 }
54 }
55
56 protected function serialize_value( $value, string $date_format = 'Y-m-d\TH:i:s\Z' ) {
57 if ( $value instanceof DateTime ) {
58 $value = $value->format( $date_format );
59 }
60
61 if ( is_subclass_of( $value, __CLASS__ ) ) {
62 $value = $value->to_array( false );
63 }
64
65 return $value;
66 }
67
68 protected function conditional( string $name, $value, $remove_if_empty = false ): array {
69 if ( ! $value ) {
70 return [];
71 }
72
73 $value = $this->serialize_value( $value );
74
75 if ( $remove_if_empty && empty( $value ) ) {
76 return [];
77 }
78
79 return [ $name => $value ];
80 }
81 }
82