Skip to main content

oxblade/
collections.rs

1//! Laravel collection operations on Rust lists and insertion-ordered maps.
2//!
3//! List results compact indices after filtering, sorting, slicing, reversing, set operations,
4//! grouping and chunking. Maps keep keys unless an operation explicitly emits values, and retain
5//! their shape when empty. Group keys appear in first-seen order. Map equality compares fields
6//! irrespective of insertion order, while list equality compares in order.
7//!
8//! The selector methods (`where`, membership, uniqueness, search, set operations and their
9//! strict aliases) compare without PHP coercion. Any accepted PHP strictness flags leave that
10//! behavior in place. Predicates require booleans, and `filter()` with no predicate removes
11//! missing values. Ordering requires compatible Rust types, and ties in either sort direction
12//! retain input order. Numeric aggregates accept homogeneous integers or floats, integer sums
13//! check overflow, and `avg` always returns a float when it finds a result. A failed search is
14//! `None`.
15//!
16//! `len`, `rev` and `join` replace Laravel's `count`, `reverse` and `implode`. Join uses Rust's
17//! display formatting. The collection JSON methods use standard JSON escaping, and PHP-specific
18//! JSON and sort flags are outside native dispatch. Collection constructors
19//! produce lists and maps directly. `range` uses integer endpoints and steps. Map keys are
20//! strings, and integer keys emitted into maps use their decimal spelling.
21//!
22//! In-place methods return the replacement collection. For operations that return an extracted
23//! item in PHP (`pull`, `pop`, `shift`, `splice`, `get_or_put`), use lookup before the update
24//! to read the old item. The static `Arr` update helpers also return the resulting collection.
25//! Consult `design/DECISIONS.md` for operations requiring PHP objects, shared mutation, laziness,
26//! or randomness.
27
28use crate::{
29    error::Result,
30    library::CallLimits,
31    value::{Arg, Value},
32};
33
34mod arrange;
35mod arrays;
36mod mutate;
37mod select;
38mod support;
39mod transform;
40
41use support::{Args, is_collection};
42
43/// Dispatches a collection method for a list, map, or borrowed JSON collection.
44///
45/// Returns `None` for names outside the collection library or scalar receivers. The evaluator
46/// attaches source information to errors and writes replacement collections to mutable bindings.
47pub fn method<'a>(
48    name: &str,
49    receiver: &Value<'a>,
50    args: Vec<Arg<'a, '_>>,
51) -> Option<Result<Value<'a>>> {
52    method_with_limits(name, receiver, args, CallLimits::default())
53}
54
55pub(crate) fn method_with_limits<'a>(
56    name: &str,
57    receiver: &Value<'a>,
58    args: Vec<Arg<'a, '_>>,
59    limits: CallLimits,
60) -> Option<Result<Value<'a>>> {
61    if !is_collection(receiver) {
62        return None;
63    }
64
65    let mut args = Args(args, limits);
66    macro_rules! dispatch {
67        ($($group:ident { $($method:literal : $min:literal $(, $max:expr)?;)* })*) => {
68            match name {
69                $($($method => {
70                    let max = [$min $(, $max)?].into_iter().last().unwrap_or($min);
71                    args.count(name, $min, max)
72                        .and_then(|()| $group::run(name, receiver, &mut args))
73                },)*)*
74                _ => return None,
75            }
76        };
77    }
78
79    Some(dispatch! {
80        select {
81            "len": 0;
82            "is_empty": 0;
83            "is_not_empty": 0;
84            "filter": 0, 1;
85            "reject": 0, 1;
86            "where": 1, 3;
87            "where_by": 1;
88            "where_strict": 2;
89            "where_null": 0, 1;
90            "where_not_null": 0, 1;
91            "where_in": 2, 3;
92            "where_in_strict": 2;
93            "where_not_in": 2, 3;
94            "where_not_in_strict": 2;
95            "where_between": 2;
96            "where_not_between": 2;
97            "where_instance_of": 1;
98            "first_where": 1, 3;
99            "first": 0, 2;
100            "last": 0, 2;
101            "sole": 0, 3;
102            "first_or_fail": 0, 3;
103            "has_sole": 0, 3;
104            "has_many": 0, 3;
105            "contains": 1, 3;
106            "some": 1, 3;
107            "doesnt_contain": 1, 3;
108            "doesnt_contain_strict": 1, 3;
109            "contains_strict": 1, 2;
110            "contains_one_item": 0, 1;
111            "contains_many_items": 0, 1;
112            "every": 1, 3;
113            "partition": 1, 3;
114            "percentage": 1, 2;
115            "ensure": 1;
116            "before": 1, 2;
117            "after": 1, 2;
118            "search": 1, 2;
119            "diff": 1;
120            "diff_using": 2;
121            "diff_assoc": 1;
122            "diff_assoc_using": 2;
123            "diff_keys": 1;
124            "diff_keys_using": 2;
125            "intersect": 1;
126            "intersect_using": 2;
127            "intersect_assoc": 1;
128            "intersect_assoc_using": 2;
129            "intersect_by_keys": 1;
130            "only_values": 1, 2;
131            "except_values": 1, 2;
132        }
133        transform {
134            "all": 0;
135            "collect": 0;
136            "to_base": 0;
137            "to_array": 0;
138            "json_serialize": 0;
139            "to_json": 0;
140            "to_pretty_json": 0;
141            "map": 1;
142            "transform": 1;
143            "map_spread": 1;
144            "map_to_dictionary": 1;
145            "map_to_groups": 1;
146            "map_with_keys": 1;
147            "flat_map": 1;
148            "pluck": 1, 2;
149            "key_by": 1;
150            "group_by": 1, 2;
151            "count_by": 0, 1;
152            "keys": 0;
153            "values": 0;
154            "divide": 0;
155            "flip": 0;
156            "select": 1;
157            "sum": 0, 1;
158            "avg": 0, 1;
159            "average": 0, 1;
160            "min": 0, 1;
161            "max": 0, 1;
162            "median": 0, 1;
163            "mode": 0, 1;
164            "reduce": 1, 2;
165            "reduce_with_keys": 1, 2;
166            "reduce_spread": 1, usize::MAX;
167            "pipe": 1;
168            "pipe_through": 1;
169            "when": 2, 3;
170            "unless": 2, 3;
171            "when_empty": 1, 2;
172            "when_not_empty": 1, 2;
173            "unless_empty": 1, 2;
174            "unless_not_empty": 1, 2;
175            "join": 1, 2;
176            "to_css_classes": 0;
177            "to_css_styles": 0;
178            "query": 0;
179        }
180        arrange {
181            "rev": 0;
182            "sort": 0, 1;
183            "sort_desc": 0;
184            "sort_by": 1, 3;
185            "sort_by_desc": 1, 2;
186            "sort_keys": 0, 2;
187            "sort_keys_desc": 0, 1;
188            "sort_keys_using": 1;
189            "sort_recursive": 0, 2;
190            "sort_recursive_desc": 0, 1;
191            "unique": 0, 2;
192            "unique_strict": 0, 1;
193            "duplicates": 0, 2;
194            "duplicates_strict": 0, 1;
195            "chunk": 1, 2;
196            "chunk_while": 1;
197            "chunk_by": 1;
198            "split": 1;
199            "split_in": 1;
200            "sliding": 0, 2;
201            "take": 1;
202            "take_until": 1;
203            "take_while": 1;
204            "skip": 1;
205            "skip_until": 1;
206            "skip_while": 1;
207            "slice": 1, 2;
208            "for_page": 2;
209            "nth": 1, 2;
210            "flatten": 0, 1;
211            "collapse": 0;
212            "collapse_with_keys": 0;
213            "dot": 0, 1;
214            "undot": 0;
215            "zip": 1, usize::MAX;
216            "cross_join": 0, usize::MAX;
217        }
218        mutate {
219            "push": 0, usize::MAX;
220            "add": 1;
221            "unshift": 0, usize::MAX;
222            "prepend": 1, 2;
223            "pop": 0, 1;
224            "shift": 0, 1;
225            "splice": 1, 3;
226            "put": 2;
227            "set": 2;
228            "get_or_put": 2;
229            "forget": 1;
230            "pull": 1, 2;
231            "merge": 1;
232            "merge_recursive": 1;
233            "replace": 1;
234            "replace_recursive": 1;
235            "concat": 1;
236            "union": 1;
237            "combine": 1;
238            "multiply": 1;
239            "pad": 2;
240            "prepend_keys_with": 1;
241        }
242        arrays {
243            "get": 1, 2;
244            "value": 1, 2;
245            "array": 1, 2;
246            "boolean": 1, 2;
247            "float": 1, 2;
248            "integer": 1, 2;
249            "string": 1, 2;
250            "contains_key": 1;
251            "exists": 1;
252            "offset_exists": 1;
253            "offset_get": 1;
254            "offset_set": 2;
255            "offset_unset": 1;
256            "has": 1, usize::MAX;
257            "has_all": 1, usize::MAX;
258            "has_any": 1, usize::MAX;
259            "is_assoc": 0;
260            "is_list": 0;
261            "only": 1;
262            "except": 1;
263        }
264    })
265}
266
267/// Dispatches static constructors and `Arr` helpers with their array argument first.
268///
269/// Use `collection::` or `arr::` as the namespace. Static array operations whose signature
270/// differs from a collection method use the corresponding Laravel array signature.
271pub fn function<'a>(name: &str, args: Vec<Arg<'a, '_>>) -> Option<Result<Value<'a>>> {
272    function_with_limits(name, args, CallLimits::default())
273}
274
275pub(crate) fn function_with_limits<'a>(
276    name: &str,
277    args: Vec<Arg<'a, '_>>,
278    limits: CallLimits,
279) -> Option<Result<Value<'a>>> {
280    arrays::function(name, args, limits)
281}