Scrutinizer GitHub App not installed

We could not synchronize checks via GitHub's checks API since Scrutinizer's GitHub App is not installed for this repository.

Install GitHub App

GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 1bf084...af5a56 )
by Der Mundschenk
16s
created

Settings::remap_character()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 11
ccs 6
cts 6
cp 1
rs 10
cc 3
nc 4
nop 2
crap 3
1
<?php
2
/**
3
 *  This file is part of PHP-Typography.
4
 *
5
 *  Copyright 2014-2019 Peter Putzer.
6
 *  Copyright 2009-2011 KINGdesk, LLC.
7
 *
8
 *  This program is free software; you can redistribute it and/or modify
9
 *  it under the terms of the GNU General Public License as published by
10
 *  the Free Software Foundation; either version 2 of the License, or
11
 *  (at your option) any later version.
12
 *
13
 *  This program is distributed in the hope that it will be useful,
14
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 *  GNU General Public License for more details.
17
 *
18
 *  You should have received a copy of the GNU General Public License along
19
 *  with this program; if not, write to the Free Software Foundation, Inc.,
20
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21
 *
22
 *  ***
23
 *
24
 *  @package mundschenk-at/php-typography
25
 *  @license http://www.gnu.org/licenses/gpl-2.0.html
26
 */
27
28
namespace PHP_Typography;
29
30
use PHP_Typography\Settings\Dash_Style;
31
use PHP_Typography\Settings\Quote_Style;
32
use PHP_Typography\Settings\Quotes;
33
34
/**
35
 * Store settings for the PHP_Typography class.
36
 *
37
 * @author Peter Putzer <[email protected]>
38
 *
39
 * @since 4.0.0
40
 * @since 6.5.0 The protected property $no_break_narrow_space has been deprecated.
41
 */
42
class Settings implements \ArrayAccess, \JsonSerializable {
43
44
	/**
45
	 * The current no-break narrow space character.
46
	 *
47
	 * @deprecated 6.5.0
48
	 *
49
	 * @var string
50
	 */
51
	protected $no_break_narrow_space;
52
53
	/**
54
	 * Primary quote style.
55
	 *
56
	 * @var Quotes
57
	 */
58
	protected $primary_quote_style;
59
60
	/**
61
	 * Secondary quote style.
62
	 *
63
	 * @var Quotes
64
	 */
65
	protected $secondary_quote_style;
66
67
	/**
68
	 * A regex pattern for custom units (or the empty string).
69
	 *
70
	 * @var string
71
	 */
72
	protected $custom_units = '';
73
74
	/**
75
	 * A hashmap of settings for the various typographic options.
76
	 *
77
	 * @var array
78
	 */
79
	protected $data = [];
80
81
	/**
82
	 * The current dash style.
83
	 *
84
	 * @var Settings\Dashes
85
	 */
86
	protected $dash_style;
87
88
	/**
89
	 * The Unicode character mapping (some characters still have compatibility issues).
90
	 *
91
	 * @since 6.5.0
92
	 *
93
	 * @var string[]
94
	 */
95
	protected $unicode_mapping;
96
97
	/**
98
	 * An array containing just remapped characters (for optimization).
99
	 *
100
	 * @since 6.5.0
101
	 *
102
	 * @var string[]
103
	 */
104
	protected $remapped_characters;
105
106
	/**
107
	 * Sets up a new Settings object.
108
	 *
109
	 * @since 6.0.0 If $set_defaults is `false`, the settings object is not fully
110
	 *              initialized unless `set_smart_quotes_primary`,
111
	 *              `set_smart_quotes_secondary`, `set_smart_dashes_style` and
112
	 *              `set_true_no_break_narrow_space` are called explicitly.
113
	 * @since 6.5.0 A (partial) character mapping can be given to remap certain
114
	 *              characters.
115
	 *
116
	 * @param bool     $set_defaults Optional. If true, set default values for various properties. Default true.
117
	 * @param string[] $mapping      Optional. Unicode characters to remap. The default maps the narrow no-break space to the normal NO-BREAK SPACE and the apostrophe to the RIGHT SINGLE QUOTATION MARK.
118
	 */
119 1
	public function __construct( $set_defaults = true, array $mapping = [ U::NO_BREAK_NARROW_SPACE => U::NO_BREAK_SPACE, U::APOSTROPHE => U::SINGLE_QUOTE_CLOSE ] ) { // phpcs:ignore WordPress.Arrays.ArrayDeclarationSpacing
120 1
		if ( $set_defaults ) {
121 1
			$this->set_defaults();
122
		}
123
124
		// Merge default character mapping with given mapping.
125 1
		$this->unicode_mapping = $mapping;
126
127
		// Keep backwards compatibility.
128 1
		if ( isset( $this->unicode_mapping[ U::NO_BREAK_NARROW_SPACE ] ) ) {
129
			/* @scrutinizer ignore-deprecated */
130 1
			$this->no_break_narrow_space = $this->unicode_mapping[ U::NO_BREAK_NARROW_SPACE ];
131
		}
132 1
	}
133
134
	/**
135
	 * Provides access to named settings (object syntax).
136
	 *
137
	 * @param string $key The settings key.
138
	 *
139
	 * @return mixed
140
	 */
141 1
	public function &__get( $key ) {
142 1
		return $this->data[ $key ];
143
	}
144
145
	/**
146
	 * Changes a named setting (object syntax).
147
	 *
148
	 * @param string $key   The settings key.
149
	 * @param mixed  $value The settings value.
150
	 */
151 1
	public function __set( $key, $value ) {
152 1
		$this->data[ $key ] = $value;
153 1
	}
154
155
	/**
156
	 * Checks if a named setting exists (object syntax).
157
	 *
158
	 * @param string $key The settings key.
159
	 */
160 1
	public function __isset( $key ) {
161 1
		return isset( $this->data[ $key ] );
162
	}
163
164
	/**
165
	 * Unsets a named setting.
166
	 *
167
	 * @param string $key The settings key.
168
	 */
169 1
	public function __unset( $key ) {
170 1
		unset( $this->data[ $key ] );
171 1
	}
172
173
	/**
174
	 * Changes a named setting (array syntax).
175
	 *
176
	 * @param string $offset The settings key.
177
	 * @param mixed  $value  The settings value.
178
	 */
179 1
	public function offsetSet( $offset, $value ) {
180 1
		if ( ! empty( $offset ) ) {
181 1
			$this->data[ $offset ] = $value;
182
		}
183 1
	}
184
185
	/**
186
	 * Checks if a named setting exists (array syntax).
187
	 *
188
	 * @param string $offset The settings key.
189
	 */
190 1
	public function offsetExists( $offset ) {
191 1
		return isset( $this->data[ $offset ] );
192
	}
193
194
	/**
195
	 * Unsets a named setting (array syntax).
196
	 *
197
	 * @param string $offset The settings key.
198
	 */
199 1
	public function offsetUnset( $offset ) {
200 1
		unset( $this->data[ $offset ] );
201 1
	}
202
203
	/**
204
	 * Provides access to named settings (array syntax).
205
	 *
206
	 * @param string $offset The settings key.
207
	 *
208
	 * @return mixed
209
	 */
210 1
	public function offsetGet( $offset ) {
211 1
		return isset( $this->data[ $offset ] ) ? $this->data[ $offset ] : null;
212
	}
213
214
	/**
215
	 * Provides a JSON serialization of the settings.
216
	 *
217
	 * @return mixed
218
	 */
219 1
	public function jsonSerialize() {
220 1
		return \array_merge(
221 1
			$this->data,
222
			[
223 1
				'unicode_mapping'       => $this->unicode_mapping,
224 1
				'primary_quotes'        => "{$this->primary_quote_style->open()}|{$this->primary_quote_style->close()}",
225 1
				'secondary_quotes'      => "{$this->secondary_quote_style->open()}|{$this->secondary_quote_style->close()}",
226 1
				'dash_style'            => "{$this->dash_style->interval_dash()}|{$this->dash_style->interval_space()}|{$this->dash_style->parenthetical_dash()}|{$this->dash_style->parenthetical_space()}",
227 1
				'custom_units'          => $this->custom_units,
228
			]
229
		);
230
	}
231
232
	/**
233
	 * Remaps a unicode character to another one.
234
	 *
235
	 * @since 6.5.0
236
	 *
237
	 * @param  string $char     The remapped character.
238
	 * @param  string $new_char The character to actually use.
239
	 */
240 1
	public function remap_character( $char, $new_char ) {
241 1
		if ( $char !== $new_char ) {
242 1
			$this->unicode_mapping[ $char ] = $new_char;
243
		} else {
244 1
			unset( $this->unicode_mapping[ $char ] );
245
		}
246
247
		// Compatibility with the old way of setting the no-break narrow space.
248 1
		if ( U::NO_BREAK_NARROW_SPACE === $char ) {
249
			/* @scrutinizer ignore-deprecated */
250 1
			$this->no_break_narrow_space = $new_char;
251
		}
252 1
	}
253
254
	/**
255
	 * Remaps one or more strings.
256
	 *
257
	 * @since 6.5.0
258
	 *
259
	 * @param  string|string[] $input The input string(s).
260
	 *
261
	 * @return string|string[]
262
	 */
263 4
	public function apply_character_mapping( $input ) {
264
265
		// Nothing for us to do.
266 4
		if ( empty( $input ) || empty( $this->unicode_mapping ) ) {
267 1
			return $input;
268
		}
269
270 3
		$native_array = \is_array( $input );
271 3
		$data         = (array) $input;
272
273 3
		foreach ( $data as $key => $string ) {
274 3
			$data[ $key ] = \strtr( $string, $this->unicode_mapping );
275
		}
276
277 3
		return $native_array ? $data : $data[0];
278
	}
279
280
	/**
281
	 * Retrieves the current non-breaking narrow space character (either the
282
	 * regular non-breaking space &nbsp; or the the true non-breaking narrow space &#8239;).
283
	 *
284
	 * @deprecated 6.5.0 Use U::NO_BREAK_NARROW_SPACE instead and let Settings::apply_character_mapping() do the rest.
285
	 *
286
	 * @return string
287
	 */
288 1
	public function no_break_narrow_space() {
289 1
		return /* @scrutinizer ignore-deprecated */$this->no_break_narrow_space;
290
	}
291
292
	/**
293
	 * Retrieves the primary (double) quote style.
294
	 *
295
	 * @return Quotes
296
	 */
297 1
	public function primary_quote_style() {
298 1
		return $this->primary_quote_style;
299
	}
300
301
	/**
302
	 * Retrieves the secondary (single) quote style.
303
	 *
304
	 * @return Quotes
305
	 */
306 1
	public function secondary_quote_style() {
307 1
		return $this->secondary_quote_style;
308
	}
309
310
	/**
311
	 * Retrieves the dash style.
312
	 *
313
	 * @return Settings\Dashes
314
	 */
315 1
	public function dash_style() {
316 1
		return $this->dash_style;
317
	}
318
319
	/**
320
	 * Retrieves the custom units pattern.
321
	 *
322
	 * @return string The pattern is suitable for inclusion into a regular expression.
323
	 */
324 1
	public function custom_units() {
325 1
		return $this->custom_units;
326
	}
327
328
	/**
329
	 * (Re)set various options to their default values.
330
	 */
331 1
	public function set_defaults() {
332
		// General attributes.
333 1
		$this->set_tags_to_ignore();
334 1
		$this->set_classes_to_ignore();
335 1
		$this->set_ids_to_ignore();
336
337
		// Smart characters.
338 1
		$this->set_smart_quotes();
339 1
		$this->set_smart_quotes_primary();
340 1
		$this->set_smart_quotes_secondary();
341 1
		$this->set_smart_quotes_exceptions();
342 1
		$this->set_smart_dashes();
343 1
		$this->set_smart_dashes_style();
344 1
		$this->set_smart_ellipses();
345 1
		$this->set_smart_diacritics();
346 1
		$this->set_diacritic_language();
347 1
		$this->set_diacritic_custom_replacements();
348 1
		$this->set_smart_marks();
349 1
		$this->set_smart_ordinal_suffix();
350 1
		$this->set_smart_ordinal_suffix_match_roman_numerals();
351 1
		$this->set_smart_math();
352 1
		$this->set_smart_fractions();
353 1
		$this->set_smart_exponents();
354 1
		$this->set_smart_area_units();
355
356
		// Smart spacing.
357 1
		$this->set_single_character_word_spacing();
358 1
		$this->set_fraction_spacing();
359 1
		$this->set_unit_spacing();
360 1
		$this->set_french_punctuation_spacing();
361 1
		$this->set_units();
362 1
		$this->set_dash_spacing();
363 1
		$this->set_dewidow();
364 1
		$this->set_max_dewidow_length();
365 1
		$this->set_max_dewidow_pull();
366 1
		$this->set_dewidow_word_number();
367 1
		$this->set_wrap_hard_hyphens();
368 1
		$this->set_url_wrap();
369 1
		$this->set_email_wrap();
370 1
		$this->set_min_after_url_wrap();
371 1
		$this->set_space_collapse();
372
		/* @scrutinizer ignore-deprecated */
373 1
		$this->set_true_no_break_narrow_space();
374
375
		// Character styling.
376 1
		$this->set_style_ampersands();
377 1
		$this->set_style_caps();
378 1
		$this->set_style_initial_quotes();
379 1
		$this->set_style_numbers();
380 1
		$this->set_style_hanging_punctuation();
381 1
		$this->set_initial_quote_tags();
382
383
		// Hyphenation.
384 1
		$this->set_hyphenation();
385 1
		$this->set_hyphenation_language();
386 1
		$this->set_min_length_hyphenation();
387 1
		$this->set_min_before_hyphenation();
388 1
		$this->set_min_after_hyphenation();
389 1
		$this->set_hyphenate_headings();
390 1
		$this->set_hyphenate_all_caps();
391 1
		$this->set_hyphenate_title_case();
392 1
		$this->set_hyphenate_compounds();
393 1
		$this->set_hyphenation_exceptions();
394
395
		// Parser error handling.
396 1
		$this->set_ignore_parser_errors();
397 1
	}
398
399
	/**
400
	 * Enable lenient parser error handling (HTML is "best guess" if enabled).
401
	 *
402
	 * @param bool $on Optional. Default false.
403
	 */
404 1
	public function set_ignore_parser_errors( $on = false ) {
405 1
		$this->data['parserErrorsIgnore'] = $on;
406 1
	}
407
408
	/**
409
	 * Sets an optional handler for parser errors. Invalid callbacks will be silently ignored.
410
	 *
411
	 * @since 6.0.0. callable type is enforced via typehinting.
412
	 *
413
	 * @param callable|null $handler Optional. A callable that takes an array of error strings as its parameter. Default null.
414
	 */
415 2
	public function set_parser_errors_handler( callable $handler = null ) {
416 2
		$this->data['parserErrorsHandler'] = $handler;
417 2
	}
418
419
	/**
420
	 * Enable usage of true "no-break narrow space" (&#8239;) instead of the normal no-break space (&nbsp;).
421
	 *
422
	 * @deprecated 6.5.0 Use ::remap_character() instead.
423
	 *
424
	 * @param bool $on Optional. Default false.
425
	 */
426 1
	public function set_true_no_break_narrow_space( $on = false ) {
427
428 1
		if ( $on ) {
429 1
			$this->remap_character( U::NO_BREAK_NARROW_SPACE, U::NO_BREAK_NARROW_SPACE );
430
		} else {
431 1
			$this->remap_character( U::NO_BREAK_NARROW_SPACE, U::NO_BREAK_SPACE );
432
		}
433 1
	}
434
435
	/**
436
	 * Sets tags for which the typography of their children will be left untouched.
437
	 *
438
	 * @param string|array $tags A comma separated list or an array of tag names.
439
	 */
440 1
	public function set_tags_to_ignore( $tags = [ 'code', 'head', 'kbd', 'object', 'option', 'pre', 'samp', 'script', 'noscript', 'noembed', 'select', 'style', 'textarea', 'title', 'var', 'math' ] ) {
441
		// Ensure that we pass only lower-case tag names to XPath.
442 1
		$tags = array_filter( array_map( 'strtolower', Strings::maybe_split_parameters( $tags ) ), 'ctype_alnum' );
443
444 1
		$this->data['ignoreTags'] = array_unique( array_merge( $tags, array_flip( DOM::inappropriate_tags() ) ) );
445 1
	}
446
447
	/**
448
	 * Sets classes for which the typography of their children will be left untouched.
449
	 *
450
	 * @param string|array $classes A comma separated list or an array of class names.
451
	 */
452 1
	public function set_classes_to_ignore( $classes = [ 'vcard', 'noTypo' ] ) {
453 1
		$this->data['ignoreClasses'] = Strings::maybe_split_parameters( $classes );
454 1
	}
455
456
	/**
457
	 * Sets IDs for which the typography of their children will be left untouched.
458
	 *
459
	 * @param string|array $ids A comma separated list or an array of tag names.
460
	 */
461 1
	public function set_ids_to_ignore( $ids = [] ) {
462 1
		$this->data['ignoreIDs'] = Strings::maybe_split_parameters( $ids );
463 1
	}
464
465
	/**
466
	 * Enables/disables typographic quotes.
467
	 *
468
	 * @param bool $on Optional. Default true.
469
	 */
470 1
	public function set_smart_quotes( $on = true ) {
471 1
		$this->data['smartQuotes'] = $on;
472 1
	}
473
474
	/**
475
	 * Sets the style for primary ('double') quotemarks.
476
	 *
477
	 * Allowed values for $style:
478
	 * "doubleCurled" => "&ldquo;foo&rdquo;",
479
	 * "doubleCurledReversed" => "&rdquo;foo&rdquo;",
480
	 * "doubleLow9" => "&bdquo;foo&rdquo;",
481
	 * "doubleLow9Reversed" => "&bdquo;foo&ldquo;",
482
	 * "singleCurled" => "&lsquo;foo&rsquo;",
483
	 * "singleCurledReversed" => "&rsquo;foo&rsquo;",
484
	 * "singleLow9" => "&sbquo;foo&rsquo;",
485
	 * "singleLow9Reversed" => "&sbquo;foo&lsquo;",
486
	 * "doubleGuillemetsFrench" => "&laquo;&nbsp;foo&nbsp;&raquo;",
487
	 * "doubleGuillemets" => "&laquo;foo&raquo;",
488
	 * "doubleGuillemetsReversed" => "&raquo;foo&laquo;",
489
	 * "singleGuillemets" => "&lsaquo;foo&rsaquo;",
490
	 * "singleGuillemetsReversed" => "&rsaquo;foo&lsaquo;",
491
	 * "cornerBrackets" => "&#x300c;foo&#x300d;",
492
	 * "whiteCornerBracket" => "&#x300e;foo&#x300f;"
493
	 *
494
	 * @param  Quotes|string $style Optional. A Quotes instance or a quote style constant. Defaults to 'doubleCurled'.
495
	 *
496
	 * @throws \DomainException Thrown if $style constant is invalid.
497
	 */
498 3
	public function set_smart_quotes_primary( $style = Quote_Style::DOUBLE_CURLED ) {
499 3
		$this->primary_quote_style = $this->get_quote_style( $style );
500 2
	}
501
502
	/**
503
	 * Sets the style for secondary ('single') quotemarks.
504
	 *
505
	 * Allowed values for $style:
506
	 * "doubleCurled" => "&ldquo;foo&rdquo;",
507
	 * "doubleCurledReversed" => "&rdquo;foo&rdquo;",
508
	 * "doubleLow9" => "&bdquo;foo&rdquo;",
509
	 * "doubleLow9Reversed" => "&bdquo;foo&ldquo;",
510
	 * "singleCurled" => "&lsquo;foo&rsquo;",
511
	 * "singleCurledReversed" => "&rsquo;foo&rsquo;",
512
	 * "singleLow9" => "&sbquo;foo&rsquo;",
513
	 * "singleLow9Reversed" => "&sbquo;foo&lsquo;",
514
	 * "doubleGuillemetsFrench" => "&laquo;&nbsp;foo&nbsp;&raquo;",
515
	 * "doubleGuillemets" => "&laquo;foo&raquo;",
516
	 * "doubleGuillemetsReversed" => "&raquo;foo&laquo;",
517
	 * "singleGuillemets" => "&lsaquo;foo&rsaquo;",
518
	 * "singleGuillemetsReversed" => "&rsaquo;foo&lsaquo;",
519
	 * "cornerBrackets" => "&#x300c;foo&#x300d;",
520
	 * "whiteCornerBracket" => "&#x300e;foo&#x300f;"
521
	 *
522
	 * @param  Quotes|string $style Optional. A Quotes instance or a quote style constant. Defaults to 'singleCurled'.
523
	 *
524
	 * @throws \DomainException Thrown if $style constant is invalid.
525
	 */
526 3
	public function set_smart_quotes_secondary( $style = Quote_Style::SINGLE_CURLED ) {
527 3
		$this->secondary_quote_style = $this->get_quote_style( $style );
528 2
	}
529
530
	/**
531
	 * Retrieves a Quotes instance from a given style.
532
	 *
533
	 * @param  Quotes|string $style A Quotes instance or a quote style constant.
534
	 *
535
	 * @throws \DomainException Thrown if $style constant is invalid.
536
	 *
537
	 * @return Quotes
538
	 */
539 6
	protected function get_quote_style( $style ) {
540 6
		return $this->get_style( $style, Quotes::class, [ Quote_Style::class, 'get_styled_quotes' ], 'quote' );
541
	}
542
543
	/**
544
	 * Sets the list of exceptional words for smart quotes replacement. Mainly,
545
	 * this is used for contractions beginning with an apostrophe.
546
	 *
547
	 * @param string[] $exceptions Optional. An array of replacements indexed by the ”non-smart" form.
548
	 *                             Default a list of English words beginning with an apostrophy.
549
	 */
550 1
	public function set_smart_quotes_exceptions( $exceptions = [
551
		"'tain't"   => U::APOSTROPHE . 'tain' . U::APOSTROPHE . 't',
552
		"'twere"    => U::APOSTROPHE . 'twere',
553
		"'twas"     => U::APOSTROPHE . 'twas',
554
		"'tis"      => U::APOSTROPHE . 'tis',
555
		"'til"      => U::APOSTROPHE . 'til',
556
		"'bout"     => U::APOSTROPHE . 'bout',
557
		"'nuff"     => U::APOSTROPHE . 'nuff',
558
		"'round"    => U::APOSTROPHE . 'round',
559
		"'cause"    => U::APOSTROPHE . 'cause',
560
		"'splainin" => U::APOSTROPHE . 'splainin',
561
		"'em'"      => U::APOSTROPHE . 'em',
562
	] ) {
563 1
		$this->data['smartQuotesExceptions'] = [
564 1
			'patterns'     => \array_keys( $exceptions ),
565 1
			'replacements' => \array_values( $exceptions ),
566
		];
567 1
	}
568
569
	/**
570
	 * Retrieves an object from a given style.
571
	 *
572
	 * @param  object|string $style          A style object instance or a style constant.
573
	 * @param  string        $expected_class A class name.
574
	 * @param  callable      $get_style      A function that returns a style object from a given style constant.
575
	 * @param  string        $description    Style description for the exception message.
576
	 *
577
	 * @throws \DomainException Thrown if $style constant is invalid.
578
	 *
579
	 * @return object An instance of $expected_class.
580
	 */
581 9
	protected function get_style( $style, $expected_class, callable $get_style, $description ) {
582 9
		if ( $style instanceof $expected_class ) {
583 3
			$object = $style;
584
		} else {
585 6
			$object = $get_style( $style, $this );
586
		}
587
588 9
		if ( ! \is_object( $object ) || ! $object instanceof $expected_class ) {
589 3
			throw new \DomainException( "Invalid $description style $style." );
590
		}
591
592 6
		return $object;
593
	}
594
595
	/**
596
	 * Enables/disables replacement of "a--a" with En Dash " -- " and "---" with Em Dash.
597
	 *
598
	 * @param bool $on Optional. Default true.
599
	 */
600 1
	public function set_smart_dashes( $on = true ) {
601 1
		$this->data['smartDashes'] = $on;
602 1
	}
603
604
	/**
605
	 * Sets the typographical conventions used by smart_dashes.
606
	 *
607
	 * Allowed values for $style:
608
	 * - "traditionalUS"
609
	 * - "international"
610
	 *
611
	 * @param string|Settings\Dashes $style Optional. Default Dash_Style::TRADITIONAL_US.
612
	 *
613
	 * @throws \DomainException Thrown if $style constant is invalid.
614
	 */
615 3
	public function set_smart_dashes_style( $style = Dash_Style::TRADITIONAL_US ) {
616 3
		$this->dash_style = $this->get_style( $style, Settings\Dashes::class, [ Dash_Style::class, 'get_styled_dashes' ], 'dash' );
617 2
	}
618
619
	/**
620
	 * Enables/disables replacement of "..." with "…".
621
	 *
622
	 * @param bool $on Optional. Default true.
623
	 */
624 1
	public function set_smart_ellipses( $on = true ) {
625 1
		$this->data['smartEllipses'] = $on;
626 1
	}
627
628
	/**
629
	 * Enables/disables replacement "creme brulee" with "crème brûlée".
630
	 *
631
	 * @param bool $on Optional. Default true.
632
	 */
633 1
	public function set_smart_diacritics( $on = true ) {
634 1
		$this->data['smartDiacritics'] = $on;
635 1
	}
636
637
	/**
638
	 * Sets the language used for diacritics replacements.
639
	 *
640
	 * @param string $lang Has to correspond to a filename in 'diacritics'. Optional. Default 'en-US'.
641
	 */
642 1
	public function set_diacritic_language( $lang = 'en-US' ) {
643 1
		if ( isset( $this->data['diacriticLanguage'] ) && $this->data['diacriticLanguage'] === $lang ) {
644 1
			return;
645
		}
646
647 1
		$this->data['diacriticLanguage'] = $lang;
648 1
		$language_file_name              = \dirname( __FILE__ ) . '/diacritics/' . $lang . '.json';
649
650 1
		if ( \file_exists( $language_file_name ) ) {
651 1
			$diacritics_file              = \json_decode( \file_get_contents( $language_file_name ), true );
652 1
			$this->data['diacriticWords'] = $diacritics_file['diacritic_words'];
653
		} else {
654 1
			unset( $this->data['diacriticWords'] );
655
		}
656
657 1
		$this->update_diacritics_replacement_arrays();
658 1
	}
659
660
	/**
661
	 * Sets up custom diacritics replacements.
662
	 *
663
	 * @param string|array $custom_replacements An array formatted [needle=>replacement, needle=>replacement...],
664
	 *                                          or a string formatted `"needle"=>"replacement","needle"=>"replacement",...
665
	 */
666 6
	public function set_diacritic_custom_replacements( $custom_replacements = [] ) {
667 6
		if ( ! \is_array( $custom_replacements ) ) {
668 3
			$custom_replacements = $this->parse_diacritics_replacement_string( $custom_replacements );
669
		}
670
671 6
		$this->data['diacriticCustomReplacements'] = self::array_map_assoc(
672
			function( $key, $replacement ) {
673 5
				$key         = \strip_tags( \trim( $key ) );
674 5
				$replacement = \strip_tags( \trim( $replacement ) );
675
676 5
				if ( ! empty( $key ) && ! empty( $replacement ) ) {
677 3
					return [ $key => $replacement ];
678
				} else {
679 2
					return [];
680
				}
681 6
			},
682
			$custom_replacements
683
		);
684
685 6
		$this->update_diacritics_replacement_arrays();
686 6
	}
687
688
	/**
689
	 * Parses a custom diacritics replacement string into an array.
690
	 *
691
	 * @param string $custom_replacements A string formatted `"needle"=>"replacement","needle"=>"replacement",...
692
	 *
693
	 * @return array
694
	 */
695 3
	private function parse_diacritics_replacement_string( $custom_replacements ) {
696 3
		return self::array_map_assoc(
697
			function( $key, $replacement ) {
698
				// Account for single and double quotes in keys in and values, discard everything else.
699 3
				if ( \preg_match( '/(?<kquo>"|\')(?<key>(?:(?!\k<kquo>).)+)\k<kquo>\s*=>\s*(?<rquo>"|\')(?<replacement>(?:(?!\k<rquo>).)+)\k<rquo>/', $replacement, $match ) ) {
700 2
					$key         = $match['key'];
701 2
					$replacement = $match['replacement'];
702
703 2
					return [ $key => $replacement ];
704
				}
705
706 1
				return [];
707 3
			},
708
			/** RE correct. @scrutinizer ignore-type */
709 3
			\preg_split( '/,/', $custom_replacements, -1, PREG_SPLIT_NO_EMPTY )
710
		);
711
	}
712
713
	/**
714
	 * Provides an array_map implementation with control over resulting array's keys.
715
	 *
716
	 * Based on https://gist.github.com/jasand-pereza/84ecec7907f003564584.
717
	 *
718
	 * @since 6.0.0
719
	 *
720
	 * @param  callable $callback A callback function that needs to return [ $key => $value ] pairs.
721
	 * @param  array    $array    The array.
722
	 *
723
	 * @return array
724
	 */
725 2
	protected static function array_map_assoc( callable $callback, array $array ) {
726 2
		$new = [];
727
728 2
		foreach ( $array as $k => $v ) {
729 2
			$u = $callback( $k, $v );
730
731 2
			if ( ! empty( $u ) ) {
732 1
				$new[ \key( $u ) ] = \current( $u );
733
			}
734
		}
735
736 2
		return $new;
737
	}
738
739
	/**
740
	 * Update the pattern and replacement arrays in $settings['diacriticReplacement'].
741
	 *
742
	 * Should be called whenever a new diacritics replacement language is selected or
743
	 * when the custom replacements are updated.
744
	 */
745 7
	private function update_diacritics_replacement_arrays() {
746 7
		$patterns     = [];
747 7
		$replacements = [];
748
749 7
		if ( ! empty( $this->data['diacriticCustomReplacements'] ) ) {
750 3
			$this->parse_diacritics_rules( $this->data['diacriticCustomReplacements'], $patterns, $replacements );
751
		}
752 7
		if ( ! empty( $this->data['diacriticWords'] ) ) {
753 1
			$this->parse_diacritics_rules( $this->data['diacriticWords'], $patterns, $replacements );
754
		}
755
756 7
		$this->data['diacriticReplacement'] = [
757 7
			'patterns'     => $patterns,
758 7
			'replacements' => $replacements,
759
		];
760 7
	}
761
762
	/**
763
	 * Parse an array of diacritics rules.
764
	 *
765
	 * @param array $diacritics_rules The rules ( $word => $replacement ).
766
	 * @param array $patterns         Resulting patterns. Passed by reference.
767
	 * @param array $replacements     Resulting replacements. Passed by reference.
768
	 */
769 4
	private function parse_diacritics_rules( array $diacritics_rules, array &$patterns, array &$replacements ) {
770
771 4
		foreach ( $diacritics_rules as $needle => $replacement ) {
772 4
			$patterns[]              = '/\b(?<!\w[' . U::NO_BREAK_SPACE . U::SOFT_HYPHEN . '])' . $needle . '\b(?![' . U::NO_BREAK_SPACE . U::SOFT_HYPHEN . ']\w)/u';
773 4
			$replacements[ $needle ] = $replacement;
774
		}
775 4
	}
776
777
	/**
778
	 * Enables/disables replacement of (r) (c) (tm) (sm) (p) (R) (C) (TM) (SM) (P) with ® © ™ ℠ ℗.
779
	 *
780
	 * @param bool $on Optional. Default true.
781
	 */
782 1
	public function set_smart_marks( $on = true ) {
783 1
		$this->data['smartMarks'] = $on;
784 1
	}
785
786
	/**
787
	 * Enables/disables proper mathematical symbols.
788
	 *
789
	 * @param bool $on Optional. Default true.
790
	 */
791 1
	public function set_smart_math( $on = true ) {
792 1
		$this->data['smartMath'] = $on;
793 1
	}
794
795
	/**
796
	 * Enables/disables replacement of 2^2 with 2<sup>2</sup>
797
	 *
798
	 * @param bool $on Optional. Default true.
799
	 */
800 1
	public function set_smart_exponents( $on = true ) {
801 1
		$this->data['smartExponents'] = $on;
802 1
	}
803
804
	/**
805
	 * Enables/disables replacement of 1/4 with <sup>1</sup>&#8260;<sub>4</sub>.
806
	 *
807
	 * @param bool $on Optional. Default true.
808
	 */
809 1
	public function set_smart_fractions( $on = true ) {
810 1
		$this->data['smartFractions'] = $on;
811 1
	}
812
813
	/**
814
	 * Enables/disables replacement of 1st with 1<sup>st</sup>.
815
	 *
816
	 * @param bool $on Optional. Default true.
817
	 */
818 1
	public function set_smart_ordinal_suffix( $on = true ) {
819 1
		$this->data['smartOrdinalSuffix'] = $on;
820 1
	}
821
822
	/**
823
	 * Enables/disables replacement of XXe with XX<sup>e</sup>.
824
	 *
825
	 * @since 6.5.0
826
	 *
827
	 * @param bool $on Optional. Default false.
828
	 */
829 1
	public function set_smart_ordinal_suffix_match_roman_numerals( $on = false ) {
830 1
		$this->data['smartOrdinalSuffixRomanNumerals'] = $on;
831 1
	}
832
833
	/**
834
	 * Enables/disables replacement of m2 with m³ and m3 with m³.
835
	 *
836
	 * @param bool $on Optional. Default true.
837
	 */
838 1
	public function set_smart_area_units( $on = true ) {
839 1
		$this->data['smartAreaVolumeUnits'] = $on;
840 1
	}
841
842
	/**
843
	 * Enables/disables forcing single character words to next line with the insertion of &nbsp;.
844
	 *
845
	 * @param bool $on Optional. Default true.
846
	 */
847 1
	public function set_single_character_word_spacing( $on = true ) {
848 1
		$this->data['singleCharacterWordSpacing'] = $on;
849 1
	}
850
851
	/**
852
	 * Enables/disables fraction spacing.
853
	 *
854
	 * @param bool $on Optional. Default true.
855
	 */
856 1
	public function set_fraction_spacing( $on = true ) {
857 1
		$this->data['fractionSpacing'] = $on;
858 1
	}
859
860
	/**
861
	 * Enables/disables keeping units and values together with the insertion of &nbsp;.
862
	 *
863
	 * @param bool $on Optional. Default true.
864
	 */
865 1
	public function set_unit_spacing( $on = true ) {
866 1
		$this->data['unitSpacing'] = $on;
867 1
	}
868
869
	/**
870
	 * Enables/disables numbered abbreviations like "ISO 9000" together with the insertion of &nbsp;.
871
	 *
872
	 * @param bool $on Optional. Default true.
873
	 */
874 1
	public function set_numbered_abbreviation_spacing( $on = true ) {
875 1
		$this->data['numberedAbbreviationSpacing'] = $on;
876 1
	}
877
878
	/**
879
	 * Enables/disables extra whitespace before certain punction marks, as is the French custom.
880
	 *
881
	 * @since 6.0.0 The default value is now `false`.`
882
	 *
883
	 * @param bool $on Optional. Default false.
884
	 */
885 1
	public function set_french_punctuation_spacing( $on = false ) {
886 1
		$this->data['frenchPunctuationSpacing'] = $on;
887 1
	}
888
889
	/**
890
	 * Sets the list of units to keep together with their values.
891
	 *
892
	 * @param string|array $units A comma separated list or an array of units.
893
	 */
894 1
	public function set_units( $units = [] ) {
895 1
		$this->data['units'] = Strings::maybe_split_parameters( $units );
896 1
		$this->custom_units  = $this->update_unit_pattern( $this->data['units'] );
897 1
	}
898
899
	/**
900
	 * Update pattern for matching custom units.
901
	 *
902
	 * @since 6.4.0 Visibility changed to protected, return value added.
903
	 *
904
	 * @param array $units An array of unit names.
905
	 *
906
	 * @return string
907
	 */
908 2
	protected function update_unit_pattern( array $units ) {
909
		// Update unit regex pattern.
910 2
		foreach ( $units as $index => $unit ) {
911 2
			$units[ $index ] = \preg_quote( $unit, '/' );
912
		}
913
914 2
		$custom_units  = \implode( '|', $units );
915 2
		$custom_units .= ! empty( $custom_units ) ? '|' : '';
916
917 2
		return $custom_units;
918
	}
919
920
	/**
921
	 * Enables/disables wrapping of Em and En dashes are in thin spaces.
922
	 *
923
	 * @param bool $on Optional. Default true.
924
	 */
925 1
	public function set_dash_spacing( $on = true ) {
926 1
		$this->data['dashSpacing'] = $on;
927 1
	}
928
929
	/**
930
	 * Enables/disables removal of extra whitespace characters.
931
	 *
932
	 * @param bool $on Optional. Default true.
933
	 */
934 1
	public function set_space_collapse( $on = true ) {
935 1
		$this->data['spaceCollapse'] = $on;
936 1
	}
937
938
	/**
939
	 * Enables/disables widow handling.
940
	 *
941
	 * @param bool $on Optional. Default true.
942
	 */
943 1
	public function set_dewidow( $on = true ) {
944 1
		$this->data['dewidow'] = $on;
945 1
	}
946
947
	/**
948
	 * Sets the maximum length of widows that will be protected.
949
	 *
950
	 * @param int $length Defaults to 5. Trying to set the value to less than 2 resets the length to the default.
951
	 */
952 1
	public function set_max_dewidow_length( $length = 5 ) {
953 1
		$length = ( $length > 1 ) ? $length : 5;
954
955 1
		$this->data['dewidowMaxLength'] = $length;
956 1
	}
957
958
	/**
959
	 * Sets the maximum number of words considered for dewidowing.
960
	 *
961
	 * @param int $number Defaults to 1. Only 1, 2 and 3 are valid.
962
	 */
963 1
	public function set_dewidow_word_number( $number = 1 ) {
964 1
		$number = ( $number > 3 || $number < 1 ) ? 1 : $number;
965
966 1
		$this->data['dewidowWordNumber'] = $number;
967 1
	}
968
969
	/**
970
	 * Sets the maximum length of pulled text to keep widows company.
971
	 *
972
	 * @param int $length Defaults to 5. Trying to set the value to less than 2 resets the length to the default.
973
	 */
974 1
	public function set_max_dewidow_pull( $length = 5 ) {
975 1
		$length = ( $length > 1 ) ? $length : 5;
976
977 1
		$this->data['dewidowMaxPull'] = $length;
978 1
	}
979
980
	/**
981
	 * Enables/disables wrapping at internal hard hyphens with the insertion of a zero-width-space.
982
	 *
983
	 * @param bool $on Optional. Default true.
984
	 */
985 1
	public function set_wrap_hard_hyphens( $on = true ) {
986 1
		$this->data['hyphenHardWrap'] = $on;
987 1
	}
988
989
	/**
990
	 * Enables/disables wrapping of urls.
991
	 *
992
	 * @param bool $on Optional. Default true.
993
	 */
994 1
	public function set_url_wrap( $on = true ) {
995 1
		$this->data['urlWrap'] = $on;
996 1
	}
997
998
	/**
999
	 * Enables/disables wrapping of email addresses.
1000
	 *
1001
	 * @param bool $on Optional. Default true.
1002
	 */
1003 1
	public function set_email_wrap( $on = true ) {
1004 1
		$this->data['emailWrap'] = $on;
1005 1
	}
1006
1007
	/**
1008
	 * Sets the minimum character requirement after an URL wrapping point.
1009
	 *
1010
	 * @param int $length Defaults to 5. Trying to set the value to less than 1 resets the length to the default.
1011
	 */
1012 1
	public function set_min_after_url_wrap( $length = 5 ) {
1013 1
		$length = ( $length > 0 ) ? $length : 5;
1014
1015 1
		$this->data['urlMinAfterWrap'] = $length;
1016 1
	}
1017
1018
	/**
1019
	 * Enables/disables wrapping of ampersands in <span class="amp">.
1020
	 *
1021
	 * @param bool $on Optional. Default true.
1022
	 */
1023 1
	public function set_style_ampersands( $on = true ) {
1024 1
		$this->data['styleAmpersands'] = $on;
1025 1
	}
1026
1027
	/**
1028
	 * Enables/disables wrapping caps in <span class="caps">.
1029
	 *
1030
	 * @param bool $on Optional. Default true.
1031
	 */
1032 1
	public function set_style_caps( $on = true ) {
1033 1
		$this->data['styleCaps'] = $on;
1034 1
	}
1035
1036
	/**
1037
	 * Enables/disables wrapping of initial quotes in <span class="quo"> or <span class="dquo">.
1038
	 *
1039
	 * @param bool $on Optional. Default true.
1040
	 */
1041 1
	public function set_style_initial_quotes( $on = true ) {
1042 1
		$this->data['styleInitialQuotes'] = $on;
1043 1
	}
1044
1045
	/**
1046
	 * Enables/disables wrapping of numbers in <span class="numbers">.
1047
	 *
1048
	 * @param bool $on Optional. Default true.
1049
	 */
1050 1
	public function set_style_numbers( $on = true ) {
1051 1
		$this->data['styleNumbers'] = $on;
1052 1
	}
1053
1054
	/**
1055
	 * Enables/disables wrapping of punctiation and wide characters in <span class="pull-*">.
1056
	 *
1057
	 * @param bool $on Optional. Default true.
1058
	 */
1059 1
	public function set_style_hanging_punctuation( $on = true ) {
1060 1
		$this->data['styleHangingPunctuation'] = $on;
1061 1
	}
1062
1063
	/**
1064
	 * Sets the list of tags where initial quotes and guillemets should be styled.
1065
	 *
1066
	 * @param string|array $tags A comma separated list or an array of tag names.
1067
	 */
1068 1
	public function set_initial_quote_tags( $tags = [ 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'li', 'dd', 'dt' ] ) {
1069
		// Make array if handed a list of tags as a string.
1070 1
		if ( ! \is_array( $tags ) ) {
1071 1
			$tags = \preg_split( '/[^a-z0-9]+/', $tags, -1, PREG_SPLIT_NO_EMPTY );
1072
		}
1073
1074
		// Store the tag array inverted (with the tagName as its index for faster lookup).
1075 1
		$this->data['initialQuoteTags'] = \array_change_key_case( \array_flip( /** Array. @scrutinizer ignore-type */ $tags ), CASE_LOWER );
1076 1
	}
1077
1078
	/**
1079
	 * Enables/disables hyphenation.
1080
	 *
1081
	 * @param bool $on Optional. Default true.
1082
	 */
1083 1
	public function set_hyphenation( $on = true ) {
1084 1
		$this->data['hyphenation'] = $on;
1085 1
	}
1086
1087
	/**
1088
	 * Sets the hyphenation pattern language.
1089
	 *
1090
	 * @param string $lang Has to correspond to a filename in 'lang'. Optional. Default 'en-US'.
1091
	 */
1092 8
	public function set_hyphenation_language( $lang = 'en-US' ) {
1093 8
		if ( isset( $this->data['hyphenLanguage'] ) && $this->data['hyphenLanguage'] === $lang ) {
1094 3
			return; // Bail out, no need to do anything.
1095
		}
1096
1097 8
		$this->data['hyphenLanguage'] = $lang;
1098 8
	}
1099
1100
	/**
1101
	 * Sets the minimum length of a word that may be hyphenated.
1102
	 *
1103
	 * @param int $length Defaults to 5. Trying to set the value to less than 2 resets the length to the default.
1104
	 */
1105 1
	public function set_min_length_hyphenation( $length = 5 ) {
1106 1
		$length = ( $length > 1 ) ? $length : 5;
1107
1108 1
		$this->data['hyphenMinLength'] = $length;
1109 1
	}
1110
1111
	/**
1112
	 * Sets the minimum character requirement before a hyphenation point.
1113
	 *
1114
	 * @param int $length Defaults to 3. Trying to set the value to less than 1 resets the length to the default.
1115
	 */
1116 1
	public function set_min_before_hyphenation( $length = 3 ) {
1117 1
		$length = ( $length > 0 ) ? $length : 3;
1118
1119 1
		$this->data['hyphenMinBefore'] = $length;
1120 1
	}
1121
1122
	/**
1123
	 * Sets the minimum character requirement after a hyphenation point.
1124
	 *
1125
	 * @param int $length Defaults to 2. Trying to set the value to less than 1 resets the length to the default.
1126
	 */
1127 1
	public function set_min_after_hyphenation( $length = 2 ) {
1128 1
		$length = ( $length > 0 ) ? $length : 2;
1129
1130 1
		$this->data['hyphenMinAfter'] = $length;
1131 1
	}
1132
1133
	/**
1134
	 * Enables/disables hyphenation of titles and headings.
1135
	 *
1136
	 * @param bool $on Optional. Default true.
1137
	 */
1138 1
	public function set_hyphenate_headings( $on = true ) {
1139 1
		$this->data['hyphenateTitle'] = $on;
1140 1
	}
1141
1142
	/**
1143
	 * Enables/disables hyphenation of words set completely in capital letters.
1144
	 *
1145
	 * @param bool $on Optional. Default true.
1146
	 */
1147 1
	public function set_hyphenate_all_caps( $on = true ) {
1148 1
		$this->data['hyphenateAllCaps'] = $on;
1149 1
	}
1150
1151
	/**
1152
	 * Enables/disables hyphenation of words starting with a capital letter.
1153
	 *
1154
	 * @param bool $on Optional. Default true.
1155
	 */
1156 1
	public function set_hyphenate_title_case( $on = true ) {
1157 1
		$this->data['hyphenateTitleCase'] = $on;
1158 1
	}
1159
1160
	/**
1161
	 * Enables/disables hyphenation of compound words (e.g. "editor-in-chief").
1162
	 *
1163
	 * @param bool $on Optional. Default true.
1164
	 */
1165 1
	public function set_hyphenate_compounds( $on = true ) {
1166 1
		$this->data['hyphenateCompounds'] = $on;
1167 1
	}
1168
1169
	/**
1170
	 * Sets custom word hyphenations.
1171
	 *
1172
	 * @param string|array $exceptions An array of words with all hyphenation points marked with a hard hyphen (or a string list of such words).
1173
	 *        In the latter case, only alphanumeric characters and hyphens are recognized. The default is empty.
1174
	 */
1175 2
	public function set_hyphenation_exceptions( $exceptions = [] ) {
1176 2
		$this->data['hyphenationCustomExceptions'] = Strings::maybe_split_parameters( $exceptions );
1177 2
	}
1178
1179
	/**
1180
	 * Retrieves a unique hash value for the current settings.
1181
	 *
1182
	 * @since 5.2.0 The new parameter $raw_output has been added.
1183
	 *
1184
	 * @param int  $max_length Optional. The maximum number of bytes returned (0 for unlimited). Default 16.
1185
	 * @param bool $raw_output Optional. Wether to return raw binary data for the hash. Default true.
1186
	 *
1187
	 * @return string A binary hash value for the current settings limited to $max_length.
1188
	 */
1189 1
	public function get_hash( $max_length = 16, $raw_output = true ) {
1190 1
		$hash = \md5( \json_encode( $this ), $raw_output );
1191
1192 1
		if ( $max_length < \strlen( $hash ) && $max_length > 0 ) {
1193 1
			$hash = \substr( $hash, 0, $max_length );
1194
		}
1195
1196 1
		return $hash;
1197
	}
1198
}
1199