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.
Passed
Pull Request — master (#44)
by Der Mundschenk
02:23
created

PHP_Typography::get_diacritic_languages()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
/**
3
 *  This file is part of PHP-Typography.
4
 *
5
 *  Copyright 2014-2017 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\Fixes\Registry;
31
32
/**
33
 * Parses HTML5 (or plain text) and applies various typographic fixes to the text.
34
 *
35
 * If used with multibyte language, UTF-8 encoding is required.
36
 *
37
 * Portions of this code have been inspired by:
38
 *  - typogrify (https://code.google.com/p/typogrify/)
39
 *  - WordPress code for wptexturize (https://developer.wordpress.org/reference/functions/wptexturize/)
40
 *  - PHP SmartyPants Typographer (https://michelf.ca/projects/php-smartypants/typographer/)
41
 *
42
 *  @author Jeffrey D. King <[email protected]>
43
 *  @author Peter Putzer <[email protected]>
44
 */
45
class PHP_Typography {
46
47
	/**
48
	 * A DOM-based HTML5 parser.
49
	 *
50
	 * @var \Masterminds\HTML5
51
	 */
52
	private $html5_parser;
53
54
	/**
55
	 * The hyphenator cache.
56
	 *
57
	 * @var Hyphenator\Cache
58
	 */
59
	protected $hyphenator_cache;
60
61
	/**
62
	 * The node fixes registry.
63
	 *
64
	 * @var Registry|null;
65
	 */
66
	private $registry;
67
68
	/**
69
	 * Whether the Hyphenator\Cache of the $registry needs to be updated.
70
	 *
71
	 * @var bool
72
	 */
73
	private $update_registry_cache;
74
75
	/**
76
	 * Sets up a new PHP_Typography object.
77
	 *
78
	 * @param Registry|null $registry Optional. A fix registry instance. Default null,
79
	 *                                meaning the default fixes are used.
80
	 */
81
	public function __construct( Registry $registry = null ) {
82
		$this->registry              = $registry;
83
		$this->update_registry_cache = ! empty( $registry );
84
	}
85
86
	/**
87
	 * Modifies $html according to the defined settings.
88
	 *
89
	 * @param string   $html      A HTML fragment.
90
	 * @param Settings $settings  A settings object.
91
	 * @param bool     $is_title  Optional. If the HTML fragment is a title. Default false.
92
	 *
93
	 * @return string The processed $html.
94
	 */
95
	public function process( $html, Settings $settings, $is_title = false ) {
96
		return $this->process_textnodes( $html, function( $html, $settings, $is_title ) {
97
			return $this->get_registry()->apply_fixes( $html, $settings, $is_title, false );
98
		}, $settings, $is_title );
99
	}
100
101
	/**
102
	 * Modifies $html according to the defined settings, in a way that is appropriate for RSS feeds
103
	 * (i.e. excluding processes that may not display well with limited character set intelligence).
104
	 *
105
	 * @param string   $html     A HTML fragment.
106
	 * @param Settings $settings  A settings object.
107
	 * @param bool     $is_title Optional. If the HTML fragment is a title. Default false.
108
	 *
109
	 * @return string The processed $html.
110
	 */
111
	public function process_feed( $html, Settings $settings, $is_title = false ) {
112
		return $this->process_textnodes( $html, function( $html, $settings, $is_title ) {
113
			return $this->get_registry()->apply_fixes( $html, $settings, $is_title, true );
114
		}, $settings, $is_title );
115
	}
116
117
	/**
118
	 * Applies specific fixes to all textnodes of the HTML fragment.
119
	 *
120
	 * @param string   $html     A HTML fragment.
121
	 * @param callable $fixer    A callback that applies typography fixes to a single textnode.
122
	 * @param Settings $settings  A settings object.
123
	 * @param bool     $is_title Optional. If the HTML fragment is a title. Default false.
124
	 *
125
	 * @return string The processed $html.
126
	 */
127
	public function process_textnodes( $html, callable $fixer, Settings $settings, $is_title = false ) {
128
		if ( isset( $settings['ignoreTags'] ) && $is_title && ( in_array( 'h1', $settings['ignoreTags'], true ) || in_array( 'h2', $settings['ignoreTags'], true ) ) ) {
129
			return $html;
130
		}
131
132
		// Lazy-load our parser (the text parser is not needed for feeds).
133
		$html5_parser = $this->get_html5_parser();
134
135
		// Parse the HTML.
136
		$dom = $this->parse_html( $html5_parser, $html, $settings );
137
138
		// Abort if there were parsing errors.
139
		if ( empty( $dom ) ) {
140
			return $html;
141
		}
142
143
		// Query some nodes in the DOM.
144
		$xpath          = new \DOMXPath( $dom );
145
		$body_node      = $xpath->query( '/html/body' )->item( 0 );
146
		$all_textnodes  = $xpath->query( '//text()', $body_node );
147
		$tags_to_ignore = $this->query_tags_to_ignore( $xpath, $body_node, $settings );
148
149
		// Start processing.
150
		foreach ( $all_textnodes as $textnode ) {
151
			if ( self::arrays_intersect( DOM::get_ancestors( $textnode ), $tags_to_ignore ) ) {
152
				continue;
153
			}
154
155
			// We won't be doing anything with spaces, so we can jump ship if that is all we have.
156
			if ( $textnode->isWhitespaceInElementContent() ) {
157
				continue;
158
			}
159
160
			// Decode all characters except < > &.
161
			$textnode->data = htmlspecialchars( $textnode->data, ENT_NOQUOTES, 'UTF-8' ); // returns < > & to encoded HTML characters (&lt; &gt; and &amp; respectively).
162
163
			// Apply fixes.
164
			$fixer( $textnode, $settings, $is_title );
165
166
			// Until now, we've only been working on a textnode: HTMLify result.
167
			$this->replace_node_with_html( $textnode, $textnode->data );
168
		}
169
170
		return $html5_parser->saveHTML( $body_node->childNodes );
171
	}
172
173
	/**
174
	 * Determines whether two object arrays intersect. The second array is expected
175
	 * to use the spl_object_hash for its keys.
176
	 *
177
	 * @param array $array1 The keys are ignored.
178
	 * @param array $array2 This array has to be in the form ( $spl_object_hash => $object ).
179
	 *
180
	 * @return boolean
181
	 */
182
	protected static function arrays_intersect( array $array1, array $array2 ) {
183
		foreach ( $array1 as $value ) {
184
			if ( isset( $array2[ spl_object_hash( $value ) ] ) ) {
185
				return true;
186
			}
187
		}
188
189
		return false;
190
	}
191
192
	/**
193
	 * Parse HTML5 fragment while ignoring certain warnings for invalid HTML code (e.g. duplicate IDs).
194
	 *
195
	 * @param \Masterminds\HTML5 $parser   An intialized parser object.
196
	 * @param string             $html     The HTML fragment to parse (not a complete document).
197
	 * @param Settings           $settings The settings to apply.
198
	 *
199
	 * @return \DOMDocument|null The encoding has already been set to UTF-8. Returns null if there were parsing errors.
200
	 */
201
	public function parse_html( \Masterminds\HTML5 $parser, $html, Settings $settings ) {
202
		// Silence some parsing errors for invalid HTML.
203
		set_error_handler( [ $this, 'handle_parsing_errors' ] ); // @codingStandardsIgnoreLine
204
		$xml_error_handling = libxml_use_internal_errors( true );
205
206
		// Do the actual parsing.
207
		$dom           = $parser->loadHTML( '<!DOCTYPE html><html><body>' . $html . '</body></html>' );
208
		$dom->encoding = 'UTF-8';
209
210
		// Restore original error handling.
211
		libxml_clear_errors();
212
		libxml_use_internal_errors( $xml_error_handling );
213
		restore_error_handler();
214
215
		// Handle any parser errors.
216
		$errors = $parser->getErrors();
217
		if ( ! empty( $settings['parserErrorsHandler'] ) && ! empty( $errors ) ) {
218
			$errors = $settings['parserErrorsHandler']( $errors );
219
		}
220
221
		// Return null if there are still unhandled parsing errors.
222
		if ( ! empty( $errors ) && ! $settings['parserErrorsIgnore'] ) {
223
			$dom = null;
224
		}
225
226
		return $dom;
227
	}
228
229
	/**
230
	 * Silently handle certain HTML parsing errors.
231
	 *
232
	 * @param int    $errno      Error number.
233
	 * @param string $errstr     Error message.
234
	 * @param string $errfile    The file in which the error occurred.
235
	 * @param int    $errline    The line in which the error occurred.
236
	 * @param array  $errcontext Calling context.
237
	 *
238
	 * @return boolean Returns true if the error was handled, false otherwise.
239
	 */
240
	public function handle_parsing_errors( $errno, $errstr, $errfile, $errline, array $errcontext ) {
0 ignored issues
show
Unused Code introduced by
The parameter $errline is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $errcontext is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
241
		if ( ! ( error_reporting() & $errno ) ) { // @codingStandardsIgnoreLine.
242
			return true; // not interesting.
243
		}
244
245
		// Ignore warnings from parser & let PHP handle the rest.
246
		return $errno & E_USER_WARNING && 0 === substr_compare( $errfile, 'DOMTreeBuilder.php', -18 );
247
	}
248
249
	/**
250
	 * Retrieves an array of nodes that should be skipped during processing.
251
	 *
252
	 * @param \DOMXPath $xpath        A valid XPath instance for the DOM to be queried.
253
	 * @param \DOMNode  $initial_node The starting node of the XPath query.
254
	 * @param Settings  $settings     The settings to apply.
255
	 *
256
	 * @return \DOMNode[] An array of \DOMNode (can be empty).
257
	 */
258
	public function query_tags_to_ignore( \DOMXPath $xpath, \DOMNode $initial_node, Settings $settings ) {
259
		$elements    = [];
260
		$query_parts = [];
261 View Code Duplication
		if ( ! empty( $settings['ignoreTags'] ) ) {
262
			$query_parts[] = '//' . implode( ' | //', $settings['ignoreTags'] );
263
		}
264 View Code Duplication
		if ( ! empty( $settings['ignoreClasses'] ) ) {
265
			$query_parts[] = "//*[contains(concat(' ', @class, ' '), ' " . implode( " ') or contains(concat(' ', @class, ' '), ' ", $settings['ignoreClasses'] ) . " ')]";
266
		}
267 View Code Duplication
		if ( ! empty( $settings['ignoreIDs'] ) ) {
268
			$query_parts[] = '//*[@id=\'' . implode( '\' or @id=\'', $settings['ignoreIDs'] ) . '\']';
269
		}
270
271 View Code Duplication
		if ( ! empty( $query_parts ) ) {
272
			$ignore_query = implode( ' | ', $query_parts );
273
274
			$nodelist = $xpath->query( $ignore_query, $initial_node );
275
			if ( false !== $nodelist ) {
276
				$elements = DOM::nodelist_to_array( $nodelist );
277
			}
278
		}
279
280
		return $elements;
281
	}
282
283
	/**
284
	 * Replaces the given node with HTML content. Uses the HTML5 parser.
285
	 *
286
	 * @param \DOMNode $node    The node to replace.
287
	 * @param string   $content The HTML fragment used to replace the node.
288
	 *
289
	 * @return \DOMNode|array An array of \DOMNode containing the new nodes or the old \DOMNode if the replacement failed.
290
	 */
291
	public function replace_node_with_html( \DOMNode $node, $content ) {
292
		$result = $node;
293
294
		$parent = $node->parentNode;
295
		if ( empty( $parent ) ) {
296
			return $node; // abort early to save cycles.
297
		}
298
299
		set_error_handler( [ $this, 'handle_parsing_errors' ] ); // @codingStandardsIgnoreLine.
300
301
		$html_fragment = $this->get_html5_parser()->loadHTMLFragment( $content );
302
		if ( ! empty( $html_fragment ) ) {
303
			$imported_fragment = $node->ownerDocument->importNode( $html_fragment, true );
304
305 View Code Duplication
			if ( ! empty( $imported_fragment ) ) {
306
				// Save the children of the imported DOMDocumentFragment before replacement.
307
				$children = DOM::nodelist_to_array( $imported_fragment->childNodes );
308
309
				if ( false !== $parent->replaceChild( $imported_fragment, $node ) ) {
310
					// Success! We return the saved array of DOMNodes as
311
					// $imported_fragment is just an empty DOMDocumentFragment now.
312
					$result = $children;
313
				}
314
			}
315
		}
316
317
		restore_error_handler();
318
319
		return $result;
320
	}
321
322
	/**
323
	 * Retrieves the fix registry.
324
	 *
325
	 * @return Registry
326
	 */
327
	public function get_registry() {
328
		if ( ! isset( $this->registry ) ) {
329
			$this->registry = Registry::create( $this->get_hyphenator_cache() );
330
		} elseif ( $this->update_registry_cache ) {
331
			$this->registry->update_hyphenator_cache( $this->get_hyphenator_cache() );
332
			$this->update_registry_cache = false;
333
		}
334
335
		return $this->registry;
336
	}
337
338
	/**
339
	 * Retrieves the HTML5 parser instance.
340
	 *
341
	 * @return \Masterminds\HTML5
342
	 */
343
	public function get_html5_parser() {
344
		// Lazy-load HTML5 parser.
345
		if ( ! isset( $this->html5_parser ) ) {
346
			$this->html5_parser = new \Masterminds\HTML5( [
347
				'disable_html_ns' => true,
348
			] );
349
		}
350
351
		return $this->html5_parser;
352
	}
353
354
	/**
355
	 * Retrieves the hyphenator cache.
356
	 *
357
	 * @return Hyphenator\Cache
358
	 */
359
	public function get_hyphenator_cache() {
360
		if ( ! isset( $this->hyphenator_cache ) ) {
361
			$this->hyphenator_cache = new Hyphenator\Cache();
362
		}
363
364
		return $this->hyphenator_cache;
365
	}
366
367
	/**
368
	 * Injects an existing Hyphenator\Cache (to facilitate persistent language caching).
369
	 *
370
	 * @param Hyphenator\Cache $cache A hyphenator cache instance.
371
	 */
372
	public function set_hyphenator_cache( Hyphenator\Cache $cache ) {
373
		$this->hyphenator_cache = $cache;
374
375
		// Change hyphenator cache for existing token fixes.
376
		if ( isset( $this->registry ) ) {
377
			$this->registry->update_hyphenator_cache( $cache );
378
		}
379
	}
380
381
	/**
382
	 * Retrieves the list of valid language plugins in the given directory.
383
	 *
384
	 * @param string $path The path in which to look for language plugin files.
385
	 *
386
	 * @return string[] An array in the form ( $language_code => $language_name ).
387
	 */
388
	private static function get_language_plugin_list( $path ) {
389
		$language_name_pattern = '/"language"\s*:\s*((".+")|(\'.+\'))\s*,/';
390
		$languages             = [];
391
		$handle                = opendir( $path );
392
393
		// Read all files in directory.
394
		$file = readdir( $handle );
395
		while ( $file ) {
396
			// We only want the JSON files.
397
			if ( '.json' === substr( $file, -5 ) ) {
398
				$file_content = file_get_contents( $path . $file );
399
				if ( preg_match( $language_name_pattern, $file_content, $matches ) ) {
400
					$language_name = substr( $matches[1], 1, -1 );
401
					$language_code = substr( $file, 0, -5 );
402
403
					$languages[ $language_code ] = $language_name;
404
				}
405
			}
406
407
			// Read next file.
408
			$file = readdir( $handle );
409
		}
410
		closedir( $handle );
411
412
		// Sort translated language names according to current locale.
413
		asort( $languages );
414
415
		return $languages;
416
	}
417
418
	/**
419
	 * Retrieves the list of valid hyphenation languages.
420
	 *
421
	 * Note that this method reads all the language files on disc, so you should
422
	 * cache the results if possible.
423
	 *
424
	 * @return string[] An array in the form of ( LANG_CODE => LANGUAGE ).
425
	 */
426
	public static function get_hyphenation_languages() {
427
		return self::get_language_plugin_list( __DIR__ . '/lang/' );
428
	}
429
430
	/**
431
	 * Retrieves the list of valid diacritic replacement languages.
432
	 *
433
	 * Note that this method reads all the language files on disc, so you should
434
	 * cache the results if possible.
435
	 *
436
	 * @return string[] An array in the form of ( LANG_CODE => LANGUAGE ).
437
	 */
438
	public static function get_diacritic_languages() {
439
		return self::get_language_plugin_list( __DIR__ . '/diacritics/' );
440
	}
441
}
442