summaryrefslogtreecommitdiffstats
path: root/R/normalize.R
blob: e54c0ef953b92fe7296af50e7d92351779151bad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#' Return the 8 digits of a CEP, accepting the mask
#'
#' @description
#' `"01001-000"`, `"01001000"`, `"01001.000"` and `" 01001-000 "` all become
#' `"01001000"`.
#'
#' This runs **before** any request: a 7-digit CEP is the caller's bug, and
#' spending a round trip for the server to say so wastes both sides' time.
#'
#' @param value A length-one character vector. Numbers are rejected on
#'   purpose: `1001000` has already lost the leading zero that makes
#'   `"01001000"` a CEP. Convert with `sprintf("%08d", x)` first.
#'
#' @return The 8 digits, as a length-one character vector.
#'
#' @section Conditions:
#' Signals [cepis_invalid_cep][cepis_conditions] unless exactly 8 digits
#' remain.
#'
#' @examples
#' normalize_cep("01001-000")
#'
#' @export
normalize_cep <- function(value) {
  if (!is.character(value) || length(value) != 1L || is.na(value)) {
    stop(invalid_cep_error(
      paste0(
        "CEP must be a length-one character vector, got ",
        class(value)[1L], " of length ", length(value)
      ),
      value = value
    ))
  }

  cleaned <- gsub("[-. ]", "", trimws(value))
  if (!grepl("^[0-9]{8}$", cleaned)) {
    stop(invalid_cep_error(
      paste0("CEP must be 8 digits, got \"", value, "\""),
      value = value
    ))
  }
  cleaned
}