coupons = $coupons ?? static function ( int $id ): ?\WC_Coupon { $coupon = new \WC_Coupon( $id ); return $coupon->get_id() > 0 ? $coupon : null; }; } /** * The facts this provider declares. * * @return array> */ public static function declarations(): array { return array( 'coupon.discount_type' => array( 'type' => 'string', 'label' => 'Coupon discount type', ), 'coupon.amount' => array( 'type' => 'number', 'label' => 'Coupon amount (percent, or minor units)', ), 'coupon.usage_limit' => array( 'type' => 'number', 'label' => 'Coupon usage limit', ), 'coupon.unlimited' => array( 'type' => 'bool', 'label' => 'Coupon has no usage limit', ), 'coupon.free_shipping' => array( 'type' => 'bool', 'label' => 'Coupon grants free shipping', ), ); } /** * Facts about a coupon write. * * @param ActionDescriptor $action The classified action. * @return array */ public function __invoke( ActionDescriptor $action ): array { if ( 'read' === $action->action_cat || 'delete' === $action->action_cat ) { return array(); } $coupon = null === $action->entity_id ? null : ( $this->coupons )( $action->entity_id ); $input = $action->input; $type = is_string( $input['discount_type'] ?? null ) ? $input['discount_type'] : ( null === $coupon ? 'fixed_cart' : (string) $coupon->get_discount_type() ); $facts = array( 'coupon.discount_type' => substr( $type, 0, 1024 ) ); $amount = $input['amount'] ?? ( null === $coupon ? null : $coupon->get_amount() ); $amount = 'percent' === $type ? self::number( $amount ) : Money::to_minor( $amount, $this->currency->decimals() ); if ( null !== $amount ) { $facts['coupon.amount'] = $amount; } $limit = array_key_exists( 'usage_limit', $input ) ? $input['usage_limit'] : ( null === $coupon ? null : $coupon->get_usage_limit() ); $limit = is_numeric( $limit ) ? (int) $limit : 0; if ( $limit > 0 ) { $facts['coupon.usage_limit'] = $limit; } $facts['coupon.unlimited'] = $limit <= 0; $facts['coupon.free_shipping'] = array_key_exists( 'free_shipping', $input ) ? WcRouteClassifier::truthy( $input['free_shipping'] ) : ( null !== $coupon && (bool) $coupon->get_free_shipping() ); return $facts; } /** * A percentage as a number, or null. * * @param mixed $value Amount. */ private static function number( mixed $value ): int|float|null { if ( ! is_numeric( $value ) || ! is_finite( (float) $value ) ) { return null; } return (string) (int) $value === (string) $value ? (int) $value : (float) $value; } }