oxblade 0.1.0

Blade templates for Laravel for Rust: Blade's markup and directives, Laravel's helpers, Rust's expressions. Community package, not affiliated with Laravel.
Documentation
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! Blade's insertion-ordered component attribute bag.
//!
//! The merge and rendering rules follow Laravel's MIT-licensed
//! `Illuminate\View\ComponentAttributeBag` and `AppendableAttributeValue`.

use std::{borrow::Cow, fmt, ops::Index};

use indexmap::IndexMap;

use crate::encode::{ArrayKey, Entries, JsonKind, JsonValue, e};

/// The raw attributes in insertion order.
pub type Attributes = IndexMap<String, AttributeValue>;

/// Values accepted by the attribute bag.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub enum AttributeValue {
    /// An absent value, omitted from HTML.
    #[default]
    Null,
    /// A Boolean attribute.
    Bool(bool),
    /// An integer.
    Integer(i64),
    /// A floating-point number.
    Float(f64),
    /// Plain text, with escaping determined by the entry path.
    Text(String),
    /// Trusted HTML, corresponding to Laravel's `Htmlable`.
    Html(String),
    /// An object with an untrusted string representation.
    Stringable(String),
    /// An object implementing Laravel's escape-on-cast contract.
    Escapable {
        /// The unescaped string representation.
        text: String,
        /// Whether the string representation is escaped on display.
        escape: bool,
    },
    /// Structured data. Access and filtering preserve it, and HTML rendering rejects it.
    Array(Attributes),
    /// A default that prepends to the supplied value on merge.
    Prepended(Box<AttributeValue>),
}

impl From<&str> for AttributeValue {
    fn from(value: &str) -> Self {
        Self::Text(value.to_owned())
    }
}

impl From<String> for AttributeValue {
    fn from(value: String) -> Self {
        Self::Text(value)
    }
}

impl AttributeValue {
    pub(crate) fn depth_within(&self, remaining: usize) -> bool {
        match self {
            Self::Array(values) => {
                remaining > 0
                    && values
                        .values()
                        .all(|value| value.depth_within(remaining - 1))
            }
            Self::Prepended(value) => remaining > 0 && value.depth_within(remaining - 1),
            _ => true,
        }
    }

    fn php_string(&self) -> Result<Cow<'_, str>, AttributeError> {
        Ok(match self {
            Self::Text(text) | Self::Html(text) | Self::Stringable(text) => Cow::Borrowed(text),
            Self::Escapable { text, escape: true } => Cow::Owned(e(text)),
            Self::Escapable {
                text,
                escape: false,
            } => Cow::Borrowed(text),
            Self::Null | Self::Bool(false) => Cow::Borrowed(""),
            Self::Bool(true) => Cow::Borrowed("1"),
            Self::Integer(number) => Cow::Owned(number.to_string()),
            Self::Float(number) => Cow::Owned(php_float(*number)),
            Self::Prepended(value) => value.php_string()?,
            Self::Array(_) => return Err(AttributeError::ArrayAsText),
        })
    }

    fn truthy(&self) -> bool {
        match self {
            Self::Null | Self::Bool(false) | Self::Integer(0) => false,
            Self::Float(value) => *value != 0.0,
            Self::Text(value) => !matches!(value.as_str(), "" | "0"),
            Self::Array(values) => !values.is_empty(),
            _ => true,
        }
    }

    fn escape_default(&self, escape: bool) -> Result<Self, AttributeError> {
        Ok(match self {
            Self::Text(_) | Self::Integer(_) | Self::Float(_) | Self::Array(_) if escape => {
                Self::Text(e(&self.php_string()?))
            }
            value => value.clone(),
        })
    }
}

/// A value that cannot be printed as an HTML attribute.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum AttributeError {
    /// Arrays have no scalar representation in HTML attributes.
    ArrayAsText,
    /// A name contains a character that cannot appear in HTML attribute syntax.
    InvalidName,
    /// Rendering these attributes would exceed the available HTML bytes.
    OutputLimit,
}

impl fmt::Display for AttributeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::ArrayAsText => "an array cannot be printed as an HTML attribute",
            Self::InvalidName => "invalid attribute name",
            Self::OutputLimit => "render output limit exceeded while writing attributes",
        })
    }
}

impl std::error::Error for AttributeError {}

/// One item in a Blade class or style list.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum CssEntry<'a> {
    /// Always include the given class or declaration.
    Always(&'a str),
    /// Include the given class or declaration if the condition holds.
    If(&'a str, bool),
}

/// An ordered collection of attributes supplied to a component or slot.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct AttributeBag {
    attributes: Attributes,
}

impl AttributeBag {
    pub(crate) fn check_data_depth(&mut self) -> crate::error::Result<()> {
        if self
            .attributes
            .values()
            .all(|value| value.depth_within(crate::value::MAX_OWNED_DATA_DEPTH))
        {
            return Ok(());
        }
        let mut pending = std::mem::take(&mut self.attributes)
            .into_values()
            .collect::<Vec<_>>();
        while let Some(value) = pending.pop() {
            match value {
                AttributeValue::Array(values) => pending.extend(values.into_values()),
                AttributeValue::Prepended(value) => pending.push(*value),
                _ => {}
            }
        }
        Err(crate::library::data_depth_error())
    }

    /// Create a bag from raw attributes. Each value retains its current escaping.
    pub fn new(attributes: Attributes) -> Self {
        Self { attributes }
    }

    /// The raw attributes, including null values and omitted Boolean attributes.
    pub fn all(&self) -> &Attributes {
        &self.attributes
    }

    /// Return the raw attributes for the requested keys in their original order.
    pub fn all_for(&self, keys: &[&str]) -> Attributes {
        self.only(keys).attributes
    }

    /// The first value, if the first entry exists and is non-null.
    pub fn first(&self) -> Option<&AttributeValue> {
        self.attributes
            .first()
            .map(|(_, value)| value)
            .filter(|value| !matches!(value, AttributeValue::Null))
    }

    /// Look up an exact key. Null values take the default path, as in Laravel.
    pub fn get(&self, key: &str) -> Option<&AttributeValue> {
        self.attributes
            .get(key)
            .filter(|value| !matches!(value, AttributeValue::Null))
    }

    /// Find a value or lazily compute a fallback.
    pub fn get_or_else(
        &self,
        key: &str,
        default: impl FnOnce() -> AttributeValue,
    ) -> AttributeValue {
        self.get(key).cloned().unwrap_or_else(default)
    }

    /// Retrieve the first value or lazily compute a fallback.
    pub fn first_or_else(&self, default: impl FnOnce() -> AttributeValue) -> AttributeValue {
        self.first().cloned().unwrap_or_else(default)
    }

    /// Retain the requested keys, in bag order.
    pub fn only(&self, keys: &[&str]) -> Self {
        self.filter(|_, key| keys.contains(&key))
    }

    /// Exclude the requested keys. Dotted names can also remove nested array entries.
    pub fn except(&self, keys: &[&str]) -> Self {
        let mut attributes = self.attributes.clone();
        for key in keys {
            remove_path(&mut attributes, key);
        }
        Self::new(attributes)
    }

    /// Retain entries whose value and key pass the callback.
    pub fn filter(&self, mut predicate: impl FnMut(&AttributeValue, &str) -> bool) -> Self {
        Self::new(
            self.attributes
                .iter()
                .filter(|(key, value)| predicate(value, key))
                .map(|(key, value)| (key.clone(), value.clone()))
                .collect(),
        )
    }

    /// Retain keys that begin with any nonempty prefix.
    pub fn where_starts_with(&self, prefixes: &[&str]) -> Self {
        self.filter(|_, key| starts_with(key, prefixes))
    }

    /// Retain keys that begin with none of the nonempty prefixes.
    pub fn where_doesnt_start_with(&self, prefixes: &[&str]) -> Self {
        self.filter(|_, key| !starts_with(key, prefixes))
    }

    /// Alias for `where_starts_with`.
    pub fn that_start_with(&self, prefixes: &[&str]) -> Self {
        self.where_starts_with(prefixes)
    }

    /// Expand template-facing prop names to include the name and Laravel's kebab-case spelling.
    pub fn extract_prop_names(names: &[&str]) -> Vec<String> {
        names
            .iter()
            .flat_map(|name| [(*name).to_owned(), kebab(name)])
            .collect()
    }

    /// Retain prop attributes by their declared or kebab-case name.
    pub fn only_props(&self, names: &[&str]) -> Self {
        let props = Self::extract_prop_names(names);
        self.filter(|_, key| props.iter().any(|prop| prop == key))
    }

    /// Exclude prop attributes by their declared or kebab-case name.
    pub fn except_props(&self, names: &[&str]) -> Self {
        let props = Self::extract_prop_names(names);
        self.except(&props.iter().map(String::as_str).collect::<Vec<_>>())
    }

    /// Whether all keys exist, including keys with null values and nested array paths.
    pub fn has(&self, keys: &[&str]) -> bool {
        keys.iter().all(|key| has_path(&self.attributes, key))
    }

    /// Whether any key exists, including keys with null values and nested array paths.
    pub fn has_any(&self, keys: &[&str]) -> bool {
        keys.iter().any(|key| has_path(&self.attributes, key))
    }

    /// Whether at least one of the requested keys is missing.
    pub fn missing(&self, keys: &[&str]) -> bool {
        !self.has(keys)
    }

    /// Apply a transformation when the Boolean condition holds.
    ///
    /// The result can be a bag or a caller's runtime value that can also hold the fallback bag.
    pub fn when<T: From<Self>>(
        &self,
        condition: bool,
        callback: impl FnOnce(&Self, bool) -> Option<T>,
    ) -> T {
        self.when_else(condition, callback, |_, _| None)
    }

    /// Apply a transformation when the Boolean condition is false.
    pub fn unless<T: From<Self>>(
        &self,
        condition: bool,
        callback: impl FnOnce(&Self, bool) -> Option<T>,
    ) -> T {
        self.unless_else(condition, callback, |_, _| None)
    }

    /// Apply either branch, falling back to the original bag if the selected callback returns null.
    pub fn when_else<T: From<Self>>(
        &self,
        condition: bool,
        callback: impl FnOnce(&Self, bool) -> Option<T>,
        default: impl FnOnce(&Self, bool) -> Option<T>,
    ) -> T {
        let result = if condition {
            callback(self, condition)
        } else {
            default(self, condition)
        };
        result.unwrap_or_else(|| self.clone().into())
    }

    /// Apply either branch, running the main callback when the condition is false.
    pub fn unless_else<T: From<Self>>(
        &self,
        condition: bool,
        callback: impl FnOnce(&Self, bool) -> Option<T>,
        default: impl FnOnce(&Self, bool) -> Option<T>,
    ) -> T {
        self.when_else(condition, default, callback)
    }

    /// Construct a default value which appends the provided attribute after the default.
    pub fn prepends(&self, value: impl Into<AttributeValue>) -> AttributeValue {
        match value.into() {
            value @ AttributeValue::Prepended(_) => value,
            value => AttributeValue::Prepended(Box::new(value)),
        }
    }

    /// Merge a class list through the same escaped-default path as `merge`.
    pub fn class(&self, entries: &[CssEntry<'_>]) -> Result<Self, AttributeError> {
        self.merge_css("class", entries)
    }

    /// Merge a style list, finishing each style with a semicolon.
    pub fn style(&self, entries: &[CssEntry<'_>]) -> Result<Self, AttributeError> {
        self.merge_css("style", entries)
    }

    fn merge_css(&self, key: &str, entries: &[CssEntry<'_>]) -> Result<Self, AttributeError> {
        let parts: Vec<_> = entries
            .iter()
            .filter_map(|entry| match entry {
                CssEntry::If(_, false) => None,
                CssEntry::Always(text) | CssEntry::If(text, true) if key == "style" => {
                    Some(finish_style(text))
                }
                CssEntry::Always(text) | CssEntry::If(text, true) => Some(Cow::Borrowed(*text)),
            })
            .collect();
        self.merge(&[(key.to_owned(), parts.join(" ").into())].into(), true)
    }

    /// Add defaults in their supplied order, optionally escaping them. Class, style and
    /// prepended defaults are joined with supplied values rather than being replaced.
    pub fn merge(&self, defaults: &Attributes, escape: bool) -> Result<Self, AttributeError> {
        let defaults: Attributes = defaults
            .iter()
            .map(|(key, value)| {
                validate_name(key)?;
                let value = match value {
                    AttributeValue::Prepended(value) => {
                        AttributeValue::Prepended(Box::new(value.escape_default(escape)?))
                    }
                    value => value.escape_default(escape)?,
                };
                Ok((key.clone(), value))
            })
            .collect::<Result<_, AttributeError>>()?;
        let (appendable, ordinary): (Vec<_>, Vec<_>) =
            self.attributes.iter().partition(|(key, _)| {
                matches!(key.as_str(), "class" | "style")
                    || matches!(defaults.get(*key), Some(AttributeValue::Prepended(_)))
            });
        let mut result = Attributes::with_capacity(defaults.len() + self.attributes.len());
        let mut next_index = 0;
        for (key, value) in &defaults {
            insert_merged(&mut result, key, value.clone(), &mut next_index);
        }
        for (key, value) in appendable {
            let default = match defaults.get(key) {
                Some(AttributeValue::Prepended(value)) => value.as_ref().clone(),
                Some(value) => value.clone(),
                None => AttributeValue::Null,
            };
            let merged = append_attribute(key, &default, value)?;
            insert_merged(&mut result, key, merged.into(), &mut next_index);
        }
        for (key, value) in ordinary {
            insert_merged(&mut result, key, value.clone(), &mut next_index);
        }
        Ok(Self::new(result))
    }

    /// Insert a compiler literal. An interpolated literal must already contain escaped echoes.
    /// The literal fragments and the rendered echoes retain their exact bytes here.
    pub fn insert_literal(&mut self, name: impl Into<String>, value: impl Into<String>) {
        self.attributes
            .insert(name.into(), AttributeValue::Text(value.into()));
    }

    /// Insert a bound attribute, applying Laravel's `sanitizeComponentAttribute` rules.
    pub fn insert_bound(&mut self, name: impl Into<String>, value: impl Into<AttributeValue>) {
        self.attributes
            .insert(name.into(), sanitize_component_attribute(value.into()));
    }

    /// Forward a parent bag. Local attributes act as its unescaped defaults.
    pub fn forward(&self, parent: &Self) -> Result<Self, AttributeError> {
        parent.merge(&self.attributes, false)
    }

    /// Read the underlying attributes, including omitted values.
    pub fn get_attributes(&self) -> &Attributes {
        self.all()
    }

    /// Replace the raw attributes without escaping them.
    pub fn set_attributes(&mut self, attributes: Attributes) {
        self.attributes = attributes;
    }

    /// Whether an offset is set and non-null, following PHP's `isset`.
    pub fn offset_exists(&self, key: &str) -> bool {
        self.get(key).is_some()
    }

    /// Access a non-null value by its exact key.
    pub fn offset_get(&self, key: &str) -> Option<&AttributeValue> {
        self.get(key)
    }

    /// Set an offset without sanitizing the value.
    pub fn offset_set(&mut self, key: impl Into<String>, value: impl Into<AttributeValue>) {
        self.attributes.insert(key.into(), value.into());
    }

    /// Remove an offset, preserving the order of the remaining entries.
    pub fn offset_unset(&mut self, key: &str) {
        self.attributes.shift_remove(key);
    }

    /// Iterate over the raw values in insertion order.
    pub fn get_iterator(&self) -> indexmap::map::Iter<'_, String, AttributeValue> {
        self.attributes.iter()
    }

    /// Return the raw map as a serialization input.
    pub fn json_serialize(&self) -> &Attributes {
        self.all()
    }

    /// Return the raw attributes as an ordered map.
    pub fn to_array(&self) -> Attributes {
        self.attributes.clone()
    }

    /// Merge escaped defaults and render the result, as when a Blade bag is called.
    pub fn invoke(&self, defaults: &Attributes) -> Result<String, AttributeError> {
        self.merge(defaults, true)?.to_html()
    }

    /// Whether the bag renders to an empty string.
    pub fn is_empty(&self) -> Result<bool, AttributeError> {
        Ok(self.to_html()?.is_empty())
    }

    /// Whether the bag renders any HTML attributes.
    pub fn is_not_empty(&self) -> Result<bool, AttributeError> {
        Ok(!self.is_empty()?)
    }

    /// Render the attributes using HTML encoding, preserving existing entities.
    pub fn to_html(&self) -> Result<String, AttributeError> {
        self.to_html_bounded(usize::MAX)
    }

    pub(crate) fn to_html_bounded(&self, max_bytes: usize) -> Result<String, AttributeError> {
        let mut html = String::new();
        let mut first = true;
        let mut push = |text: &str| {
            if text.len() > max_bytes.saturating_sub(html.len()) {
                return Err(AttributeError::OutputLimit);
            }
            html.push_str(text);
            Ok(())
        };
        for (key, value) in &self.attributes {
            validate_name(key)?;
            let text = match value {
                AttributeValue::Null | AttributeValue::Bool(false) => continue,
                AttributeValue::Bool(true) if key == "x-data" || key.starts_with("wire:") => {
                    Cow::Borrowed("")
                }
                AttributeValue::Bool(true) => Cow::Borrowed(key.as_str()),
                value => value.php_string()?,
            };
            if !first {
                push(" ")?;
            }
            first = false;
            push(key)?;
            push("=\"")?;
            crate::encode::escape_attribute_parts(php_trim(&text), &mut push)?;
            push("\"")?;
        }
        Ok(html)
    }
}

impl Index<&str> for AttributeBag {
    type Output = AttributeValue;

    fn index(&self, key: &str) -> &Self::Output {
        self.get(key).unwrap_or(&AttributeValue::Null)
    }
}

impl<'a> IntoIterator for &'a AttributeBag {
    type Item = (&'a String, &'a AttributeValue);
    type IntoIter = indexmap::map::Iter<'a, String, AttributeValue>;

    fn into_iter(self) -> Self::IntoIter {
        self.get_iterator()
    }
}

impl JsonValue for AttributeValue {
    fn json_kind(&self) -> JsonKind<'_> {
        match self {
            Self::Null => JsonKind::Null,
            Self::Bool(value) => JsonKind::Bool(*value),
            Self::Integer(value) => JsonKind::Integer(*value),
            Self::Float(value) => JsonKind::Float(*value),
            Self::Text(value) => JsonKind::String(value.as_bytes()),
            Self::Html(_) | Self::Stringable(_) | Self::Escapable { .. } => {
                JsonKind::Object(Box::new(std::iter::empty()))
            }
            Self::Array(values) => JsonKind::Array(json_entries(values)),
            Self::Prepended(value) => JsonKind::Object(Box::new(std::iter::once((
                ArrayKey::from("value"),
                value.as_ref() as &dyn JsonValue,
            )))),
        }
    }
}

impl JsonValue for AttributeBag {
    fn json_kind(&self) -> JsonKind<'_> {
        JsonKind::Array(json_entries(&self.attributes))
    }
}

fn json_entries(values: &Attributes) -> Entries<'_> {
    Box::new(values.iter().map(|(key, value)| {
        let key = integer_key(key).map_or_else(|| ArrayKey::from(key.as_str()), ArrayKey::Integer);
        (key, value as &dyn JsonValue)
    }))
}

/// Escape plain bound text and untrusted stringable objects. Trusted HTML is
/// converted to text as-is. Escape-on-cast objects are marked for later escaping.
/// Other bound values retain their original representation.
pub fn sanitize_component_attribute(value: AttributeValue) -> AttributeValue {
    match value {
        AttributeValue::Text(text) | AttributeValue::Stringable(text) => {
            AttributeValue::Text(e(&text))
        }
        AttributeValue::Html(text) => AttributeValue::Text(text),
        AttributeValue::Escapable { text, .. } => AttributeValue::Escapable { text, escape: true },
        AttributeValue::Prepended(value) => {
            AttributeValue::Prepended(Box::new(sanitize_component_attribute(*value)))
        }
        value => value,
    }
}

pub(crate) fn validate_name(name: &str) -> Result<(), AttributeError> {
    if name.is_empty()
        || name.bytes().any(|byte| {
            byte.is_ascii_control() || byte.is_ascii_whitespace() || b"/=\"'<>".contains(&byte)
        })
    {
        return Err(AttributeError::InvalidName);
    }
    Ok(())
}

fn append_attribute(
    key: &str,
    default: &AttributeValue,
    value: &AttributeValue,
) -> Result<String, AttributeError> {
    let default = match default {
        AttributeValue::Text(text) if key == "style" && !text.is_empty() => {
            Some(finish_style(text))
        }
        value if value.truthy() => Some(value.php_string()?),
        _ => None,
    };
    let value = if key == "style" {
        Some(Cow::Owned(finish_style(&value.php_string()?).into_owned()))
    } else if value.truthy() {
        Some(value.php_string()?)
    } else {
        None
    };
    Ok(match (default, value) {
        (Some(default), Some(value)) if default != value => format!("{default} {value}"),
        (Some(text), _) | (_, Some(text)) => text.into_owned(),
        (None, None) => String::new(),
    })
}

fn finish_style(value: &str) -> Cow<'_, str> {
    if value.ends_with(';') && !value.ends_with(";;") {
        Cow::Borrowed(value)
    } else {
        Cow::Owned(format!("{};", value.trim_end_matches(';')))
    }
}

fn php_trim(value: &str) -> &str {
    value.trim_matches([' ', '\t', '\n', '\r', '\0', '\u{b}'])
}

fn starts_with(key: &str, prefixes: &[&str]) -> bool {
    prefixes
        .iter()
        .any(|prefix| !prefix.is_empty() && key.starts_with(prefix))
}

fn has_path(attributes: &Attributes, key: &str) -> bool {
    if attributes.contains_key(key) {
        return true;
    }
    let mut segments = key.split('.').peekable();
    let mut current = attributes;
    while let Some(segment) = segments.next() {
        match current.get(segment) {
            Some(_) if segments.peek().is_none() => return true,
            Some(AttributeValue::Array(values)) => current = values,
            _ => return false,
        }
    }
    false
}

fn remove_path(attributes: &mut Attributes, key: &str) {
    if attributes.shift_remove(key).is_some() {
        return;
    }
    let mut segments = key.split('.').peekable();
    let mut current = attributes;
    while let Some(segment) = segments.next() {
        if segments.peek().is_none() {
            current.shift_remove(segment);
            return;
        }
        match current.get_mut(segment) {
            Some(AttributeValue::Array(values)) => current = values,
            _ => return,
        }
    }
}

fn insert_merged(
    attributes: &mut Attributes,
    key: &str,
    value: AttributeValue,
    next_index: &mut usize,
) {
    let key = if key
        .parse::<i64>()
        .is_ok_and(|index| index.to_string() == key)
    {
        let key = next_index.to_string();
        *next_index += 1;
        key
    } else {
        key.to_owned()
    };
    attributes.insert(key, value);
}

fn integer_key(key: &str) -> Option<i64> {
    let index = key.parse::<i64>().ok()?;
    (index.to_string() == key).then_some(index)
}

fn kebab(value: &str) -> String {
    let mut result = String::new();
    let mut word_start = true;
    for ch in value.chars() {
        if ch.is_whitespace() {
            word_start |= matches!(ch, ' ' | '\t' | '\r' | '\n' | '\u{b}' | '\u{c}');
            continue;
        }
        let ch = if word_start {
            ch.to_ascii_uppercase()
        } else {
            ch
        };
        if !result.is_empty() && ch.is_ascii_uppercase() {
            result.push('-');
        }
        result.push(ch);
        word_start = false;
    }
    result.to_lowercase()
}

fn php_float(number: f64) -> String {
    if number.is_nan() {
        return "NAN".to_owned();
    }
    if !number.is_finite() {
        return if number.is_sign_negative() {
            "-INF"
        } else {
            "INF"
        }
        .to_owned();
    }
    let scientific = format!("{number:.13e}");
    let (mantissa, exponent) = scientific.split_once('e').unwrap_or((&scientific, "0"));
    let exponent = exponent.parse::<i32>().unwrap_or(0);
    if (-4..14).contains(&exponent) {
        let decimal = format!("{number:.precision$}", precision = (13 - exponent) as usize);
        decimal
            .trim_end_matches('0')
            .trim_end_matches('.')
            .to_owned()
    } else {
        let truncated = mantissa.trim_end_matches('0').trim_end_matches('.');
        let fraction = if truncated.contains('.') { "" } else { ".0" };
        format!("{truncated}{fraction}E{exponent:+}")
    }
}