db->prepare( 'SELECT * FROM %i WHERE `id` = %d LIMIT 1', $this->table( 'orders' ), $id ); $row = $this->db->get_row( $sql, ARRAY_A ); return is_array( $row ) ? $this->hydrate( $row ) : null; } /** * Find by uuid. * * {@inheritDoc} * * @param Uuid $uuid Parameter. * @since 0.1.0 */ public function find_by_uuid( Uuid $uuid ): ?Order { $sql = $this->db->prepare( 'SELECT * FROM %i WHERE `uuid` = %s LIMIT 1', $this->table( 'orders' ), $uuid->to_string() ); $row = $this->db->get_row( $sql, ARRAY_A ); return is_array( $row ) ? $this->hydrate( $row ) : null; } /** * Save. * * {@inheritDoc} * * @param Order $order Parameter. * @since 0.1.0 */ public function save( Order $order ): void { $currency = $order->currency(); $data = [ 'uuid' => $order->uuid()->to_string(), 'customer_id' => $order->customer_id(), 'status' => $order->status()->value, 'subtotal_minor' => $order->subtotal()->amount_minor(), 'discount_minor' => $order->discount()->amount_minor(), 'tax_minor' => $order->tax()->amount_minor(), 'total_minor' => $order->total()->amount_minor(), 'paid_minor' => $order->paid()->amount_minor(), 'currency' => $currency, 'coupon_id' => $order->coupon_id(), 'source' => null === $order->source() ? null : $order->source()->value, 'ip_hash' => $order->ip_hash(), 'user_agent_hash' => $order->user_agent_hash(), 'meta' => $this->encode_meta( $order->meta() ), 'created_at' => $this->format_datetime( $order->created_at() ), 'updated_at' => $this->format_datetime( $order->updated_at() ), ]; if ( null === $order->id() ) { $this->db->insert( $this->table( 'orders' ), $data ); $order->assign_id( $this->last_insert_id() ); return; } $this->db->update( $this->table( 'orders' ), $data, [ 'id' => $order->id() ] ); } /** * Map a database row to an entity. * * @param array $row Database row. */ private function hydrate( array $row ): Order { $currency = (string) $row['currency']; return new Order( (int) $row['id'], new Uuid( (string) $row['uuid'] ), (int) $row['customer_id'], OrderStatus::from( (string) $row['status'] ), new Money( (int) $row['subtotal_minor'], $currency ), new Money( (int) $row['discount_minor'], $currency ), new Money( (int) $row['tax_minor'], $currency ), new Money( (int) $row['total_minor'], $currency ), new Money( (int) $row['paid_minor'], $currency ), null !== $row['coupon_id'] ? (int) $row['coupon_id'] : null, null !== $row['source'] && '' !== $row['source'] ? OrderSource::from( (string) $row['source'] ) : null, null !== $row['ip_hash'] ? (string) $row['ip_hash'] : null, null !== $row['user_agent_hash'] ? (string) $row['user_agent_hash'] : null, $this->decode_meta( isset( $row['meta'] ) ? (string) $row['meta'] : null ), $this->parse_datetime( (string) $row['created_at'] ), $this->parse_datetime( (string) $row['updated_at'] ), ); } }