aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe-external-packages/src/symfony/console/helper/helper.rs
blob: b599f111610a0e55681e95f3255561120c370a4e (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
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
use crate::symfony::console::formatter::output_formatter_interface::OutputFormatterInterface;
use crate::symfony::console::helper::helper_set::HelperSet;
use crate::symfony::string::unicode_string::UnicodeString;
use std::cell::RefCell;
use std::rc::Rc;

/// Helper is the base class for all helper classes.
#[derive(Debug, Default)]
pub struct Helper {
    pub(crate) helper_set: Option<Rc<RefCell<HelperSet>>>,
}

impl Helper {
    pub fn set_helper_set(&mut self, helper_set: Option<Rc<RefCell<HelperSet>>>) {
        self.helper_set = helper_set;
    }

    pub fn get_helper_set(&self) -> Option<Rc<RefCell<HelperSet>>> {
        self.helper_set.clone()
    }

    /// Returns the length of a string, using mb_strwidth if it is available.
    ///
    /// @deprecated since Symfony 5.3
    pub fn strlen(string: &str) -> i64 {
        shirabe_php_shim::trigger_deprecation(
            "symfony/console",
            "5.3",
            "Method \"%s()\" is deprecated and will be removed in Symfony 6.0. Use Helper::width() or Helper::length() instead.",
            "Helper::strlen",
        );

        Self::width(string)
    }

    /// Returns the width of a string, using mb_strwidth if it is available.
    /// The width is how many characters positions the string will use.
    pub fn width(string: &str) -> i64 {
        if shirabe_php_shim::preg_match("//u", string, &mut Vec::new()) != 0 {
            return UnicodeString::new(string).width(false);
        }

        let encoding = shirabe_php_shim::mb_detect_encoding(string, None, true);
        let encoding = match encoding {
            Some(encoding) => encoding,
            None => return shirabe_php_shim::strlen(string),
        };

        shirabe_php_shim::mb_strwidth(string, Some(&encoding))
    }

    /// Returns the length of a string, using mb_strlen if it is available.
    /// The length is related to how many bytes the string will use.
    pub fn length(string: &str) -> i64 {
        if shirabe_php_shim::preg_match("//u", string, &mut Vec::new()) != 0 {
            return UnicodeString::new(string).length();
        }

        let encoding = shirabe_php_shim::mb_detect_encoding(string, None, true);
        let encoding = match encoding {
            Some(encoding) => encoding,
            None => return shirabe_php_shim::strlen(string),
        };

        shirabe_php_shim::mb_strlen(string, &encoding)
    }

    /// Returns the subset of a string, using mb_substr if it is available.
    pub fn substr(string: &str, from: i64, length: Option<i64>) -> String {
        let encoding = shirabe_php_shim::mb_detect_encoding(string, None, true);
        let encoding = match encoding {
            Some(encoding) => encoding,
            None => return shirabe_php_shim::substr(string, from, length),
        };

        shirabe_php_shim::mb_substr(string, from, length, Some(&encoding))
    }

    pub fn format_time(secs: f64) -> Option<String> {
        // [threshold, label, divisor?]
        let time_formats: [(f64, &str, Option<f64>); 9] = [
            (0.0, "< 1 sec", None),
            (1.0, "1 sec", None),
            (2.0, "secs", Some(1.0)),
            (60.0, "1 min", None),
            (120.0, "mins", Some(60.0)),
            (3600.0, "1 hr", None),
            (7200.0, "hrs", Some(3600.0)),
            (86400.0, "1 day", None),
            (172800.0, "days", Some(86400.0)),
        ];

        for (index, format) in time_formats.iter().enumerate() {
            if secs >= format.0 {
                if (index + 1 < time_formats.len() && secs < time_formats[index + 1].0)
                    || index == time_formats.len() - 1
                {
                    match format.2 {
                        None => return Some(format.1.to_string()),
                        Some(divisor) => {
                            return Some(format!("{} {}", (secs / divisor).floor(), format.1));
                        }
                    }
                }
            }
        }

        None
    }

    pub fn format_memory(memory: i64) -> String {
        if memory >= 1024 * 1024 * 1024 {
            return shirabe_php_shim::sprintf(
                "%.1f GiB",
                &[shirabe_php_shim::PhpMixed::Float(
                    memory as f64 / 1024.0 / 1024.0 / 1024.0,
                )],
            );
        }

        if memory >= 1024 * 1024 {
            return shirabe_php_shim::sprintf(
                "%.1f MiB",
                &[shirabe_php_shim::PhpMixed::Float(
                    memory as f64 / 1024.0 / 1024.0,
                )],
            );
        }

        if memory >= 1024 {
            return shirabe_php_shim::sprintf(
                "%d KiB",
                &[shirabe_php_shim::PhpMixed::Int(memory / 1024)],
            );
        }

        shirabe_php_shim::sprintf("%d B", &[shirabe_php_shim::PhpMixed::Int(memory)])
    }

    /// @deprecated since Symfony 5.3
    pub fn strlen_without_decoration(
        formatter: &mut dyn OutputFormatterInterface,
        string: &str,
    ) -> i64 {
        shirabe_php_shim::trigger_deprecation(
            "symfony/console",
            "5.3",
            "Method \"%s()\" is deprecated and will be removed in Symfony 6.0. Use Helper::removeDecoration() instead.",
            "Helper::strlenWithoutDecoration",
        );

        Self::width(&Self::remove_decoration(formatter, string))
    }

    pub fn remove_decoration(formatter: &mut dyn OutputFormatterInterface, string: &str) -> String {
        let is_decorated = formatter.is_decorated();
        formatter.set_decorated(false);
        // remove <...> formatting
        let string = formatter.format(Some(string)).unwrap().unwrap_or_default();
        // remove already formatted characters
        let string =
            shirabe_php_shim::preg_replace("/\u{1b}\\[[^m]*m/", "", &string).unwrap_or_default();
        // remove terminal hyperlinks
        let string =
            shirabe_php_shim::preg_replace("/\u{1b}]8;[^;]*;[^\u{1b}]*\u{1b}\\\\/", "", &string)
                .unwrap_or_default();
        formatter.set_decorated(is_decorated);

        string
    }
}