Skip to main content

laravel_rust_format/
lib.rs

1//! PHP and Laravel formatting for Laravel for Rust applications. The Rust functions
2//! are re-exported from [`core`], and the service provider makes them available in MiniJinja
3//! templates. English is the default for numbers and dates. Locale arguments select other outputs.
4//!
5//! # Install
6//!
7//! ```sh
8//! cargo add laravel-rust-format
9//! ```
10//!
11//! Register the provider in your application builder:
12//!
13//! ```
14//! use laravel::Application;
15//! use laravel_rust_format::FormattingServiceProvider;
16//!
17//! let _builder = Application::configure().with_providers(|providers| {
18//!     providers.add(FormattingServiceProvider);
19//! });
20//! ```
21//!
22//! This enables the filters when your application renders HTML with the framework's MiniJinja
23//! engine. For a standalone environment, call the `register_filters` function with a
24//! [`FormattingConfig`]. Disable default features to use the provider and Rust API without
25//! enabling MiniJinja, Markdown or random helpers. To register filters without Markdown,
26//! enable just the `minijinja` feature.
27//!
28//! # Configuration
29//!
30//! | Environment variable | Default | Effect |
31//! | --- | --- | --- |
32//! | `FORMATTING_CURRENCY` | `USD` | Default currency for `number_currency`. The provider validates it against the ISO 4217 current currency and funds list at boot. |
33//! | `FORMATTING_TIMEZONE` | `UTC` | Display timezone for Unix seconds, serialized timestamps ending in `Z` and `php_date`. The provider validates the zone at boot. |
34//! | `FORMATTING_MAX_OUTPUT_BYTES` | `8388608` | Maximum raw bytes per call, before MiniJinja autoescaping. |
35//! | `FORMATTING_MAX_COLLECTION_ITEMS` | `100000` | Maximum collection entries per call, including nested entries. |
36//!
37//! # Filter reference
38//!
39//! Pass optional arguments positionally in the order shown, or by name. `none` denotes an
40//! omitted argument unless otherwise specified.
41//!
42//! | Filter or function | Arguments | PHP or Laravel equivalent | Example → output |
43//! | --- | --- | --- | --- |
44//! | `number_format` | `decimals=0, dec_point=".", thousands_sep=","` | `number_format()` | `1234.5 \| number_format(2)` → `1,234.50` |
45//! | `php_round` | `precision=0`, `mode=` | `round()` with a PHP mode name or integer | `3.5 \| php_round \| php_echo` → `4` |
46//! | `php_echo` | | `echo $number` | `1.0e20 \| php_echo` → `1.0E+20` |
47//! | `ucfirst` | | `ucfirst()` | `"apple" \| ucfirst` → `Apple` |
48//! | `php_lcfirst` | | `lcfirst()` | `"Apple" \| php_lcfirst` → `apple` |
49//! | `php_ucwords` | `separators=none` | `ucwords()` | `"red-apple" \| php_ucwords("-")` → `Red-Apple` |
50//! | `php_strtolower` | | `strtolower()` | `"ÉTÉ" \| php_strtolower` → `ÉtÉ` |
51//! | `php_strtoupper` | | `strtoupper()` | `"été" \| php_strtoupper` → `éTé` |
52//! | `str_limit` | `limit=100, end="...", preserve_words=false` | `Str::limit()` | `"hello" \| str_limit(3)` → `hel...` |
53//! | `str_words` | `words=100, end="..."` | `Str::words()` | `"one two three" \| str_words(2)` → `one two...` |
54//! | `str_slug` | `separator="-", language="en"` | `Str::slug()` | `"Café Noir" \| str_slug` → `cafe-noir` |
55//! | `str_ascii` | `language="en"` | `Str::ascii()` | `"café" \| str_ascii` → `cafe` |
56//! | `str_title` | | `Str::title()` | `"red apple" \| str_title` → `Red Apple` |
57//! | `str_headline` | | `Str::headline()` | `"first_name" \| str_headline` → `First Name` |
58//! | `str_ucfirst` | | `Str::ucfirst()` | `"été" \| str_ucfirst` → `Été` |
59//! | `str_lcfirst` | | `Str::lcfirst()` | `"Été" \| str_lcfirst` → `été` |
60//! | `str_upper` | | `Str::upper()` | `"été" \| str_upper` → `ÉTÉ` |
61//! | `str_lower` | | `Str::lower()` | `"ÉTÉ" \| str_lower` → `été` |
62//! | `str_plural` | `count=2, prepend_count=false` | `Str::plural()` | `"city" \| str_plural(3, true)` → `3 cities` |
63//! | `str_singular` | | `Str::singular()` | `"cities" \| str_singular` → `city` |
64//! | `plural(word, count)` | Both required | `Str::plural()` without prepending the count | `plural("city", 3)` → `cities` |
65//! | `number_format_intl` | `precision=none, max_precision=none, locale=none` | `Number::format()` | `2.5 \| number_format_intl(0)` → `2` |
66//! | `number_file_size` | `precision=0, max_precision=none, locale=none` | `Number::fileSize()` | `1536 \| number_file_size(1)` → `1.5 KB` |
67//! | `number_percentage` | `precision=0, max_precision=none, locale=none` | `Number::percentage()` | `2.5 \| number_percentage(1)` → `2.5%` |
68//! | `number_currency` | `code=config.currency, precision=none, locale=none` | `Number::currency()` | `42 \| number_currency("EUR")` → `€42.00` |
69//! | `number_abbreviate` | `precision=0, max_precision=none, locale=none` | `Number::abbreviate()` | `1500 \| number_abbreviate(1)` → `1.5K` |
70//! | `number_for_humans` | `precision=0, max_precision=none, abbreviate=false, locale=none` | `Number::forHumans()` | `1500 \| number_for_humans(1)` → `1.5 thousand` |
71//! | `number_ordinal` | `locale=none` | `Number::ordinal()` | `21 \| number_ordinal` → `21st` |
72//! | `carbon_format` | `format` (required, PHP date letters) | `Carbon::format()` | `"2026-12-03" \| carbon_format("D, M j")` → `Thu, Dec 3` |
73//! | `carbon_iso8601` | | `Carbon::toIso8601String()` | `"2026-12-03" \| carbon_iso8601` → `2026-12-03T00:00:00+00:00` |
74//! | `carbon_iso_string` | | `Carbon::toISOString()` | `"2026-12-03" \| carbon_iso_string` → `2026-12-03T00:00:00.000000Z` |
75//! | `carbon_date_string` | | `Carbon::toDateString()` | `"2026-12-03T16:30:00+01:00" \| carbon_date_string` → `2026-12-03` |
76//! | `diff_for_humans` | `other=none, short=false, parts=1, join=false, just_now=false`. See below for keyword options. | `Carbon::diffForHumans()` | `"2026-12-02" \| diff_for_humans("2026-12-03")` → `1 day before` |
77//! | `php_nl2br` | `is_xhtml=true` | `nl2br` | `"<b>line</b>\nnext"\|php_nl2br(is_xhtml=false)` → `&lt;b&gt;line&lt;&#x2f;b&gt;&lt;br&gt;\nnext` |
78//! | `php_str_pad` | `length, pad=" ", side=1` | `str_pad` | `"x"\|php_str_pad(4, "-", side=2)` → `-x--` |
79//! | `php_wordwrap` | `width=75, line_break="\n", cut_long_words=false` | `wordwrap` | `"one two"\|php_wordwrap(4, " / ")` → `one &#x2f; two` |
80//! | `php_strip_tags` | `allowed_tags=none` | `strip_tags` | `"<b>bold</b><i>italic</i>"\|php_strip_tags(["b"])` → `&lt;b&gt;bold&lt;&#x2f;b&gt;italic` |
81//! | `str_after` | `search` | `Str::after` | `"id:42"\|str_after(":")` → `42` |
82//! | `str_after_last` | `search` | `Str::afterLast` | `"a:b:c"\|str_after_last(":")` → `c` |
83//! | `str_before` | `search` | `Str::before` | `"id:42"\|str_before(":")` → `id` |
84//! | `str_before_last` | `search` | `Str::beforeLast` | `"a:b:c"\|str_before_last(":")` → `a:b` |
85//! | `str_between` | `from, to` | `Str::between` | `"[a][b]"\|str_between("[", "]")` → `a][b` |
86//! | `str_between_first` | `from, to` | `Str::betweenFirst` | `"[a][b]"\|str_between_first("[", "]")` → `a` |
87//! | `str_camel` |  | `Str::camel` | `"user name"\|str_camel` → `userName` |
88//! | `str_snake` | `delimiter="_"` | `Str::snake` | `"UserName"\|str_snake(delimiter=".")` → `user.name` |
89//! | `str_studly` | `normalize=false` | `Str::studly` | `"user name"\|str_studly` → `UserName` |
90//! | `str_kebab` |  | `Str::kebab` | `"UserName"\|str_kebab` → `user-name` |
91//! | `str_mask` | `character, index, length=none` | `Str::mask` | `"abcdef"\|str_mask("*", 1, length=3)` → `a***ef` |
92//! | `str_pad_left` | `length, pad=" "` | `Str::padLeft` | `"猫"\|str_pad_left(3, "-")` → `--猫` |
93//! | `str_pad_right` | `length, pad=" "` | `Str::padRight` | `"猫"\|str_pad_right(3, "-")` → `猫--` |
94//! | `str_pad_both` | `length, pad=" "` | `Str::padBoth` | `"猫"\|str_pad_both(4, "-")` → `-猫--` |
95//! | `str_replace` | `search, replacement, case_sensitive=true` | `Str::replace` | `"Été"\|str_replace("é", "x", case_sensitive=false)` → `xtx` |
96//! | `str_squish` |  | `Str::squish` | `" one\t  two "\|str_squish` → `one two` |
97//! | `str_word_wrap` | `width=75, line_break="\n", cut_long_words=false` | `Str::wordWrap` | `"one two"\|str_word_wrap(4, " / ")` → `one &#x2f; two` |
98//! | `str_apa` |  | `Str::apa` | `"notes from the road"\|str_apa` → `Notes From the Road` |
99//! | `str_initials` | `capitalize=false` | `Str::initials` | `"ada lovelace"\|str_initials(capitalize=true)` → `AL` |
100//! | `str_match` | `pattern` | `Str::match` | `"ID-42"\|str_match("/ID-([0-9]+)/")` → `42` |
101//! | `str_is_match` | `pattern` | `Str::isMatch` | `"ID-42"\|str_is_match("/^ID-/")` → `True` |
102//! | `str_replace_matches` | `pattern, replacement, limit=-1` | `Str::replaceMatches` | `"blue blue"\|str_replace_matches("/blue/", "red", limit=1)` → `red blue` |
103//! | `str_markdown` | `html_input="allow", allow_unsafe_links=true, soft_break="\n"` | `Str::markdown` | `"**hello**"\|str_markdown` → `&lt;p&gt;&lt;strong&gt;hello&lt;&#x2f;strong&gt;&lt;&#x2f;p&gt;\n` |
104//! | `str_inline_markdown` | `html_input="allow", allow_unsafe_links=true, soft_break="\n"` | `Str::inlineMarkdown` | `"**hello**<br>"\|str_inline_markdown(html_input="strip")` → `&lt;strong&gt;hello&lt;&#x2f;strong&gt;\n` |
105//! | `number_spell` | `locale=none, after=none, until=none` | `Number::spell` | `100000\|number_spell(locale="en_IN")` → `one lakh` |
106//! | `number_spell_ordinal` | `locale=none` | `Number::spellOrdinal` | `123\|number_spell_ordinal` → `one hundred twenty-third` |
107//! | `carbon_iso_format` | `format, locale="en"` | `$date->isoFormat($format)` | `zoned\|carbon_iso_format("LLLL", locale="fr")` → `mardi 14 juillet 2026 09:00` |
108//! | `carbon_translated_format` | `format, locale="en"` | `$date->translatedFormat($format)` | `zoned\|carbon_translated_format("l j F", locale="fr")` → `mardi 14 juillet` |
109//! | `carbon_calendar` | `reference, locale="en"` | `$date->calendar($reference)` | `zoned\|carbon_calendar(other, locale="fr")` → `Aujourd’hui à 09:00` |
110//! | `interval_for_humans` | `short=false, parts=-1, join=false, locale="en", cascade=false` | `$interval->forHumans($options)` | `5400\|interval_for_humans(join=true, cascade=true)` → `1 hour and 30 minutes` |
111//! | `carbon_diff_for_humans_in` | `other, locale="en"` | `$date->diffForHumans($other)` | `zoned\|carbon_diff_for_humans_in(other, locale="fr")` → `2 heures avant` |
112//! | `php_trim`, `php_ltrim`, `php_rtrim` | `characters=none` (PHP byte mask) | PHP trim functions | `"abc!cab" \| php_trim("a..c")` → `!` |
113//! | `arr_join` | `glue`, `final_glue=""` | `Arr::join()` | `["a", "b"] \| arr_join(", ", " and ")` → `a and b` |
114//! | `php_implode` | `separator=""` | `implode()` | `[12, false, "x"] \| php_implode("/")` → `12//x` |
115//! | `php_explode` | `separator, limit=9223372036854775807` | `explode()` | `"a,b,c" \| php_explode(",", limit=2)` → `["a", "b,c"]` |
116//! | `php_array_filter`, `php_array_values` |  | PHP array filtering and reindexing | `["0", "00"] \| php_array_filter \| php_array_values` → `["00"]` |
117//! | `str_append` and `str_prepend` | Variadic parts | `Stringable::append()` / `prepend()` | `"end" \| str_prepend("first ")` → `first end` |
118//! | `carbon_parse` | `tz=none` | `Carbon::parse()` | `"2024-02-29" \| carbon_parse \| carbon_date_string` → `2024-02-29` |
119//! | `carbon_modify` | `modifier, tz=none` | `$date->modify($modifier)` | `"2024-01-31" \| carbon_modify("+1 month") \| carbon_date_string` → `2024-03-02` |
120//! | `php_strtotime` | `base_timestamp=none, tz=none` | `strtotime($text, $baseTimestamp)` | `"+1 week" \| php_strtotime(0)` → `604800` |
121//! | `carbon_create_from_format` | `format, tz=none` | `Carbon::createFromFormat()` | `"2024-02" \| carbon_create_from_format("!Y-m") \| carbon_date_string` → `2024-02-01` |
122//! | `carbon_date_time_string` | `precision="second", tz=none` | `Carbon::toDateTimeString()` | `zoned \| carbon_date_time_string("minute")` → `2026-07-14 09:00` |
123//! | `js_from` | `flags=0, depth=512` | `Js::from()` | `[1, 2] \| js_from` → `JSON.parse('[1,2]')` |
124//! | `php_json_encode` | `flags=0, depth=512`, named flag overrides | `json_encode()` | `"é" \| php_json_encode(unescaped_unicode=true)` → `"é"` |
125//! | `blade_json` | `flags=15, depth=512` | Blade `@json` | `"</script>" \| blade_json` → `"\u003C\/script\u003E"` |
126//! | `php_e` | `double_encode=true` | Laravel `e()` | `"&amp;<" \| php_e(double_encode=false)` → `&amp;&lt;` |
127//! | `php_sprintf`, `php_vsprintf` | Positional values, or one sequence/map for `php_vsprintf` | PHP printf formatting | `"%04d" \| php_sprintf(7)` → `0007` |
128//! | `php_str_starts_with` | `needle` | `str_starts_with()` | `"hello" \| php_str_starts_with("")` → `True` |
129//! | `str_contains` | `needles, ignore_case=false` | `Str::contains()` | `"CAFÉ" \| str_contains(["", "Fé"], ignore_case=true)` → `True` |
130//! | `str_starts_with`, `str_ends_with` | `needles` | `Str::startsWith()`, `Str::endsWith()` | `"été" \| str_ends_with("")` → `False` |
131//! | `str_substr` | `start, length=none` | `Str::substr()` | `"a猫b" \| str_substr(-2, -1)` → `猫` |
132//! | `str_length` |  | `Str::length()` | `"a猫b" \| str_length` → `3` |
133//! | `str_match_all` | `pattern` | `Str::matchAll()` | `"3 12" \| str_match_all("/([0-9]+)/")` → `["3", "12"]` |
134//! | `str_split` | `pattern, limit=-1, flags=0` | `preg_split()` | `"a,b" \| str_split("/,/")` → `["a", "b"]` |
135//! | `str_scan` | `format` | `Stringable::scan()` | `"42 apples" \| str_scan("%d %s")` → `[42, "apples"]` |
136//! | `str_to_boolean` | — | `Stringable::toBoolean()` | `" YES " \| str_to_boolean` → true |
137//! | `now()`, `time()` |  | Current ISO timestamp or Unix seconds from the app clock | `now() \| carbon_format("Y", tz="Asia/Tokyo")` |
138//! | `php_date` | `format, tz=none` as a function, or pass the format as filter input | PHP `date()` with the app clock | `php_date("Y")` or `"Y" \| php_date` |
139//!
140//! `str_replace` and `str_replace_matches` accept a string or sequence for search and
141//! replacement. Searches run in order, and missing parallel replacements mean the empty string.
142//! The regular expression limit applies to each pattern.
143//!
144//! When both precisions are supplied, `max_precision` wins and removes trailing zeros.
145//! For `str_slug`, explicitly passing `language=none` disables transliteration.
146//! `php_round` returns a float. Use `php_echo` to print it with PHP's number-to-string rules.
147//!
148//! ## Relative dates
149//!
150//! Pass `other` for “before” and “after” wording. Omitting it uses `laravel::now()` for
151//! “ago” and “from now”, including the test clock set by `travel` or `freeze_time`.
152//! A standalone environment needs an explicit `other`.
153//!
154//! | Keyword | Default | Effect |
155//! | --- | --- | --- |
156//! | `syntax` | `"auto"` | Override the wording with `"absolute"`, `"relative_to_now"`, or `"relative_to_other"`. |
157//! | `short`, `parts` | `false`, `1` | Use abbreviated units or show more than one unit. |
158//! | `join`, `last_glue` | `false`, `none` | `join=true` uses the selected locale’s conjunctions. Pass a string for custom glue and optionally a second string in `last_glue` for the final pair. |
159//! | `locale` | `"en"` | Carbon translations for the full options builder. |
160//! | `minimum_unit`, `skip` | `none`, `[]` | Limit the smallest displayed unit or skip a list of units. |
161//! | `a_unit` | `false` | Use an article such as “an hour” for a single unit. |
162//! | `options` | `0` | Carbon's flags as a bit mask. The boolean flags below add to it. |
163//! | `just_now`, `no_zero_diff` | `false` | Use “just now” when equal to the clock or replace a zero difference with one unit. |
164//! | `one_day_words`, `two_day_words` | `false` | Enable weekday-relative wording such as “yesterday” and “after tomorrow”. |
165//! | `sequential_parts_only` | `false` | Stop at the first missing unit. |
166//! | `round`, `ceil`, `floor` | `false` | Round excess parts, in that order of precedence. |
167//!
168//! ## Values, errors and escaping
169//!
170//! Null and undefined input generally render as an empty string. The JSON and JavaScript encoders render them
171//! as `null`. Number filters accept MiniJinja integers and floats, PHP numeric strings, and booleans
172//! coerced to `1` or `0`. Integers outside PHP's signed 64-bit range are treated as floats.
173//!
174//! Every Carbon filter accepts an IANA timezone override as `tz=`. The date filters accept
175//! integer or fractional Unix seconds, ISO dates and the framework's serialized Jiff dates and date-times.
176//! An explicit zone converts timestamps and zoned inputs to that zone and interprets civil dates
177//! and times there. By default, timestamps use `FORMATTING_TIMEZONE`, explicit offsets and named
178//! zones are preserved, and civil inputs use UTC. The constructor filters interpret civil
179//! inputs in the configured time zone and use the Laravel clock for clock words and omitted
180//! fields. `carbon_iso_string` renders in UTC by default, accepts `keep_offset=true`,
181//! and returns an empty string for Carbon's null conversion (local year zero).
182//!
183//! `now()`, `time()` and `php_date` require an application context and follow test travel and
184//! freeze. Register the adapter after the optional `minijinja-contrib` helpers to use its `now()`.
185//!
186//! Malformed values produce template errors named for their filter. Most outputs follow
187//! MiniJinja autoescaping. `php_e` returns the exact Laravel-escaped HTML as a safe value.
188//! `blade_json` uses Blade's HEX flags by default. Keep those flags for raw JSON in script
189//! expressions or single-quoted data attributes. `js_from` uses Laravel's required flags
190//! for JavaScript expressions in script elements. Use autoescaped `php_json_encode` in
191//! HTML attributes. All three take `flags` and `depth` (default 512). Named JSON options
192//! such as `pretty_print` and `numeric_check` override the corresponding mask bits.
193
194#![deny(missing_docs)]
195
196pub use laravel_rust_format_core as core;
197pub use laravel_rust_format_core::{Error, ErrorKind, PhpNumber, Result, arr, carbon, js, number, php, prelude, str};
198
199#[cfg(feature = "minijinja")]
200mod filters;
201#[cfg(feature = "minijinja")]
202mod filters_php;
203mod provider;
204
205#[cfg(feature = "minijinja")]
206pub use filters::register_filters;
207pub use provider::{FormattingConfig, FormattingServiceProvider};