ci4

Форк
0
/
Filters.php 
249 строк · 6.4 Кб
1
<?php
2

3
declare(strict_types=1);
4

5
/**
6
 * This file is part of CodeIgniter 4 framework.
7
 *
8
 * (c) CodeIgniter Foundation <admin@codeigniter.com>
9
 *
10
 * For the full copyright and license information, please view
11
 * the LICENSE file that was distributed with this source code.
12
 */
13

14
namespace CodeIgniter\View;
15

16
use NumberFormatter;
17

18
/**
19
 * View filters
20
 */
21
class Filters
22
{
23
    /**
24
     * Returns $value as all lowercase with the first letter capitalized.
25
     */
26
    public static function capitalize(string $value): string
27
    {
28
        return ucfirst(strtolower($value));
29
    }
30

31
    /**
32
     * Formats a date into the given $format.
33
     *
34
     * @param int|string|null $value
35
     */
36
    public static function date($value, string $format): string
37
    {
38
        if (is_string($value) && ! is_numeric($value)) {
39
            $value = strtotime($value);
40
        }
41

42
        if ($value !== null) {
43
            $value = (int) $value;
44
        }
45

46
        return date($format, $value);
47
    }
48

49
    /**
50
     * Given a string or DateTime object, will return the date modified
51
     * by the given value. Returns the value as a unix timestamp
52
     *
53
     * Example:
54
     *      my_date|date_modify(+1 day)
55
     *
56
     * @param int|string|null $value
57
     *
58
     * @return false|int
59
     */
60
    public static function date_modify($value, string $adjustment)
61
    {
62
        $value = static::date($value, 'Y-m-d H:i:s');
63

64
        return strtotime($adjustment, strtotime($value));
65
    }
66

67
    /**
68
     * Returns the given default value if $value is empty or undefined.
69
     *
70
     * @param bool|float|int|list<string>|object|resource|string|null $value
71
     */
72
    public static function default($value, string $default): string
73
    {
74
        return empty($value) // @phpstan-ignore-line
75
            ? $default
76
            : $value;
77
    }
78

79
    /**
80
     * Escapes the given value with our `esc()` helper function.
81
     *
82
     * @param         string                               $value
83
     * @phpstan-param 'html'|'js'|'css'|'url'|'attr'|'raw' $context
84
     */
85
    public static function esc($value, string $context = 'html'): string
86
    {
87
        return esc($value, $context);
88
    }
89

90
    /**
91
     * Returns an excerpt of the given string.
92
     */
93
    public static function excerpt(string $value, string $phrase, int $radius = 100): string
94
    {
95
        helper('text');
96

97
        return excerpt($value, $phrase, $radius);
98
    }
99

100
    /**
101
     * Highlights a given phrase within the text using '<mark></mark>' tags.
102
     */
103
    public static function highlight(string $value, string $phrase): string
104
    {
105
        helper('text');
106

107
        return highlight_phrase($value, $phrase);
108
    }
109

110
    /**
111
     * Highlights code samples with HTML/CSS.
112
     *
113
     * @param string $value
114
     */
115
    public static function highlight_code($value): string
116
    {
117
        helper('text');
118

119
        return highlight_code($value);
120
    }
121

122
    /**
123
     * Limits the number of characters to $limit, and trails of with an ellipsis.
124
     * Will break at word break so may be more or less than $limit.
125
     *
126
     * @param string $value
127
     */
128
    public static function limit_chars($value, int $limit = 500): string
129
    {
130
        helper('text');
131

132
        return character_limiter($value, $limit);
133
    }
134

135
    /**
136
     * Limits the number of words to $limit, and trails of with an ellipsis.
137
     *
138
     * @param string $value
139
     */
140
    public static function limit_words($value, int $limit = 100): string
141
    {
142
        helper('text');
143

144
        return word_limiter($value, $limit);
145
    }
146

147
    /**
148
     * Returns the $value displayed in a localized manner.
149
     *
150
     * @param float|int $value
151
     */
152
    public static function local_number($value, string $type = 'decimal', int $precision = 4, ?string $locale = null): string
153
    {
154
        helper('number');
155

156
        $types = [
157
            'decimal'    => NumberFormatter::DECIMAL,
158
            'currency'   => NumberFormatter::CURRENCY,
159
            'percent'    => NumberFormatter::PERCENT,
160
            'scientific' => NumberFormatter::SCIENTIFIC,
161
            'spellout'   => NumberFormatter::SPELLOUT,
162
            'ordinal'    => NumberFormatter::ORDINAL,
163
            'duration'   => NumberFormatter::DURATION,
164
        ];
165

166
        return format_number((float) $value, $precision, $locale, ['type' => $types[$type]]);
167
    }
168

169
    /**
170
     * Returns the $value displayed as a currency string.
171
     *
172
     * @param float|int $value
173
     * @param int       $fraction
174
     */
175
    public static function local_currency($value, string $currency, ?string $locale = null, $fraction = null): string
176
    {
177
        helper('number');
178

179
        $fraction ??= 0;
180

181
        $options = [
182
            'type'     => NumberFormatter::CURRENCY,
183
            'currency' => $currency,
184
            'fraction' => $fraction,
185
        ];
186

187
        return format_number((float) $value, 2, $locale, $options);
188
    }
189

190
    /**
191
     * Returns a string with all instances of newline character (\n)
192
     * converted to an HTML <br> tag.
193
     */
194
    public static function nl2br(string $value): string
195
    {
196
        $typography = service('typography');
197

198
        return $typography->nl2brExceptPre($value);
199
    }
200

201
    /**
202
     * Takes a body of text and uses the auto_typography() method to
203
     * turn it into prettier, easier-to-read, prose.
204
     */
205
    public static function prose(string $value): string
206
    {
207
        $typography = service('typography');
208

209
        return $typography->autoTypography($value);
210
    }
211

212
    /**
213
     * Rounds a given $value in one of 3 ways;
214
     *
215
     *  - common    Normal rounding
216
     *  - ceil      always rounds up
217
     *  - floor     always rounds down
218
     *
219
     * @param int|string $precision precision or type
220
     *
221
     * @return float|string
222
     */
223
    public static function round(string $value, $precision = 2, string $type = 'common')
224
    {
225
        // In case that $precision is a type like `{ value1|round(ceil) }`
226
        if (! is_numeric($precision)) {
227
            $type      = $precision;
228
            $precision = 2;
229
        } else {
230
            $precision = (int) $precision;
231
        }
232

233
        return match ($type) {
234
            'common' => round((float) $value, $precision),
235
            'ceil'   => ceil((float) $value),
236
            'floor'  => floor((float) $value),
237
            // Still here, just return the value.
238
            default => $value,
239
        };
240
    }
241

242
    /**
243
     * Returns a "title case" version of the string.
244
     */
245
    public static function title(string $value): string
246
    {
247
        return ucwords(strtolower($value));
248
    }
249
}
250

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.