# `Localize.AcceptLanguage`
[🔗](https://github.com/elixir-localize/localize_web/blob/main/lib/localize/accept_language.ex#L1)

Parses HTTP `Accept-Language` headers and finds the best matching locale.

The `Accept-Language` header is parsed per [RFC 2616](https://www.rfc-editor.org/rfc/rfc2616#section-14.4) into quality-tagged language tags which are then matched against the supported locales. The primary entry point is `best_match/1` which returns the highest-quality tag that matches a supported locale.

# `best_match`

```elixir
@spec best_match(term()) :: {:ok, Localize.LanguageTag.t()} | {:error, Exception.t()}
```

Returns the best matching locale for the given `Accept-Language` header.

Parses the header and returns the highest-quality language tag that
matches a supported locale. A tag that only resolves to a supported
locale by fallback, such as `ja` when no Japanese locale is supported,
is skipped in favour of the next tag in the header.

### Arguments

* `header` is an Accept-Language header string.

### Returns

* `{:ok, Localize.LanguageTag.t()}` or

* `{:error, exception}`: a `Localize.UnknownLocaleError` when no tag matches a supported locale, or a `Localize.InvalidValueError` when `header` is not a string.

### Examples

    iex> {:ok, locale} = Localize.AcceptLanguage.best_match("en-US,fr;q=0.8")
    iex> locale.language
    "en"

# `parse`

```elixir
@spec parse(term()) ::
  {:ok, [{float(), {:ok, Localize.LanguageTag.t()} | {:error, term()}}]}
  | {:error, Exception.t()}
```

Parses an `Accept-Language` header and validates each language tag
against known locales.

### Arguments

* `header` is an Accept-Language header string.

### Returns

* `{:ok, [{quality, result}]}` where `result` is either
  `{:ok, Localize.LanguageTag.t()}` or `{:error, reason}`, or

* `{:error, exception}` when `header` is not a string.

### Examples

    iex> {:ok, results} = Localize.AcceptLanguage.parse("en-US,zh;q=0.8")
    iex> length(results)
    2

# `tokenize`

```elixir
@spec tokenize(term()) :: [{float(), String.t()}]
```

Tokenizes an `Accept-Language` header string into a list of
`{quality, language_tag_string}` tuples sorted by quality descending.

### Arguments

* `header` is an Accept-Language header string.

### Returns

* A list of `{quality, language_tag_string}` tuples. A `header` that is not a string has no tags.

### Examples

    iex> Localize.AcceptLanguage.tokenize("en-US,en;q=0.9,fr;q=0.8")
    [{1.0, "en-us"}, {0.9, "en"}, {0.8, "fr"}]

---

*Consult [api-reference.md](api-reference.md) for complete listing*
