|
| 1 | +<?php |
| 2 | +/** |
| 3 | + * Factory class for the WooCommerce's coupon data objects. |
| 4 | + * |
| 5 | + * @since v0.6.1 |
| 6 | + * @package Tests\WPGraphQL\WooCommerce\Factory |
| 7 | + */ |
| 8 | + |
| 9 | +namespace Tests\WPGraphQL\WooCommerce\Factory; |
| 10 | + |
| 11 | +use Tests\WPGraphQL\WooCommerce\Utils\Dummy; |
| 12 | + |
| 13 | +/** |
| 14 | + * Coupon factory class for testing. |
| 15 | + */ |
| 16 | +class CouponFactory extends \WP_UnitTest_Factory_For_Thing { |
| 17 | + function __construct( $factory = null ) { |
| 18 | + parent::__construct( $factory ); |
| 19 | + |
| 20 | + $this->default_generation_definitions = array( |
| 21 | + 'coupon_class' => '\WC_Coupon', |
| 22 | + ); |
| 23 | + } |
| 24 | + |
| 25 | + public function create_object( $args ) { |
| 26 | + if ( is_wp_error( $args ) ) codecept_debug( $args ); |
| 27 | + $coupon_class = $args['coupon_class' ]; |
| 28 | + unset( $args['coupon_class'] ); |
| 29 | + |
| 30 | + $coupon = new $coupon_class(); |
| 31 | + |
| 32 | + $amount = Dummy::instance()->number( 0, 75 ); |
| 33 | + $coupon->set_props( |
| 34 | + array_merge( |
| 35 | + array( |
| 36 | + 'code' => $amount . 'off', |
| 37 | + 'amount' => floatval( $amount ), |
| 38 | + 'date_expires' => null, |
| 39 | + 'discount_type' => 'percent', |
| 40 | + 'description' => 'Test coupon', |
| 41 | + ), |
| 42 | + $args |
| 43 | + ) |
| 44 | + ); |
| 45 | + |
| 46 | + // Set meta data. |
| 47 | + if ( ! empty( $args['meta_data'] ) ) { |
| 48 | + $coupon->set_meta_data( $args['meta_data'] ); |
| 49 | + } |
| 50 | + |
| 51 | + return $coupon->save(); |
| 52 | + } |
| 53 | + |
| 54 | + public function update_object( $object, $fields ) { |
| 55 | + if ( ! $object instanceof \WC_Coupon && 0 !== absint( $object ) ) { |
| 56 | + $object = $this->get_object_by_id( $object ); |
| 57 | + } |
| 58 | + |
| 59 | + foreach( $fields as $field => $field_value ) { |
| 60 | + if ( ! is_callable( array( $object, "set_{$field}" ) ) ) { |
| 61 | + throw new \Exception( |
| 62 | + sprintf( '"%1$s" is not a valid %2$s coupon field.', $field, $object->get_type() ) |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | + $object->{"set_{$field}"}( $field_value ); |
| 67 | + } |
| 68 | + |
| 69 | + $object->save(); |
| 70 | + } |
| 71 | + |
| 72 | + public function get_object_by_id( $id ) { |
| 73 | + return new \WC_Coupon( $id ); |
| 74 | + } |
| 75 | +} |
0 commit comments