get_cogs_total_value() ); return ( null === $cents || $cents <= 0 ) ? null : $cents; } /** * Describe one product and its variants. * * @param int $product_id Product id. * @return array|null Null when the product does not exist, is in the trash or is not simple/variable. */ public function describe( int $product_id ): ?array { $product = wc_get_product( $product_id ); if ( ! $product || 'trash' === $product->get_status() || ! in_array( $product->get_type(), self::SUPPORTED_TYPES, true ) ) { return null; } $variants = array(); if ( $product->is_type( 'variable' ) ) { foreach ( $product->get_children() as $child_id ) { $variation = wc_get_product( $child_id ); if ( ! $variation instanceof \WC_Product_Variation ) { continue; } $label = wc_get_formatted_variation( $variation, true, false ); $variants[] = array( 'id' => (string) $variation->get_id(), 'title' => '' !== $label ? $label : '#' . $variation->get_id(), 'priceCents' => self::to_cents( $variation->get_price() ), 'costCents' => self::store_cost_cents( $variation ), ); } } else { $variants[] = array( 'id' => (string) $product->get_id(), 'title' => '', 'priceCents' => self::to_cents( $product->get_price() ), 'costCents' => self::store_cost_cents( $product ), ); } return array( 'id' => (string) $product->get_id(), 'title' => $product->get_name(), 'type' => $product->get_type(), 'status' => $product->get_status(), 'variants' => $variants, ); } /** * Find simple and variable products by title or SKU, for the "add a recipe" picker. * * @param string $term Search text. * @param int $limit Maximum number of results. * @return array[] Each: id, title, type, price (cents or null), hasRecipe. */ public function search( string $term, int $limit = 20 ): array { $args = array( 'type' => self::SUPPORTED_TYPES, 'status' => array( 'publish', 'draft', 'pending', 'private' ), 'limit' => max( 1, min( 50, $limit ) ), 'orderby' => 'title', 'order' => 'ASC', 'return' => 'objects', ); if ( '' !== $term ) { $args['s'] = $term; } $found = array(); foreach ( wc_get_products( $args ) as $product ) { $found[] = array( 'id' => (string) $product->get_id(), 'title' => $product->get_name(), 'type' => $product->get_type(), 'priceCents' => self::to_cents( $product->get_price() ), 'hasRecipe' => '' !== (string) get_post_meta( $product->get_id(), Recipes::META_KEY, true ), ); } return $found; } }