Nav apraksta

class-wc-shipping-flat-rate.php 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. <?php
  2. /**
  3. * Flat Rate Shipping Method.
  4. *
  5. * @version 2.6.0
  6. * @package WooCommerce\Classes\Shipping
  7. */
  8. defined( 'ABSPATH' ) || exit;
  9. /**
  10. * WC_Shipping_Flat_Rate class.
  11. */
  12. class WC_Shipping_Flat_Rate extends WC_Shipping_Method {
  13. /**
  14. * Cost passed to [fee] shortcode.
  15. *
  16. * @var string Cost.
  17. */
  18. protected $fee_cost = '';
  19. /**
  20. * Constructor.
  21. *
  22. * @param int $instance_id Shipping method instance ID.
  23. */
  24. public function __construct( $instance_id = 0 ) {
  25. $this->id = 'flat_rate';
  26. $this->instance_id = absint( $instance_id );
  27. $this->method_title = __( 'Flat rate', 'woocommerce' );
  28. $this->method_description = __( 'Lets you charge a fixed rate for shipping.', 'woocommerce' );
  29. $this->supports = array(
  30. 'shipping-zones',
  31. 'instance-settings',
  32. 'instance-settings-modal',
  33. );
  34. $this->init();
  35. add_action( 'woocommerce_update_options_shipping_' . $this->id, array( $this, 'process_admin_options' ) );
  36. }
  37. /**
  38. * Init user set variables.
  39. */
  40. public function init() {
  41. $this->instance_form_fields = include __DIR__ . '/includes/settings-flat-rate.php';
  42. $this->title = $this->get_option( 'title' );
  43. $this->tax_status = $this->get_option( 'tax_status' );
  44. $this->cost = $this->get_option( 'cost' );
  45. $this->type = $this->get_option( 'type', 'class' );
  46. }
  47. /**
  48. * Evaluate a cost from a sum/string.
  49. *
  50. * @param string $sum Sum of shipping.
  51. * @param array $args Args, must contain `cost` and `qty` keys. Having `array()` as default is for back compat reasons.
  52. * @return string
  53. */
  54. protected function evaluate_cost( $sum, $args = array() ) {
  55. // Add warning for subclasses.
  56. if ( ! is_array( $args ) || ! array_key_exists( 'qty', $args ) || ! array_key_exists( 'cost', $args ) ) {
  57. wc_doing_it_wrong( __FUNCTION__, '$args must contain `cost` and `qty` keys.', '4.0.1' );
  58. }
  59. include_once WC()->plugin_path() . '/includes/libraries/class-wc-eval-math.php';
  60. // Allow 3rd parties to process shipping cost arguments.
  61. $args = apply_filters( 'woocommerce_evaluate_shipping_cost_args', $args, $sum, $this );
  62. $locale = localeconv();
  63. $decimals = array( wc_get_price_decimal_separator(), $locale['decimal_point'], $locale['mon_decimal_point'], ',' );
  64. $this->fee_cost = $args['cost'];
  65. // Expand shortcodes.
  66. add_shortcode( 'fee', array( $this, 'fee' ) );
  67. $sum = do_shortcode(
  68. str_replace(
  69. array(
  70. '[qty]',
  71. '[cost]',
  72. ),
  73. array(
  74. $args['qty'],
  75. $args['cost'],
  76. ),
  77. $sum
  78. )
  79. );
  80. remove_shortcode( 'fee', array( $this, 'fee' ) );
  81. // Remove whitespace from string.
  82. $sum = preg_replace( '/\s+/', '', $sum );
  83. // Remove locale from string.
  84. $sum = str_replace( $decimals, '.', $sum );
  85. // Trim invalid start/end characters.
  86. $sum = rtrim( ltrim( $sum, "\t\n\r\0\x0B+*/" ), "\t\n\r\0\x0B+-*/" );
  87. // Do the math.
  88. return $sum ? WC_Eval_Math::evaluate( $sum ) : 0;
  89. }
  90. /**
  91. * Work out fee (shortcode).
  92. *
  93. * @param array $atts Attributes.
  94. * @return string
  95. */
  96. public function fee( $atts ) {
  97. $atts = shortcode_atts(
  98. array(
  99. 'percent' => '',
  100. 'min_fee' => '',
  101. 'max_fee' => '',
  102. ),
  103. $atts,
  104. 'fee'
  105. );
  106. $calculated_fee = 0;
  107. if ( $atts['percent'] ) {
  108. $calculated_fee = $this->fee_cost * ( floatval( $atts['percent'] ) / 100 );
  109. }
  110. if ( $atts['min_fee'] && $calculated_fee < $atts['min_fee'] ) {
  111. $calculated_fee = $atts['min_fee'];
  112. }
  113. if ( $atts['max_fee'] && $calculated_fee > $atts['max_fee'] ) {
  114. $calculated_fee = $atts['max_fee'];
  115. }
  116. return $calculated_fee;
  117. }
  118. /**
  119. * Calculate the shipping costs.
  120. *
  121. * @param array $package Package of items from cart.
  122. */
  123. public function calculate_shipping( $package = array() ) {
  124. $rate = array(
  125. 'id' => $this->get_rate_id(),
  126. 'label' => $this->title,
  127. 'cost' => 0,
  128. 'package' => $package,
  129. );
  130. // Calculate the costs.
  131. $has_costs = false; // True when a cost is set. False if all costs are blank strings.
  132. $cost = $this->get_option( 'cost' );
  133. if ( '' !== $cost ) {
  134. $has_costs = true;
  135. $rate['cost'] = $this->evaluate_cost(
  136. $cost,
  137. array(
  138. 'qty' => $this->get_package_item_qty( $package ),
  139. 'cost' => $package['contents_cost'],
  140. )
  141. );
  142. }
  143. // Add shipping class costs.
  144. $shipping_classes = WC()->shipping()->get_shipping_classes();
  145. if ( ! empty( $shipping_classes ) ) {
  146. $found_shipping_classes = $this->find_shipping_classes( $package );
  147. $highest_class_cost = 0;
  148. foreach ( $found_shipping_classes as $shipping_class => $products ) {
  149. // Also handles BW compatibility when slugs were used instead of ids.
  150. $shipping_class_term = get_term_by( 'slug', $shipping_class, 'product_shipping_class' );
  151. $class_cost_string = $shipping_class_term && $shipping_class_term->term_id ? $this->get_option( 'class_cost_' . $shipping_class_term->term_id, $this->get_option( 'class_cost_' . $shipping_class, '' ) ) : $this->get_option( 'no_class_cost', '' );
  152. if ( '' === $class_cost_string ) {
  153. continue;
  154. }
  155. $has_costs = true;
  156. $class_cost = $this->evaluate_cost(
  157. $class_cost_string,
  158. array(
  159. 'qty' => array_sum( wp_list_pluck( $products, 'quantity' ) ),
  160. 'cost' => array_sum( wp_list_pluck( $products, 'line_total' ) ),
  161. )
  162. );
  163. if ( 'class' === $this->type ) {
  164. $rate['cost'] += $class_cost;
  165. } else {
  166. $highest_class_cost = $class_cost > $highest_class_cost ? $class_cost : $highest_class_cost;
  167. }
  168. }
  169. if ( 'order' === $this->type && $highest_class_cost ) {
  170. $rate['cost'] += $highest_class_cost;
  171. }
  172. }
  173. if ( $has_costs ) {
  174. $this->add_rate( $rate );
  175. }
  176. /**
  177. * Developers can add additional flat rates based on this one via this action since @version 2.4.
  178. *
  179. * Previously there were (overly complex) options to add additional rates however this was not user.
  180. * friendly and goes against what Flat Rate Shipping was originally intended for.
  181. */
  182. do_action( 'woocommerce_' . $this->id . '_shipping_add_rate', $this, $rate );
  183. }
  184. /**
  185. * Get items in package.
  186. *
  187. * @param array $package Package of items from cart.
  188. * @return int
  189. */
  190. public function get_package_item_qty( $package ) {
  191. $total_quantity = 0;
  192. foreach ( $package['contents'] as $item_id => $values ) {
  193. if ( $values['quantity'] > 0 && $values['data']->needs_shipping() ) {
  194. $total_quantity += $values['quantity'];
  195. }
  196. }
  197. return $total_quantity;
  198. }
  199. /**
  200. * Finds and returns shipping classes and the products with said class.
  201. *
  202. * @param mixed $package Package of items from cart.
  203. * @return array
  204. */
  205. public function find_shipping_classes( $package ) {
  206. $found_shipping_classes = array();
  207. foreach ( $package['contents'] as $item_id => $values ) {
  208. if ( $values['data']->needs_shipping() ) {
  209. $found_class = $values['data']->get_shipping_class();
  210. if ( ! isset( $found_shipping_classes[ $found_class ] ) ) {
  211. $found_shipping_classes[ $found_class ] = array();
  212. }
  213. $found_shipping_classes[ $found_class ][ $item_id ] = $values;
  214. }
  215. }
  216. return $found_shipping_classes;
  217. }
  218. /**
  219. * Sanitize the cost field.
  220. *
  221. * @since 3.4.0
  222. * @param string $value Unsanitized value.
  223. * @throws Exception Last error triggered.
  224. * @return string
  225. */
  226. public function sanitize_cost( $value ) {
  227. $value = is_null( $value ) ? '' : $value;
  228. $value = wp_kses_post( trim( wp_unslash( $value ) ) );
  229. $value = str_replace( array( get_woocommerce_currency_symbol(), html_entity_decode( get_woocommerce_currency_symbol() ) ), '', $value );
  230. // Thrown an error on the front end if the evaluate_cost will fail.
  231. $dummy_cost = $this->evaluate_cost(
  232. $value,
  233. array(
  234. 'cost' => 1,
  235. 'qty' => 1,
  236. )
  237. );
  238. if ( false === $dummy_cost ) {
  239. throw new Exception( WC_Eval_Math::$last_error );
  240. }
  241. return $value;
  242. }
  243. }