Passed
Push — v1 ( ac69b6...2a5986 )
by Andrew
08:08 queued 05:31
created

TypogrifyTwigExtension::wordLimit()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 3
dl 0
loc 3
rs 10
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/
8
 * @copyright Copyright (c) 2017 nystudio107
9
 */
10
11
namespace nystudio107\typogrify\twigextensions;
12
13
use nystudio107\typogrify\Typogrify;
14
15
use craft\helpers\Template;
16
17
use Stringy\Stringy;
18
19
/**
20
 * @author    nystudio107
21
 * @package   Typogrify
22
 * @since     1.0.0
23
 */
24
class TypogrifyTwigExtension extends \Twig_Extension
25
{
26
    // Public Methods
27
    // =========================================================================
28
29
    /**
30
     * @inheritdoc
31
     */
32
    public function getName()
33
    {
34
        return 'Typogrify';
35
    }
36
37
    /**
38
     * @inheritdoc
39
     */
40
    public function getFilters()
41
    {
42
        return [
43
            new \Twig_SimpleFilter('typogrify', [$this, 'typogrify']),
44
            new \Twig_SimpleFilter('typogrifyFeed', [$this, 'typogrifyFeed']),
45
            new \Twig_SimpleFilter('smartypants', [$this, 'smartypants']),
46
            new \Twig_SimpleFilter('truncate', [$this, 'truncate']),
47
            new \Twig_SimpleFilter('truncateOnWord', [$this, 'truncateOnWord']),
48
            new \Twig_SimpleFilter('stringy', [$this, 'stringy']),
49
            new \Twig_SimpleFilter('humanFileSize', [$this, 'humanFileSize']),
50
            new \Twig_SimpleFilter('humanDuration', [$this, 'humanDuration']),
51
            new \Twig_SimpleFilter('humanRelativeTime', [$this, 'humanRelativeTime']),
52
            new \Twig_SimpleFilter('ordinalize', [$this, 'ordinalize']),
53
            new \Twig_SimpleFilter('pluralize', [$this, 'pluralize']),
54
            new \Twig_SimpleFilter('singularize', [$this, 'singularize']),
55
            new \Twig_SimpleFilter('transliterate', [$this, 'transliterate']),
56
            new \Twig_SimpleFilter('wordLimit', [$this, 'wordLimit']),
57
        ];
58
    }
59
60
    /**
61
     * @inheritdoc
62
     */
63
    public function getFunctions()
64
    {
65
        return [
66
            new \Twig_SimpleFunction('typogrify', [$this, 'typogrify']),
67
            new \Twig_SimpleFunction('typogrifyFeed', [$this, 'typogrifyFeed']),
68
            new \Twig_SimpleFunction('smartypants', [$this, 'smartypants']),
69
            new \Twig_SimpleFunction('getPhpTypographySettings', [$this, 'getPhpTypographySettings']),
70
            new \Twig_SimpleFunction('truncate', [$this, 'truncate']),
71
            new \Twig_SimpleFunction('truncateOnWord', [$this, 'truncateOnWord']),
72
            new \Twig_SimpleFunction('stringy', [$this, 'stringy']),
73
            new \Twig_SimpleFunction('humanFileSize', [$this, 'humanFileSize']),
74
            new \Twig_SimpleFunction('humanDuration', [$this, 'humanDuration']),
75
            new \Twig_SimpleFunction('humanRelativeTime', [$this, 'humanRelativeTime']),
76
            new \Twig_SimpleFunction('ordinalize', [$this, 'ordinalize']),
77
            new \Twig_SimpleFunction('pluralize', [$this, 'pluralize']),
78
            new \Twig_SimpleFunction('singularize', [$this, 'singularize']),
79
            new \Twig_SimpleFunction('transliterate', [$this, 'transliterate']),
80
            new \Twig_SimpleFunction('wordLimit', [$this, 'wordLimit']),
81
        ];
82
    }
83
84
    /**
85
     * Typogrify applies a veritable kitchen sink of typographic treatments to
86
     * beautify your web typography
87
     *
88
     * @param string $text    The text or HTML fragment to process
89
     * @param bool   $isTitle Optional. If the HTML fragment is a title.
90
     *                        Default false
91
     *
92
     * @return string The processed HTML
93
     */
94
    public function typogrify($text, $isTitle = false)
95
    {
96
        return Template::raw(Typogrify::$plugin->typogrify->typogrify($text, $isTitle));
97
    }
98
99
    /**
100
     * Typogrify applies a veritable kitchen sink of typographic treatments to
101
     * beautify your web typography but in a way that is appropriate for RSS
102
     * (or similar) feeds -- i.e. excluding processes that may cause issues in
103
     * contexts with limited character set intelligence.
104
     *
105
     * @param string $text    The text or HTML fragment to process
106
     * @param bool   $isTitle Optional. If the HTML fragment is a title.
107
     *                        Default false
108
     *
109
     * @return string The processed HTML
110
     */
111
    public function typogrifyFeed($text, $isTitle = false)
112
    {
113
        return Template::raw(Typogrify::$plugin->typogrify->typogrifyFeed($text, $isTitle));
114
    }
115
116
    /**
117
     * @param string $text
118
     *
119
     * @return \Twig_Markup
120
     */
121
    public function smartypants($text)
122
    {
123
        return Template::raw(Typogrify::$plugin->typogrify->smartypants($text));
124
    }
125
126
    /**
127
     * @return \PHP_Typography\Settings
128
     */
129
    public function getPhpTypographySettings()
130
    {
131
        return Typogrify::$plugin->typogrify->phpTypographySettings;
132
    }
133
134
    /**
135
     * Truncates the string to a given length. If $substring is provided, and
136
     * truncating occurs, the string is further truncated so that the substring
137
     * may be appended without exceeding the desired length.
138
     *
139
     * @param  string $string    The string to truncate
140
     * @param  int    $length    Desired length of the truncated string
141
     * @param  string $substring The substring to append if it can fit
142
     *
143
     * @return string with the resulting $str after truncating
144
     */
145
    public function truncate($string, $length, $substring = '…'): string
146
    {
147
        return Template::raw(Typogrify::$plugin->typogrify->truncate($string, $length, $substring));
148
    }
149
150
    /**
151
     * Truncates the string to a given length, while ensuring that it does not
152
     * split words. If $substring is provided, and truncating occurs, the
153
     * string is further truncated so that the substring may be appended without
154
     * exceeding the desired length.
155
     *
156
     * @param  string $string    The string to truncate
157
     * @param  int    $length    Desired length of the truncated string
158
     * @param  string $substring The substring to append if it can fit
159
     *
160
     * @return string with the resulting $str after truncating
161
     */
162
    public function truncateOnWord($string, $length, $substring = '…'): string
163
    {
164
        return Template::raw(Typogrify::$plugin->typogrify->truncateOnWord($string, $length, $substring));
165
    }
166
167
    /**
168
     * Creates a Stringy object and assigns both string and encoding properties
169
     * the supplied values. $string is cast to a string prior to assignment, and if
170
     * $encoding is not specified, it defaults to mb_internal_encoding(). It
171
     * then returns the initialized object. Throws an InvalidArgumentException
172
     * if the first argument is an array or object without a __toString method.
173
     *
174
     * @param  string $string   The string initialize the Stringy object with
175
     * @param  string $encoding The character encoding
176
     *
177
     * @return Stringy
178
     */
179
    public function stringy($string = '', $encoding = null)
180
    {
181
        return Typogrify::$plugin->typogrify->stringy($string, $encoding);
182
    }
183
184
    /**
185
     * Formats the value in bytes as a size in human readable form for example `12 KB`.
186
     *
187
     * This is the short form of [[asSize]].
188
     *
189
     * If [[sizeFormatBase]] is 1024, [binary prefixes](http://en.wikipedia.org/wiki/Binary_prefix)
190
     * (e.g. kibibyte/KiB, mebibyte/MiB, ...) are used in the formatting result.
191
     *
192
     * @param string|int|float $bytes    value in bytes to be formatted.
193
     * @param int              $decimals the number of digits after the decimal point.
194
     *
195
     * @return string the formatted result.
196
     */
197
    public function humanFileSize($bytes, $decimals = 1): string
198
    {
199
        return Template::raw(Typogrify::$plugin->typogrify->humanFileSize($bytes, $decimals));
200
    }
201
202
    /**
203
     * Represents the value as duration in human readable format.
204
     *
205
     * @param \DateInterval|string|int $value the value to be formatted. Acceptable formats:
206
     *  - [DateInterval object](http://php.net/manual/ru/class.dateinterval.php)
207
     *  - integer - number of seconds. For example: value `131` represents `2 minutes, 11 seconds`
208
     *  - ISO8601 duration format. For example, all of these values represent `1 day, 2 hours, 30 minutes` duration:
209
     *    `2015-01-01T13:00:00Z/2015-01-02T13:30:00Z` - between two datetime values
210
     *    `2015-01-01T13:00:00Z/P1D2H30M` - time interval after datetime value
211
     *    `P1D2H30M/2015-01-02T13:30:00Z` - time interval before datetime value
212
     *    `P1D2H30M` - simply a date interval
213
     *    `P-1D2H30M` - a negative date interval (`-1 day, 2 hours, 30 minutes`)
214
     *
215
     * @return string the formatted duration.
216
     */
217
    public function humanDuration($value)
218
    {
219
        return Template::raw(Typogrify::$plugin->typogrify->humanDuration($value));
220
    }
221
222
    /**
223
     * Formats the value as the time interval between a date and now in human readable form.
224
     *
225
     * This method can be used in three different ways:
226
     *
227
     * 1. Using a timestamp that is relative to `now`.
228
     * 2. Using a timestamp that is relative to the `$referenceTime`.
229
     * 3. Using a `DateInterval` object.
230
     *
231
     * @param int|string|\DateTime|\DateInterval $value the value to be formatted. The following
232
     * types of value are supported:
233
     *
234
     * - an integer representing a UNIX timestamp
235
     * - a string that can be [parsed to create a DateTime object](http://php.net/manual/en/datetime.formats.php).
236
     *   The timestamp is assumed to be in [[defaultTimeZone]] unless a time zone is explicitly given.
237
     * - a PHP [DateTime](http://php.net/manual/en/class.datetime.php) object
238
     * - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
239
     *
240
     * @param int|string|\DateTime $referenceTime if specified the value is used as a reference time instead of `now`
241
     * when `$value` is not a `DateInterval` object.
242
     *
243
     * @return string the formatted result.
244
     */
245
    public function humanRelativeTime($value, $referenceTime = null)
246
    {
247
        return Template::raw(Typogrify::$plugin->typogrify->humanRelativeTime($value, $referenceTime));
248
    }
249
250
    /**
251
     * Converts number to its ordinal English form
252
     * For example, converts 13 to 13th, 2 to 2nd
253
     *
254
     * @param int $number
255
     *
256
     * @return \Twig_Markup
257
     */
258
    public function ordinalize(int $number)
259
    {
260
        return Template::raw(Typogrify::$plugin->typogrify->ordinalize($number));
261
    }
262
263
    /**
264
     * Converts a word to its plural form
265
     * For example, 'apple' will become 'apples', and 'child' will become 'children'
266
     *
267
     * @param string $word
268
     * @param int    $number
269
     *
270
     * @return \Twig_Markup
271
     */
272
    public function pluralize(string $word, int $number = 2)
273
    {
274
        return Template::raw(Typogrify::$plugin->typogrify->pluralize($word, $number));
275
    }
276
277
    /**
278
     * Converts a word to its singular form
279
     * For example, 'apples' will become 'apple', and 'children' will become 'child'
280
     *
281
     * @param string $word
282
     * @param int    $number
283
     *
284
     * @return \Twig_Markup
285
     */
286
    public function singularize(string $word, int $number = 1)
287
    {
288
        return Template::raw(Typogrify::$plugin->typogrify->singularize($word, $number));
289
    }
290
291
    /**
292
     * Returns transliterated version of a string
293
     * For example, 获取到 どちら Українська: ґ,є, Српска: ђ, њ, џ! ¿Español?
294
     * will be transliterated to huo qu dao dochira Ukrainsʹka: g,e, Srpska: d, n, d! ¿Espanol?
295
     *
296
     * @param string $string
297
     * @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...
298
     *
299
     * @return \Twig_Markup
300
     */
301
    public function transliterate(string $string, $transliterator = null)
302
    {
303
        return Template::raw(Typogrify::$plugin->typogrify->transliterate($string, $transliterator));
304
    }
305
306
    /**
307
     * Limits a string by word count. If $substring is provided, and truncating occurs, the
308
     * string is further truncated so that the substring may be appended without
309
     * exceeding the desired length.
310
     *
311
     * @param string $string
312
     * @param int    $length
313
     * @param string $substring
314
     *
315
     * @return string
316
     */
317
    public function wordLimit(string $string, int $length, string $substring = '…')
318
    {
319
        return Template::raw(Typogrify::$plugin->typogrify->wordLimit($string, $length, $substring));
320
    }
321
}
322