products = $products ?? static function ( int $id ): ?\WC_Product { $product = wc_get_product( $id ); return $product instanceof \WC_Product ? $product : null; }; } /** * The facts this provider declares. * * @param StoreCurrency $currency The store's money. * @return array> */ public static function declarations( StoreCurrency $currency ): array { return array( 'product.price_change_pct' => array( 'type' => 'number', 'label' => 'Price change, percent', ), 'product.new_price_minor' => Orders::money( $currency, 'New price' ), 'product.stock_delta' => array( 'type' => 'number', 'label' => 'Stock change', ), 'product.status_to' => array( 'type' => 'string', 'label' => 'Product status requested', ), ); } /** * Facts about a product write. * * @param ActionDescriptor $action The classified action. * @return array */ public function __invoke( ActionDescriptor $action ): array { if ( 'read' === $action->action_cat ) { return array(); } $decimals = $this->currency->decimals(); $product = null === $action->entity_id ? null : ( $this->products )( $action->entity_id ); $facts = array(); $price = self::requested_price( $action->input, $decimals ); if ( null !== $price ) { $facts['product.new_price_minor'] = $price; $stored = null === $product ? null : Money::to_minor( (string) $product->get_price(), $decimals ); if ( null !== $stored && $stored > 0 ) { $facts['product.price_change_pct'] = round( ( $price - $stored ) * 100 / $stored, 2 ); } } $stock = $action->input['stock_quantity'] ?? null; if ( is_int( $stock ) || ( is_string( $stock ) && 1 === preg_match( '/^-?\d{1,15}$/', $stock ) ) ) { $facts['product.stock_delta'] = (int) $stock - ( null === $product ? 0 : (int) $product->get_stock_quantity() ); } if ( isset( $action->input['status'] ) && is_string( $action->input['status'] ) ) { $facts['product.status_to'] = substr( $action->input['status'], 0, 1024 ); } return $facts; } /** * The price the write would charge, in minor units: a non-empty sale * price, else the regular price; null when it names neither. * * @param array $input Request body. * @param int $decimals Minor-unit exponent. */ private static function requested_price( array $input, int $decimals ): ?int { foreach ( array( 'sale_price', 'regular_price' ) as $field ) { if ( isset( $input[ $field ] ) && '' !== $input[ $field ] ) { return Money::to_minor( $input[ $field ], $decimals ); } } return null; } }