'%s', 'tax_class' => '%s', 'country' => '%s', 'rate_bp' => '%d', 'status' => '%s', 'sort_order' => '%d', ); /** * Every tax rate, in display order. * * @since 0.1.0 * * @return array> */ public function all(): array { $table = Tables::name( 'tax_rates' ); return array_map( array( $this, 'hydrate' ), $this->rows( "SELECT * FROM {$table} ORDER BY sort_order ASC, id ASC" ) ); } /** * Finds a tax rate. * * @since 0.1.0 * * @param int $id Rate id. * @return array|null */ public function find( int $id ): ?array { $table = Tables::name( 'tax_rates' ); $row = $this->row( "SELECT * FROM {$table} WHERE id = %d", array( $id ) ); return null === $row ? null : $this->hydrate( $row ); } /** * Inserts a tax rate, placing it last. * * @since 0.1.0 * * @param array $data name, tax_class, country, rate_bp, status. * @return int New id, or 0 on failure. */ public function insert( array $data ): int { $table = Tables::name( 'tax_rates' ); $row = array_intersect_key( $data, self::COLUMNS ); $row['sort_order'] = (int) $this->value( "SELECT COALESCE( MAX( sort_order ), 0 ) + 1 FROM {$table}" ); return $this->insert_row( $table, $row, $this->formats_for( $row ) ); } /** * Updates a tax rate. * * @since 0.1.0 * * @param int $id Rate id. * @param array $data Changed columns. * @return bool */ public function update( int $id, array $data ): bool { $row = array_intersect_key( $data, self::COLUMNS ); if ( array() === $row ) { return true; } return false !== $this->wpdb->update( Tables::name( 'tax_rates' ), $row, array( 'id' => $id ), $this->formats_for( $row ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching } /** * Deletes a tax rate. Invoices keep their own copy of the rate. * * @since 0.1.0 * * @param int $id Rate id. * @return bool */ public function delete( int $id ): bool { return false !== $this->wpdb->delete( Tables::name( 'tax_rates' ), array( 'id' => $id ), array( '%d' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching } /** * Placeholder formats in the order of a row's keys. * * @param array $row Column values. * @return string[] */ private function formats_for( array $row ): array { return array_map( static function ( string $column ) { return self::COLUMNS[ $column ]; }, array_keys( $row ) ); } /** * Casts a row. * * @param array $row Database row. * @return array */ private function hydrate( array $row ): array { $row['id'] = (int) $row['id']; $row['rate_bp'] = (int) $row['rate_bp']; $row['sort_order'] = (int) $row['sort_order']; return $row; } }