'edit_shop_orders', 'product' => 'edit_products', 'product_variation' => 'edit_products', 'coupon' => 'edit_shop_coupons', ); /** * The class every new object of a type must be, or extend. */ private const BASES = array( 'order' => \WC_Order::class, 'product' => \WC_Product::class, 'product_variation' => \WC_Product_Variation::class, 'coupon' => \WC_Coupon::class, ); /** * Run the save. * * @param ActionDescriptor $action The held action. * @param array $envelope CrudBackstop's envelope. * @return array|WP_Error */ public function replay( ActionDescriptor $action, array $envelope ): array|WP_Error { $type = is_string( $envelope['type'] ?? null ) ? $envelope['type'] : ''; $capability = self::CAPABILITIES[ $type ] ?? null; if ( null === $capability || ! current_user_can( $capability ) ) { return new WP_Error( 'adafwc_object_forbidden', __( 'The agent\'s WordPress user may no longer make this change.', 'agentic-daisy-ai-agent-firewall-for-woocommerce' ) ); } $object = self::load( $type, absint( $envelope['id'] ?? 0 ), is_string( $envelope['class'] ?? null ) ? $envelope['class'] : '' ); if ( null === $object ) { return new WP_Error( 'adafwc_object_missing', __( 'The object this change was for no longer exists.', 'agentic-daisy-ai-agent-firewall-for-woocommerce' ) ); } $set = $object->set_props( is_array( $envelope['changes'] ?? null ) ? $envelope['changes'] : array() ); if ( is_wp_error( $set ) ) { return $set; } foreach ( is_array( $envelope['meta'] ?? null ) ? $envelope['meta'] : array() as $key => $value ) { if ( null === $value ) { $object->delete_meta_data( (string) $key ); } else { $object->update_meta_data( (string) $key, $value ); } } try { return array( 'id' => $object->save() ); } catch ( \WC_Data_Exception $refused ) { return new WP_Error( $refused->getErrorCode(), $refused->getMessage() ); } } /** * The object to change: the stored one, or a new one of the class the * agent was creating - one of WooCommerce's own classes for the type. * * @param string $type Entity type. * @param int $id Object id, 0 for a new one. * @param string $class Class of the object held. */ private static function load( string $type, int $id, string $class ): \WC_Order|\WC_Product|\WC_Coupon|null { if ( 0 === $id ) { // Only a class of the stored type's own family is constructed. $base = self::BASES[ $type ] ?? null; $object = CrudBackstop::guarded( null !== $base && class_exists( $class ) && ( $class === $base || is_subclass_of( $class, $base ) ) ? new $class() : null ); return null !== $object && CrudBackstop::type_of( $object ) === $type ? $object : null; } $object = match ( $type ) { 'order' => wc_get_order( $id ), 'product', 'product_variation' => wc_get_product( $id ), 'coupon' => new \WC_Coupon( $id ), default => null, }; $object = CrudBackstop::guarded( $object ); return null !== $object && CrudBackstop::type_of( $object ) === $type && $object->get_id() > 0 ? $object : null; } }