Passed
Push — v1 ( 0163c8...a30b6b )
by Andrew
07:16 queued 04:25
created

TypogrifyVariable::normalizeText()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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