TypogrifyVariable::normalizeText()   A
last analyzed

Complexity

Conditions 5
Paths 6

Size

Total Lines 36
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 1 Features 0
Metric Value
cc 5
eloc 10
c 8
b 1
f 0
nc 6
nop 1
dl 0
loc 36
rs 9.6111
1
<?php
2
/**
3
 * Typogrify plugin for Craft CMS
4
 *
5
 * Typogrify prettifies your web typography by preventing ugly quotes and 'widows' and more
6
 *
7
 * @link      https://nystudio107.com/
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\typogrify\variables;
12
13
use Craft;
14
use craft\helpers\Template;
15
use DateInterval;
16
use DateTime;
17
use nystudio107\typogrify\Typogrify;
18
use PHP_Typography\Settings;
19
use Stringy\Stringy;
20
use Twig\Markup;
21
22
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
23
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
24
 * @package   Typogrify
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
25
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
26
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
27
class TypogrifyVariable
28
{
29
    // Public Methods
30
    // =========================================================================
31
32
    /**
33
     * Typogrify applies a veritable kitchen sink of typographic treatments to
34
     * beautify your web typography
35
     *
36
     * @param string|int|float|null $text The text or HTML fragment to process
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
37
     * @param bool $isTitle Optional. If the HTML fragment is a title.
0 ignored issues
show
Coding Style introduced by
Expected 18 spaces after parameter type; 1 found
Loading history...
38
     *                        Default false
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 22 spaces but found 24
Loading history...
39
     *
40
     * @return Markup
41
     */
42
    public function typogrify(string|int|float|null $text, bool $isTitle = false): Markup
43
    {
44
        $text = $this->normalizeText($text);
45
        return Template::raw(Typogrify::$plugin->typogrify->typogrify($text, $isTitle));
46
    }
47
48
    /**
49
     * Typogrify applies a veritable kitchen sink of typographic treatments to
50
     * beautify your web typography but in a way that is appropriate for RSS
51
     * (or similar) feeds -- i.e. excluding processes that may cause issues in
52
     * contexts with limited character set intelligence.
53
     *
54
     * @param string|int|float|null $text The text or HTML fragment to process
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
55
     * @param bool $isTitle Optional. If the HTML fragment is a title.
0 ignored issues
show
Coding Style introduced by
Expected 18 spaces after parameter type; 1 found
Loading history...
56
     *                        Default false
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 22 spaces but found 24
Loading history...
57
     *
58
     * @return Markup
59
     */
60
    public function typogrifyFeed(string|int|float|null $text, bool $isTitle = false): Markup
61
    {
62
        $text = $this->normalizeText($text);
63
        return Template::raw(Typogrify::$plugin->typogrify->typogrifyFeed($text, $isTitle));
64
    }
65
66
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
67
     * @param string|int|float|null $text
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
68
     *
69
     * @return Markup
70
     */
71
    public function smartypants(string|int|float|null $text): Markup
72
    {
73
        $text = $this->normalizeText($text);
74
        return Template::raw(Typogrify::$plugin->typogrify->smartypants($text));
75
    }
76
77
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
78
     * @return Settings
79
     */
80
    public function getPhpTypographySettings(): Settings
81
    {
82
        return Typogrify::$plugin->typogrify->phpTypographySettings;
0 ignored issues
show
Bug Best Practice introduced by
The expression return nystudio107\typog...->phpTypographySettings could return the type null which is incompatible with the type-hinted return PHP_Typography\Settings. Consider adding an additional type-check to rule them out.
Loading history...
83
    }
84
85
    /**
86
     * Truncates the string to a given length. If $substring is provided, and
87
     * truncating occurs, the string is further truncated so that the substring
88
     * may be appended without exceeding the desired length.
89
     *
90
     * @param string|int|float|null $string The string to truncate
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
91
     * @param int $length Desired length of the truncated string
0 ignored issues
show
Coding Style introduced by
Expected 19 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
92
     * @param string $substring The substring to append if it can fit
0 ignored issues
show
Coding Style introduced by
Expected 16 spaces after parameter type; 1 found
Loading history...
93
     *
94
     * @return string with the resulting $str after truncating
95
     */
96
    public function truncate(string|int|float|null $string, int $length, string $substring = '…'): string
97
    {
98
        return Typogrify::$plugin->typogrify->truncate($string, $length, $substring);
99
    }
100
101
    /**
102
     * Truncates the string to a given length, while ensuring that it does not
103
     * split words. If $substring is provided, and truncating occurs, the
104
     * string is further truncated so that the substring may be appended without
105
     * exceeding the desired length.
106
     *
107
     * @param string|int|float|null $string The string to truncate
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
108
     * @param int $length Desired length of the truncated string
0 ignored issues
show
Coding Style introduced by
Expected 19 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
109
     * @param string $substring The substring to append if it can fit
0 ignored issues
show
Coding Style introduced by
Expected 16 spaces after parameter type; 1 found
Loading history...
110
     *
111
     * @return string with the resulting $str after truncating
112
     */
113
    public function truncateOnWord(string|int|float|null $string, int $length, string $substring = '…'): string
114
    {
115
        return Typogrify::$plugin->typogrify->truncateOnWord($string, $length, $substring);
116
    }
117
118
    /**
119
     * Creates a Stringy object and assigns both string and encoding properties
120
     * the supplied values. $string is cast to a string prior to assignment, and if
121
     * $encoding is not specified, it defaults to mb_internal_encoding(). It
122
     * then returns the initialized object. Throws an InvalidArgumentException
123
     * if the first argument is an array or object without a __toString method.
124
     *
125
     * @param string|int|float|null $string The string initialize the Stringy object with
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
126
     * @param null|string $encoding The character encoding
0 ignored issues
show
Coding Style introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
127
     *
128
     * @return Stringy
129
     */
130
    public function stringy(string|int|float|null $string = '', ?string $encoding = null): Stringy
131
    {
132
        return Typogrify::$plugin->typogrify->stringy($string, $encoding);
133
    }
134
135
    /**
136
     * Formats the value in bytes as a size in human readable form for example `12 KB`.
137
     *
138
     * This is the short form of [[asSize]].
139
     *
140
     * If [[sizeFormatBase]] is 1024, [binary prefixes](http://en.wikipedia.org/wiki/Binary_prefix)
141
     * (e.g. kibibyte/KiB, mebibyte/MiB, ...) are used in the formatting result.
142
     *
143
     * @param string|int|float $bytes value in bytes to be formatted.
0 ignored issues
show
Coding Style introduced by
Expected 4 spaces after parameter name; 1 found
Loading history...
144
     * @param int $decimals the number of digits after the decimal point.
0 ignored issues
show
Coding Style introduced by
Expected 14 spaces after parameter type; 1 found
Loading history...
145
     *
146
     * @return string the formatted result.
147
     */
148
    public function humanFileSize(string|int|float $bytes, int $decimals = 1): string
149
    {
150
        return Typogrify::$plugin->typogrify->humanFileSize($bytes, $decimals);
151
    }
152
153
    /**
154
     * Represents the value as duration in human readable format.
155
     *
156
     * @param DateInterval|string|int $value the value to be formatted. Acceptable formats:
157
     *  - [DateInterval object](http://php.net/manual/ru/class.dateinterval.php)
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 39 spaces but found 2
Loading history...
158
     *  - integer - number of seconds. For example: value `131` represents `2 minutes, 11 seconds`
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 39 spaces but found 2
Loading history...
159
     *  - ISO8601 duration format. For example, all of these values represent `1 day, 2 hours, 30 minutes` duration:
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 39 spaces but found 2
Loading history...
160
     *    `2015-01-01T13:00:00Z/2015-01-02T13:30:00Z` - between two datetime values
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 39 spaces but found 4
Loading history...
161
     *    `2015-01-01T13:00:00Z/P1D2H30M` - time interval after datetime value
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 39 spaces but found 4
Loading history...
162
     *    `P1D2H30M/2015-01-02T13:30:00Z` - time interval before datetime value
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 39 spaces but found 4
Loading history...
163
     *    `P1D2H30M` - simply a date interval
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 39 spaces but found 4
Loading history...
164
     *    `P-1D2H30M` - a negative date interval (`-1 day, 2 hours, 30 minutes`)
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 39 spaces but found 4
Loading history...
165
     *
166
     * @return string the formatted duration.
167
     */
168
    public function humanDuration(DateInterval|string|int $value): string
169
    {
170
        return Typogrify::$plugin->typogrify->humanDuration($value);
171
    }
172
173
    /**
174
     * Formats the value as the time interval between a date and now in human readable form.
175
     *
176
     * This method can be used in three different ways:
177
     *
178
     * 1. Using a timestamp that is relative to `now`.
179
     * 2. Using a timestamp that is relative to the `$referenceTime`.
180
     * 3. Using a `DateInterval` object.
181
     *
182
     * @param int|string|DateTime|DateInterval $value the value to be formatted. The following
0 ignored issues
show
Coding Style introduced by
Expected 9 spaces after parameter name; 1 found
Loading history...
183
     * types of value are supported:
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 48 spaces but found 1
Loading history...
184
     *
185
     * - an integer representing a UNIX timestamp
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 48 spaces but found 1
Loading history...
186
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 48 spaces but found 1
Loading history...
187
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 48 spaces but found 3
Loading history...
188
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 48 spaces but found 1
Loading history...
189
     * - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 48 spaces but found 1
Loading history...
190
     *
191
     * @param null|int|string|DateTime $referenceTime if specified the value is used as a reference time instead of `now`
0 ignored issues
show
Coding Style introduced by
Parameter tags must be grouped together in a doc comment
Loading history...
Coding Style introduced by
Expected 9 spaces after parameter type; 1 found
Loading history...
192
     * when `$value` is not a `DateInterval` object.
0 ignored issues
show
Coding Style introduced by
Parameter comment not aligned correctly; expected 48 spaces but found 1
Loading history...
193
     *
194
     * @return string the formatted result.
195
     */
196
    public function humanRelativeTime(int|string|DateTime|DateInterval $value, null|int|string|DateTime $referenceTime = null): string
197
    {
198
        return Typogrify::$plugin->typogrify->humanRelativeTime($value, $referenceTime);
199
    }
200
201
    /**
202
     * Converts number to its ordinal English form
203
     * For example, converts 13 to 13th, 2 to 2nd
204
     *
205
     * @param int $number
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
206
     *
207
     * @return string
208
     */
209
    public function ordinalize(int $number): string
210
    {
211
        return Typogrify::$plugin->typogrify->ordinalize($number);
212
    }
213
214
    /**
215
     * Converts a word to its plural form
216
     * For example, 'apple' will become 'apples', and 'child' will become 'children'
217
     *
218
     * @param string $word
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
219
     * @param int $number
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
220
     *
221
     * @return string
222
     */
223
    public function pluralize(string $word, int $number = 2): string
224
    {
225
        return Typogrify::$plugin->typogrify->pluralize($word, $number);
226
    }
227
228
    /**
229
     * Converts a word to its singular form
230
     * For example, 'apples' will become 'apple', and 'children' will become 'child'
231
     *
232
     * @param string $word
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
233
     * @param int $number
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
234
     *
235
     * @return string
236
     */
237
    public function singularize(string $word, int $number = 1): string
238
    {
239
        return Typogrify::$plugin->typogrify->singularize($word, $number);
240
    }
241
242
    /**
243
     * Returns transliterated version of a string
244
     * For example, 获取到 どちら Українська: ґ,є, Српска: ђ, њ, џ! ¿Español?
245
     * will be transliterated to huo qu dao dochira Ukrainsʹka: g,e, Srpska: d, n, d! ¿Espanol?
246
     *
247
     * @param string $string
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
248
     * @param null $transliterator
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $transliterator is correct as it would always require null to be passed?
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
249
     *
250
     * @return string
251
     */
252
    public function transliterate(string $string, $transliterator = null): string
253
    {
254
        return Typogrify::$plugin->typogrify->transliterate($string, $transliterator);
255
    }
256
257
    /**
258
     * Limits a string by word count. If $substring is provided, and truncating occurs, the
259
     * string is further truncated so that the substring may be appended without
260
     * exceeding the desired length.
261
     *
262
     * @param string $string
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
263
     * @param int $length
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 4 spaces after parameter type; 1 found
Loading history...
264
     * @param string $substring
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
265
     *
266
     * @return string
267
     */
268
    public function wordLimit(string $string, int $length, string $substring = '…'): string
269
    {
270
        return Typogrify::$plugin->typogrify->wordLimit($string, $length, $substring);
271
    }
272
273
    // Private Methods
274
    // =========================================================================
275
276
    /**
277
     * Normalize the passed in text to ensure that untrusted strings are escaped
278
     *
279
     * @param $text
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
280
     *
281
     * @return string
282
     */
283
    private function normalizeText($text): string
0 ignored issues
show
Coding Style introduced by
Private method name "TypogrifyVariable::normalizeText" must be prefixed with an underscore
Loading history...
284
    {
285
        /* @TODO: try to resolve at a later date; Twig's `| raw` just returns a string, not `Markup` so we can't use that as a check
286
         * if ($text instanceof Markup) {
287
         * // Either came from a Redactor field (or the like) or they manually added a |raw tag. We can trust it
288
         * $text = (string)$text;
289
         * } else {
290
         * // We don't trust it, so escape any HTML
291
         * $twig = Craft::$app->view->twig;
292
         * try {
293
         * $text = twig_escape_filter($twig, $text);
294
         * } catch (\Twig_Error_Runtime $e) {
295
         * $error = $e->getMessage();
296
         * Craft::error($error, __METHOD__);
297
         * // We don't want unescaped text slipping through, so set the text to the error message
298
         * $text = $error;
299
         * }
300
         * }
301
         */
302
        // If it's null or otherwise empty, just return an empty string
303
        if (empty($text)) {
304
            $text = '';
305
        }
306
        $text = (string)$text;
307
308
        $settings = Typogrify::$plugin->getSettings();
0 ignored issues
show
Bug introduced by
The method getSettings() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

308
        /** @scrutinizer ignore-call */ 
309
        $settings = Typogrify::$plugin->getSettings();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
309
310
        if ($settings && $settings['default_escape'] === true) {
311
            $twig = Craft::$app->getView()->getTwig();
312
            $twig_escape_filter = $twig->getFilter('e');
313
            if ($twig_escape_filter) {
314
                $text = $twig_escape_filter->getCallable()($twig, $text);
315
            }
316
        }
317
318
        return $text;
319
    }
320
}
321