|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Drupal\psulib_base_helper\TwigExtension; |
| 6 | + |
| 7 | +use Twig\Extension\AbstractExtension; |
| 8 | +use Twig\TwigFilter; |
| 9 | + |
| 10 | +/** |
| 11 | + * Provides a Twig filter that strips HTML comments from input. |
| 12 | + * |
| 13 | + * @package Drupal\psulib_base_helper\TwigExtension |
| 14 | + */ |
| 15 | +class StripHtmlComments extends AbstractExtension { |
| 16 | + |
| 17 | + /** |
| 18 | + * Generates a list of all Twig filters that this extension defines. |
| 19 | + * |
| 20 | + * @return array |
| 21 | + * The Twig filters of this extension. |
| 22 | + */ |
| 23 | + public function getFilters(): array { |
| 24 | + return [ |
| 25 | + new TwigFilter('strip_html_comments', [ |
| 26 | + $this, |
| 27 | + 'stripHtmlCommentsFromString' |
| 28 | + ]), |
| 29 | + new TwigFilter('strip_html_comments_render', [ |
| 30 | + $this, |
| 31 | + 'stripHtmlCommentsAsRenderArray' |
| 32 | + ]), |
| 33 | + ]; |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * Gets the unique identifier for this Twig extension. |
| 38 | + * |
| 39 | + * @return string |
| 40 | + * The identifier for this extension. |
| 41 | + */ |
| 42 | + public function getName(): string { |
| 43 | + return 'psulib_base_helper.strip_html_comments'; |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Strips HTML comments from string. |
| 48 | + * |
| 49 | + * Example: A string which has value <!--Start DEBUG--> ABCD <!--End DEBUG--> |
| 50 | + * will be returned the output ABCD after using the the following function. |
| 51 | + * |
| 52 | + * @param string|null $string |
| 53 | + * A string or NULL. |
| 54 | + * |
| 55 | + * @return array |
| 56 | + * The string as markup render array without HTML comments. |
| 57 | + */ |
| 58 | + public function stripHtmlCommentsAsRenderArray(?string $string): array { |
| 59 | + if ($string !== NULL) { |
| 60 | + $stringWithoutHtmlComments = $this->stripHtmlCommentsFromString($string); |
| 61 | + } |
| 62 | + else { |
| 63 | + $stringWithoutHtmlComments = ''; |
| 64 | + } |
| 65 | + |
| 66 | + return [ |
| 67 | + '#markup' => $stringWithoutHtmlComments, |
| 68 | + ]; |
| 69 | + } |
| 70 | + |
| 71 | + /** |
| 72 | + * Strips HTML comments from string. |
| 73 | + * |
| 74 | + * Example: A string which has value <!--Start DEBUG--> ABCD <!--End DEBUG--> |
| 75 | + * will be returned the output ABCD after using the the following function. |
| 76 | + * |
| 77 | + * @param string|null $string |
| 78 | + * A string or NULL. |
| 79 | + * |
| 80 | + * @return string |
| 81 | + * The string without HTML comments. |
| 82 | + */ |
| 83 | + public function stripHtmlCommentsFromString(?string $string): string { |
| 84 | + if ($string !== NULL) { |
| 85 | + return preg_replace('/<!--(.|\s)*?-->\s*|\r|\n/', '', $string); |
| 86 | + } |
| 87 | + else { |
| 88 | + return ''; |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | +} |
0 commit comments