Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like Jetpack_Tweetstorm_Helper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Jetpack_Tweetstorm_Helper, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
19 | class Jetpack_Tweetstorm_Helper { |
||
20 | /** |
||
21 | * Blocks that can be converted to tweets. |
||
22 | * |
||
23 | * @var array { |
||
24 | * The key for each element must match the registered block name. |
||
25 | * |
||
26 | * @type string $type Required. The type of content this block produces. Can be one of 'break', 'embed', 'image', |
||
27 | * 'multiline', 'text', or 'video'. |
||
28 | * @type string $content_location Optional. Where the block content can be found. Can be 'html', if we need to parse |
||
29 | * it out of the block HTML text, 'html-attributes', if the we need to parse it out of HTML attributes |
||
30 | * in the block HTML, or 'block-attributes', if the content can be found in the block attributes. |
||
31 | * Note that these attributes need to be available when the serialised block is |
||
32 | * parsed using `parse_blocks()`. If it isn't set, it's assumed the block doesn't add |
||
33 | * any content to the Twitter thread. |
||
34 | * @type array $content Optional. Defines what parts of the block content need to be extracted. Behaviour can vary based on |
||
35 | * `$content_location`, and `$type`: |
||
36 | * |
||
37 | * - When `$content_location` is 'html', a value of `array()` or `array( 'content' )` have the same meaning: |
||
38 | * The entire block HTML should be used. In both cases, 'content' will be the corresponding tag in `$template`. |
||
39 | * - When `$content_location` is 'html', it should be formatted as `array( 'container' => 'tag' )`, |
||
40 | * where 'container' is the name of the corresponding RichText container in the block editor, and is also the name |
||
41 | * of the corresponding tag in the $template string. 'tag' is the HTML tag within the block that corresponds to this |
||
42 | * container. When `$type` is 'multiline', there must only be one element in the array, and tag should be set to the HTML |
||
43 | * tag that corresponds to each line, though the 'container' should still be the RichText container name. (Eg, in the core/list block, the tag is 'li'.) |
||
44 | * - When `$content_location` is 'html-attributes', the array should be formatted as `array( 'name' => array( 'tag', 'attribute') )`, |
||
45 | * where 'name' is the name of a particular value that different block types require, 'tag' is the name of the HTML tag where 'attribute' |
||
46 | * can be found, containing the value to use for 'name'. When `$type` is 'image', 'url' and 'alt' must be defined. When `$type` is 'video', |
||
47 | * 'url' must be defined. |
||
48 | * - When `$content_location` is 'block-attributes', it must be an array of block attribute names. When `$type` is 'embed', there |
||
49 | * only be one element, corresponding to the URL for the embed. |
||
50 | * @type string $template Required for 'text' and 'multiline' types, ignored for all other types. Describes how the block content will be formatted when tweeted. |
||
51 | * Tags should match the keys of `$content`, except for the special "{{content}}", which matches the entire HTML content of the block. |
||
52 | * For 'multiline' types, the template will be repeated for every line in the block. |
||
53 | * @type boolean $force_new Required. Whether or not a new tweet should be started when this block is encountered. |
||
54 | * @type boolean $force_finished Required. Whether or not a new tweet should be started after this block is finished. |
||
55 | * } |
||
56 | */ |
||
57 | private static $supported_blocks = array( |
||
58 | 'core/embed' => array( |
||
59 | 'type' => 'embed', |
||
60 | 'content_location' => 'block-attributes', |
||
61 | 'content' => array( 'url' ), |
||
62 | 'force_new' => false, |
||
63 | 'force_finished' => true, |
||
64 | ), |
||
65 | 'core/gallery' => array( |
||
66 | 'type' => 'image', |
||
67 | 'content_location' => 'html-attributes', |
||
68 | 'content' => array( |
||
69 | 'url' => array( 'img', 'src' ), |
||
70 | 'alt' => array( 'img', 'alt' ), |
||
71 | ), |
||
72 | 'force_new' => false, |
||
73 | 'force_finished' => true, |
||
74 | ), |
||
75 | 'core/heading' => array( |
||
76 | 'type' => 'text', |
||
77 | 'content_location' => 'html', |
||
78 | 'content' => array(), |
||
79 | 'template' => '{{content}}', |
||
80 | 'force_new' => true, |
||
81 | 'force_finished' => false, |
||
82 | ), |
||
83 | 'core/image' => array( |
||
84 | 'type' => 'image', |
||
85 | 'content_location' => 'html-attributes', |
||
86 | 'content' => array( |
||
87 | 'url' => array( 'img', 'src' ), |
||
88 | 'alt' => array( 'img', 'alt' ), |
||
89 | ), |
||
90 | 'force_new' => false, |
||
91 | 'force_finished' => true, |
||
92 | ), |
||
93 | 'core/list' => array( |
||
94 | 'type' => 'multiline', |
||
95 | 'content_location' => 'html', |
||
96 | // It looks a little weird to use the 'values' key for a single line, |
||
97 | // but 'values' is the name of the RichText content area. |
||
98 | 'content' => array( |
||
99 | 'values' => 'li', |
||
100 | ), |
||
101 | 'template' => '- {{values}}', |
||
102 | 'force_new' => false, |
||
103 | 'force_finished' => false, |
||
104 | ), |
||
105 | 'core/paragraph' => array( |
||
106 | 'type' => 'text', |
||
107 | 'content_location' => 'html', |
||
108 | 'content' => array(), |
||
109 | 'template' => '{{content}}', |
||
110 | 'force_new' => false, |
||
111 | 'force_finished' => false, |
||
112 | ), |
||
113 | 'core/quote' => array( |
||
114 | 'type' => 'text', |
||
115 | 'content_location' => 'html', |
||
116 | // The quote content will always be inside <p> tags. |
||
117 | 'content' => array( |
||
118 | 'value' => 'p', |
||
119 | 'citation' => 'cite', |
||
120 | ), |
||
121 | 'template' => '“{{value}}” – {{citation}}', |
||
122 | 'force_new' => false, |
||
123 | 'force_finished' => false, |
||
124 | ), |
||
125 | 'core/separator' => array( |
||
126 | 'type' => 'break', |
||
127 | 'force_new' => false, |
||
128 | 'force_finished' => true, |
||
129 | ), |
||
130 | 'core/spacer' => array( |
||
131 | 'type' => 'break', |
||
132 | 'force_new' => false, |
||
133 | 'force_finished' => true, |
||
134 | ), |
||
135 | 'core/verse' => array( |
||
136 | 'type' => 'text', |
||
137 | 'content_location' => 'html', |
||
138 | 'content' => array(), |
||
139 | 'template' => '{{content}}', |
||
140 | 'force_new' => false, |
||
141 | 'force_finished' => false, |
||
142 | ), |
||
143 | 'core/video' => array( |
||
144 | 'type' => 'video', |
||
145 | 'content_location' => 'html-attributes', |
||
146 | 'content' => array( |
||
147 | 'url' => array( 'video', 'src' ), |
||
148 | ), |
||
149 | 'force_new' => false, |
||
150 | 'force_finished' => true, |
||
151 | ), |
||
152 | 'jetpack/gif' => array( |
||
153 | 'type' => 'embed', |
||
154 | 'content_location' => 'block-attributes', |
||
155 | 'content' => array( 'giphyUrl' ), |
||
156 | 'force_new' => false, |
||
157 | 'force_finished' => true, |
||
158 | ), |
||
159 | ); |
||
160 | |||
161 | /** |
||
162 | * A cache of _wp_emoji_list( 'entities' ), after being run through html_entity_decode(). |
||
163 | * |
||
164 | * Initialised in ::is_valid_tweet(). |
||
165 | * |
||
166 | * @var array |
||
167 | */ |
||
168 | private static $emoji_list = array(); |
||
169 | |||
170 | /** |
||
171 | * Special line separator character, for multiline text. |
||
172 | * |
||
173 | * @var string |
||
174 | */ |
||
175 | private static $line_separator = "\xE2\x80\xA8"; |
||
176 | |||
177 | /** |
||
178 | * Special inline placeholder character, for inline tags that change content length in the RichText.. |
||
179 | * |
||
180 | * @var string |
||
181 | */ |
||
182 | private static $inline_placeholder = "\xE2\x81\xA3"; |
||
183 | |||
184 | /** |
||
185 | * URLs always take up a fixed length from the text limit. |
||
186 | * |
||
187 | * @var int |
||
188 | */ |
||
189 | private static $characters_per_url = 24; |
||
190 | |||
191 | /** |
||
192 | * Every media attachment takes up some space from the text limit. |
||
193 | * |
||
194 | * @var int |
||
195 | */ |
||
196 | private static $characters_per_media = 24; |
||
197 | |||
198 | /** |
||
199 | * An array to store all the tweets in. |
||
200 | * |
||
201 | * @var array |
||
202 | */ |
||
203 | private static $tweets = array(); |
||
204 | |||
205 | /** |
||
206 | * While we're caching everything, we want to keep track of the URLs we're adding. |
||
207 | * |
||
208 | * @var array |
||
209 | */ |
||
210 | private static $urls = array(); |
||
211 | |||
212 | /** |
||
213 | * Gather the Tweetstorm. |
||
214 | * |
||
215 | * @param string $url The tweet URL to gather from. |
||
216 | * @return mixed |
||
217 | */ |
||
218 | public static function gather( $url ) { |
||
258 | |||
259 | /** |
||
260 | * Parse blocks into an array of tweets. |
||
261 | * |
||
262 | * @param array $blocks { |
||
263 | * An array of blocks, with optional editor-specific information, that need to be parsed into tweets. |
||
264 | * |
||
265 | * @type array $block A single block, in the form produce by parse_blocks(). |
||
266 | * @type array $attributes Optional. A list of block attributes and their values from the block editor. |
||
267 | * @type string $clientId Optional. The clientId of this block in the block editor. |
||
268 | * } |
||
269 | * @return array An array of tweets. |
||
270 | */ |
||
271 | public static function parse( $blocks ) { |
||
311 | |||
312 | /** |
||
313 | * If the passed block name is supported, return the block definition. |
||
314 | * |
||
315 | * @param string $block_name The registered block name. |
||
316 | * @return array|null The block definition, if it's supported. |
||
317 | */ |
||
318 | private static function get_block_definition( $block_name ) { |
||
330 | |||
331 | /** |
||
332 | * If the block has any text, process it, and add it to the tweet list. |
||
333 | * |
||
334 | * @param array $block The block to process. |
||
335 | */ |
||
336 | private static function add_text_to_tweets( $block ) { |
||
515 | |||
516 | /** |
||
517 | * Check if the block has any media to add, and add it. |
||
518 | * |
||
519 | * @param array $block The block to process. |
||
520 | */ |
||
521 | private static function add_media_to_tweets( $block ) { |
||
580 | |||
581 | /** |
||
582 | * Check if the block has a tweet that we can attach to the current tweet as a quote, and add it. |
||
583 | * |
||
584 | * @param array $block The block to process. |
||
585 | */ |
||
586 | private static function add_tweet_to_tweets( $block ) { |
||
603 | |||
604 | /** |
||
605 | * Check if the block has an embed URL that we can append to the current tweet text. |
||
606 | * |
||
607 | * @param array $block The block to process. |
||
608 | */ |
||
609 | private static function add_embed_to_tweets( $block ) { |
||
610 | if ( 0 === strlen( $block['embed'] ) ) { |
||
611 | return; |
||
612 | } |
||
613 | |||
614 | $current_tweet = self::get_current_tweet(); |
||
615 | |||
616 | $reserved_characters = count( $current_tweet['media'] ) * self::$characters_per_media; |
||
617 | $reserved_characters += 1 + self::$characters_per_url; |
||
618 | |||
619 | // We can only attach an embed to the previous tweet if it doesn't already |
||
620 | // have any URLs in it. Also, we can't attach it if it'll make the tweet too long. |
||
621 | if ( preg_match( '/url-placeholder-\d+-*/', $current_tweet['text'] ) || ! self::is_valid_tweet( $current_tweet['text'], $reserved_characters ) ) { |
||
622 | $current_tweet = self::start_new_tweet(); |
||
623 | $current_tweet['text'] = self::generate_url_placeholder( $block['embed'] ); |
||
624 | } else { |
||
625 | $space = empty( $current_tweet['text'] ) ? '' : ' '; |
||
626 | $current_tweet['text'] .= $space . self::generate_url_placeholder( $block['embed'] ); |
||
627 | } |
||
628 | |||
629 | self::save_current_tweet( $current_tweet, $block ); |
||
630 | } |
||
631 | |||
632 | /** |
||
633 | * Given an array of blocks and optional editor information, this will extract them into |
||
634 | * the internal representation used during parsing. |
||
635 | * |
||
636 | * @param array $blocks An array of blocks and optional editor-related information. |
||
637 | * @return array An array of blocks, in our internal representation. |
||
638 | */ |
||
639 | private static function extract_blocks( $blocks ) { |
||
640 | if ( empty( $blocks ) ) { |
||
641 | return array(); |
||
642 | } |
||
643 | |||
644 | $block_count = count( $blocks ); |
||
645 | |||
646 | for ( $ii = 0; $ii < $block_count; $ii++ ) { |
||
647 | if ( ! self::get_block_definition( $blocks[ $ii ]['block']['blockName'] ) ) { |
||
648 | unset( $blocks[ $ii ] ); |
||
649 | continue; |
||
650 | } |
||
651 | |||
652 | $blocks[ $ii ]['name'] = $blocks[ $ii ]['block']['blockName']; |
||
653 | $blocks[ $ii ]['text'] = self::extract_text_from_block( $blocks[ $ii ]['block'] ); |
||
654 | $blocks[ $ii ]['media'] = self::extract_media_from_block( $blocks[ $ii ]['block'] ); |
||
655 | $blocks[ $ii ]['tweet'] = self::extract_tweet_from_block( $blocks[ $ii ]['block'] ); |
||
656 | $blocks[ $ii ]['embed'] = self::extract_embed_from_block( $blocks[ $ii ]['block'] ); |
||
657 | } |
||
658 | |||
659 | return array_values( $blocks ); |
||
660 | } |
||
661 | |||
662 | /** |
||
663 | * Creates a blank tweet, appends it to the tweets array, and returns the tweet. |
||
664 | * |
||
665 | * @return array The blank tweet. |
||
666 | */ |
||
667 | private static function start_new_tweet() { |
||
668 | self::$tweets[] = array( |
||
669 | // An array of blocks that make up this tweet. |
||
670 | 'blocks' => array(), |
||
671 | // If this tweet only contains part of a block, the boundary contains |
||
672 | // information about where in the block the tweet ends. |
||
673 | 'boundary' => false, |
||
674 | // The text content of the tweet. |
||
675 | 'text' => '', |
||
676 | // The media content of the tweet. |
||
677 | 'media' => array(), |
||
678 | // The quoted tweet in this tweet. |
||
679 | 'tweet' => '', |
||
680 | // Some blocks force a hard finish to the tweet, even if subsequent blocks |
||
681 | // could technically be appended. This flag shows when a tweet is finished. |
||
682 | 'finished' => false, |
||
683 | // Flag if the current tweet already has content in it. |
||
684 | 'changed' => false, |
||
685 | ); |
||
686 | |||
687 | return self::get_current_tweet(); |
||
688 | } |
||
689 | |||
690 | /** |
||
691 | * Get the last tweet in the array. |
||
692 | * |
||
693 | * @return array The tweet. |
||
694 | */ |
||
695 | private static function get_current_tweet() { |
||
696 | return end( self::$tweets ); |
||
697 | } |
||
698 | |||
699 | /** |
||
700 | * Saves the passed tweet array as the last tweet, overwriting the former last tweet. |
||
701 | * |
||
702 | * This method adds some last minute checks: marking the tweet as "changed", as well |
||
703 | * as adding the $block to the tweet (if it was passed, and hasn't already been added). |
||
704 | * |
||
705 | * @param array $tweet The tweet being stored. |
||
706 | * @param array $block Optional. The block that was used to modify this tweet. |
||
707 | * @return array The saved tweet, after the last minute checks have been done. |
||
708 | */ |
||
709 | private static function save_current_tweet( $tweet, $block = null ) { |
||
710 | $tweet['changed'] = true; |
||
711 | |||
712 | if ( isset( $block ) ) { |
||
713 | $block_def = self::get_block_definition( $block['name'] ); |
||
714 | |||
715 | // Check if this block type will be forcing a new tweet. |
||
716 | if ( $block_def['force_finished'] ) { |
||
717 | $tweet['finished'] = true; |
||
718 | } |
||
719 | |||
720 | // Check if this block is already recorded against this tweet. |
||
721 | $last_block = end( $tweet['blocks'] ); |
||
722 | if ( isset( $block['clientId'] ) && ( false === $last_block || $last_block['clientId'] !== $block['clientId'] ) ) { |
||
723 | $tweet['blocks'][] = $block; |
||
724 | } |
||
725 | } |
||
726 | |||
727 | // Find the index of the last tweet in the array. |
||
728 | end( self::$tweets ); |
||
729 | $tweet_index = key( self::$tweets ); |
||
730 | |||
731 | self::$tweets[ $tweet_index ] = $tweet; |
||
732 | |||
733 | return $tweet; |
||
734 | } |
||
735 | |||
736 | /** |
||
737 | * Checks if the passed text is valid for a tweet or not. |
||
738 | * |
||
739 | * @param string $text The text to check. |
||
740 | * @param int $reserved_characters Optional. The number of characters to reduce the maximum tweet length by. |
||
741 | * @return bool Whether or not the text is valid. |
||
742 | */ |
||
743 | private static function is_valid_tweet( $text, $reserved_characters = 0 ) { |
||
744 | return self::is_within_twitter_length( $text, 280 - $reserved_characters ); |
||
745 | } |
||
746 | |||
747 | /** |
||
748 | * Checks if the passed text is valid for image alt text. |
||
749 | * |
||
750 | * @param string $text The text to check. |
||
751 | * @return bool Whether or not the text is valid. |
||
752 | */ |
||
753 | private static function is_valid_alt_text( $text ) { |
||
754 | return self::is_within_twitter_length( $text, 1000 ); |
||
755 | } |
||
756 | |||
757 | /** |
||
758 | * Check if a string is shorter than a given length, according to Twitter's rules for counting string length. |
||
759 | * |
||
760 | * @param string $text The text to check. |
||
761 | * @param int $max_length The number of characters long this string can be. |
||
762 | * @return bool Whether or not the string is no longer than the length limit. |
||
763 | */ |
||
764 | private static function is_within_twitter_length( $text, $max_length ) { |
||
765 | // Replace all multiline separators with a \n, since that's the |
||
766 | // character we actually want to count. |
||
767 | $text = str_replace( self::$line_separator, "\n", $text ); |
||
768 | |||
769 | // Keep a running total of characters we've removed. |
||
770 | $stripped_characters = 0; |
||
771 | |||
772 | // Since we use '…' a lot, strip it out, so we can still use the ASCII checks. |
||
773 | $ellipsis_count = 0; |
||
774 | $text = str_replace( '…', '', $text, $ellipsis_count ); |
||
775 | |||
776 | // The ellipsis glyph counts for two characters. |
||
777 | $stripped_characters += $ellipsis_count * 2; |
||
778 | |||
779 | // Try filtering out emoji first, since ASCII text + emoji is a relatively common case. |
||
780 | if ( ! self::is_ascii( $text ) ) { |
||
781 | // Initialise the emoji cache. |
||
782 | if ( 0 === count( self::$emoji_list ) ) { |
||
783 | self::$emoji_list = array_map( 'html_entity_decode', _wp_emoji_list( 'entities' ) ); |
||
784 | } |
||
785 | |||
786 | $emoji_count = 0; |
||
787 | $text = str_replace( self::$emoji_list, '', $text, $emoji_count ); |
||
788 | |||
789 | // Emoji graphemes count as 2 characters each. |
||
790 | $stripped_characters += $emoji_count * 2; |
||
791 | } |
||
792 | |||
793 | if ( self::is_ascii( $text ) ) { |
||
794 | $stripped_characters += strlen( $text ); |
||
795 | if ( $stripped_characters <= $max_length ) { |
||
796 | return true; |
||
797 | } |
||
798 | |||
799 | return false; |
||
800 | } |
||
801 | |||
802 | // Remove any glyphs that count as 1 character. |
||
803 | // Source: https://github.com/twitter/twitter-text/blob/master/config/v3.json . |
||
804 | // Note that the source ranges are in decimal, the regex ranges are converted to hex. |
||
805 | $single_character_count = 0; |
||
806 | $text = preg_replace( '/[\x{0000}-\x{10FF}\x{2000}-\x{200D}\x{2010}-\x{201F}\x{2032}-\x{2037}]/uS', '', $text, -1, $single_character_count ); |
||
807 | |||
808 | $stripped_characters += $single_character_count; |
||
809 | |||
810 | // Check if there's any text we haven't counted yet. |
||
811 | // Any remaining glyphs count as 2 characters each. |
||
812 | if ( 0 !== strlen( $text ) ) { |
||
813 | // WP provides a compat version of mb_strlen(), no need to check if it exists. |
||
814 | $stripped_characters += mb_strlen( $text, 'UTF-8' ) * 2; |
||
815 | } |
||
816 | |||
817 | if ( $stripped_characters <= $max_length ) { |
||
818 | return true; |
||
819 | } |
||
820 | |||
821 | return false; |
||
822 | } |
||
823 | |||
824 | /** |
||
825 | * Checks if a string only contains ASCII characters. |
||
826 | * |
||
827 | * @param string $text The string to check. |
||
828 | * @return bool Whether or not the string is ASCII-only. |
||
829 | */ |
||
830 | private static function is_ascii( $text ) { |
||
831 | if ( function_exists( 'mb_check_encoding' ) ) { |
||
832 | if ( mb_check_encoding( $text, 'ASCII' ) ) { |
||
833 | return true; |
||
834 | } |
||
835 | } elseif ( ! preg_match( '/[^\x00-\x7F]/', $text ) ) { |
||
836 | return true; |
||
837 | } |
||
838 | |||
839 | return false; |
||
840 | } |
||
841 | |||
842 | /** |
||
843 | * A block will generate a certain amount of text to be inserted into a tweet. If that text is too |
||
844 | * long for a tweet, we already know where the text will be split when it's published as tweet, but |
||
845 | * we need to calculate where that corresponds to in the block edit UI. |
||
846 | * |
||
847 | * The tweet template for that block may add extra characters, extra characters are added for URL |
||
848 | * placeholders, and the block may contain multiple RichText areas (corresponding to attributes), |
||
849 | * so we need to keep track of both until the this function calculates which attribute area (in the |
||
850 | * block editor, the richTextIdentifier) that offset corresponds to, and how far into that attribute |
||
851 | * area it is. |
||
852 | * |
||
853 | * @param array $block The block being checked. |
||
854 | * @param integer $offset The position in the tweet text where it will be split. |
||
855 | * @return array|false `false` if the boundary can't be determined. Otherwise, returns the |
||
856 | * position in the block editor to insert the tweet boundary annotation. |
||
857 | */ |
||
858 | private static function get_boundary( $block, $offset ) { |
||
859 | // If we don't have a clientId, there's no point in generating a boundary, since this |
||
860 | // parse request doesn't have a way to map blocks back to editor UI. |
||
861 | if ( ! isset( $block['clientId'] ) ) { |
||
862 | return false; |
||
863 | } |
||
864 | |||
865 | $block_def = self::get_block_definition( $block['name'] ); |
||
866 | |||
867 | View Code Duplication | if ( isset( $block_def['content'] ) && count( $block_def['content'] ) > 0 ) { |
|
868 | $tags = $block_def['content']; |
||
869 | } else { |
||
870 | $tags = array( 'content' ); |
||
871 | } |
||
872 | |||
873 | $tag_content = self::extract_tag_content_from_html( $tags, $block['block']['innerHTML'] ); |
||
874 | |||
875 | // $tag_content is split up by tag first, then lines. We want to remap it to split it by lines |
||
876 | // first, then tag. |
||
877 | $lines = array(); |
||
878 | foreach ( $tag_content as $tag => $content ) { |
||
879 | if ( 'content' === $tag ) { |
||
880 | $attribute_name = 'content'; |
||
881 | } else { |
||
882 | $attribute_name = array_search( $tag, $block_def['content'], true ); |
||
883 | } |
||
884 | |||
885 | foreach ( $content as $id => $content_string ) { |
||
886 | // Multiline blocks can have multiple lines, but other blocks will always only have 1. |
||
887 | if ( 'multiline' === $block_def['type'] ) { |
||
888 | $line_number = $id; |
||
889 | } else { |
||
890 | $line_number = 0; |
||
891 | } |
||
892 | |||
893 | if ( ! isset( $lines[ $line_number ] ) ) { |
||
894 | $lines[ $line_number ] = array(); |
||
895 | } |
||
896 | |||
897 | if ( ! isset( $lines[ $line_number ][ $attribute_name ] ) ) { |
||
898 | // For multiline blocks, or the first time this attribute has been encountered |
||
899 | // in single line blocks, assign the string to the line/attribute. |
||
900 | $lines[ $line_number ][ $attribute_name ] = $content_string; |
||
901 | } else { |
||
902 | // For subsequent times this line/attribute is encountered (only in single line blocks), |
||
903 | // append the string with a line break. |
||
904 | $lines[ $line_number ][ $attribute_name ] .= "\n$content_string"; |
||
905 | } |
||
906 | } |
||
907 | } |
||
908 | |||
909 | $line_count = count( $lines ); |
||
910 | |||
911 | $template_parts = preg_split( '/({{\w+}})/', $block_def['template'], -1, PREG_SPLIT_DELIM_CAPTURE ); |
||
912 | |||
913 | // Keep track of the total number of bytes we've processed from this block. |
||
914 | $total_bytes_processed = 0; |
||
915 | |||
916 | // Keep track of the number of characters that the processed data translates to in the editor. |
||
917 | $characters_processed = 0; |
||
918 | |||
919 | foreach ( $lines as $line_number => $line ) { |
||
920 | // Add up the length of all the parts of this line. |
||
921 | $line_byte_total = array_sum( array_map( 'strlen', $line ) ); |
||
922 | |||
923 | if ( $line_byte_total > 0 ) { |
||
924 | // We have something to use in the template, so loop over each part of the template, and count it. |
||
925 | foreach ( $template_parts as $template_part ) { |
||
926 | $matches = array(); |
||
927 | if ( preg_match( '/{{(\w+)}}/', $template_part, $matches ) ) { |
||
928 | $part_name = $matches[1]; |
||
929 | |||
930 | $line_part_data = $line[ $part_name ]; |
||
931 | $line_part_bytes = strlen( $line_part_data ); |
||
932 | |||
933 | $cleaned_line_part_data = preg_replace( '/ \(url-placeholder-\d+-*\)/', '', $line_part_data ); |
||
934 | |||
935 | $cleaned_line_part_data = preg_replace_callback( |
||
936 | '/url-placeholder-(\d+)-*/', |
||
937 | function ( $matches ) { |
||
938 | return self::$urls[ $matches[1] ]; |
||
939 | }, |
||
940 | $cleaned_line_part_data |
||
941 | ); |
||
942 | |||
943 | if ( $total_bytes_processed + $line_part_bytes >= $offset ) { |
||
944 | // We know that the offset is somewhere inside this part of the tweet, but we need to remove the length |
||
945 | // of any URL placeholders that appear before the boundary, to be able to calculate the correct attribute offset. |
||
946 | |||
947 | // $total_bytes_processed is the sum of everything we've processed so far, (including previous parts) |
||
948 | // on this line. This makes it relatively easy to calculate the number of bytes into this part |
||
949 | // that the boundary will occur. |
||
950 | $line_part_byte_boundary = $offset - $total_bytes_processed; |
||
951 | |||
952 | // Grab the data from this line part that appears before the boundary. |
||
953 | $line_part_pre_boundary_data = substr( $line_part_data, 0, $line_part_byte_boundary ); |
||
954 | |||
955 | // Remove any URL placeholders, since these aren't shown in the editor. |
||
956 | $line_part_pre_boundary_data = preg_replace( '/ \(url-placeholder-\d+-*\)/', '', $line_part_pre_boundary_data ); |
||
957 | |||
958 | $line_part_pre_boundary_data = preg_replace_callback( |
||
959 | '/url-placeholder-(\d+)-*/', |
||
960 | function ( $matches ) { |
||
961 | return self::$urls[ $matches[1] ]; |
||
962 | }, |
||
963 | $line_part_pre_boundary_data |
||
964 | ); |
||
965 | |||
966 | $boundary_start = self::utf_16_code_unit_length( $line_part_pre_boundary_data ) - 1; |
||
967 | |||
968 | // Multiline blocks need to offset for the characters that are in the same content area, |
||
969 | // but which were counted on previous lines. |
||
970 | if ( 'multiline' === $block_def['type'] ) { |
||
971 | $boundary_start += $characters_processed; |
||
972 | } |
||
973 | |||
974 | // Check if the boundary is happening on a line break or a space. |
||
975 | if ( "\n" === $line_part_data[ $line_part_byte_boundary - 1 ] ) { |
||
976 | $type = 'line-break'; |
||
977 | |||
978 | // A line break boundary can actually be multiple consecutive line breaks, |
||
979 | // count them all up so we know how big the annotation needs to be. |
||
980 | $matches = array(); |
||
981 | preg_match( '/\n+$/', substr( $line_part_data, 0, $line_part_byte_boundary ), $matches ); |
||
982 | $boundary_end = $boundary_start + 1; |
||
983 | $boundary_start -= strlen( $matches[0] ) - 1; |
||
984 | } else { |
||
985 | $type = 'normal'; |
||
986 | $boundary_end = $boundary_start + 1; |
||
987 | } |
||
988 | |||
989 | return array( |
||
990 | 'start' => $boundary_start, |
||
991 | 'end' => $boundary_end, |
||
992 | 'container' => $part_name, |
||
993 | 'type' => $type, |
||
994 | ); |
||
995 | } else { |
||
996 | $total_bytes_processed += $line_part_bytes; |
||
997 | $characters_processed += self::utf_16_code_unit_length( $cleaned_line_part_data ); |
||
998 | continue; |
||
999 | } |
||
1000 | } else { |
||
1001 | $total_bytes_processed += strlen( $template_part ); |
||
1002 | } |
||
1003 | } |
||
1004 | |||
1005 | // Are we breaking at the end of this line? |
||
1006 | if ( $total_bytes_processed + 1 === $offset && $line_count > 1 ) { |
||
1007 | reset( $block_def['content'] ); |
||
1008 | $container = key( $block_def['content'] ); |
||
1009 | return array( |
||
1010 | 'line' => $line_number, |
||
1011 | 'container' => $container, |
||
1012 | 'type' => 'end-of-line', |
||
1013 | ); |
||
1014 | } |
||
1015 | |||
1016 | // The newline at the end of each line is 1 byte, but we don't need to count empty lines. |
||
1017 | $total_bytes_processed++; |
||
1018 | } |
||
1019 | |||
1020 | // We do need to count empty lines in the editor, since they'll be displayed. |
||
1021 | $characters_processed++; |
||
1022 | } |
||
1023 | |||
1024 | return false; |
||
1025 | } |
||
1026 | |||
1027 | /** |
||
1028 | * JavaScript uses UTF-16 for encoding strings, which means we need to provide UTF-16 |
||
1029 | * based offsets for the block editor to render tweet boundaries in the correct location. |
||
1030 | * |
||
1031 | * UTF-16 is a variable-width character encoding: every code unit is 2 bytes, a single character |
||
1032 | * can be one or two code units long. Fortunately for us, JavaScript's String.charAt() is based |
||
1033 | * on the older UCS-2 character encoding, which only counts single code units. PHP's strlen() |
||
1034 | * counts a code unit as being 2 characters, so once a string is converted to UTF-16, we have |
||
1035 | * a fast way to determine how long it is in UTF-16 code units. |
||
1036 | * |
||
1037 | * @param string $text The natively encoded string to get the length of. |
||
1038 | * @return int The length of the string in UTF-16 code units. Returns -1 if the length could not |
||
1039 | * be calculated. |
||
1040 | */ |
||
1041 | private static function utf_16_code_unit_length( $text ) { |
||
1042 | // If mb_convert_encoding() exists, we can use that for conversion. |
||
1043 | if ( function_exists( 'mb_convert_encoding' ) ) { |
||
1044 | // UTF-16 can add an additional code unit to the start of the string, called the |
||
1045 | // Byte Order Mark (BOM), which indicates whether the string is encoding as |
||
1046 | // big-endian, or little-endian. Since we don't want to count code unit, and the endianness |
||
1047 | // doesn't matter for our purposes, using PHP's UTF-16BE encoding uses big-endian |
||
1048 | // encoding, and ensures the BOM *won't* be prepended to the string to the string. |
||
1049 | return strlen( mb_convert_encoding( $text, 'UTF-16BE' ) ) / 2; |
||
1050 | } |
||
1051 | |||
1052 | // If we can't convert this string, return a result that will avoid an incorrect annotation being added. |
||
1053 | return -1; |
||
1054 | } |
||
1055 | |||
1056 | /** |
||
1057 | * Extracts the tweetable text from a block. |
||
1058 | * |
||
1059 | * @param array $block A single block, as generated by parse_block(). |
||
1060 | * @return string The tweetable text from the block, in the correct template form. |
||
1061 | */ |
||
1062 | private static function extract_text_from_block( $block ) { |
||
1063 | // If the block doesn't have an innerHTMl, we're not going to get any text. |
||
1064 | if ( empty( $block['innerHTML'] ) ) { |
||
1065 | return ''; |
||
1066 | } |
||
1067 | |||
1068 | $block_def = self::get_block_definition( $block['blockName'] ); |
||
1069 | |||
1070 | // We currently only support extracting text from HTML text nodes. |
||
1071 | if ( ! isset( $block_def['content_location'] ) || 'html' !== $block_def['content_location'] ) { |
||
1072 | return ''; |
||
1073 | } |
||
1074 | |||
1075 | // Find out which tags we need to extract content from. |
||
1076 | View Code Duplication | if ( isset( $block_def['content'] ) && count( $block_def['content'] ) > 0 ) { |
|
1077 | $tags = $block_def['content']; |
||
1078 | } else { |
||
1079 | $tags = array( 'content' ); |
||
1080 | } |
||
1081 | |||
1082 | $tag_values = self::extract_tag_content_from_html( $tags, $block['innerHTML'] ); |
||
1083 | |||
1084 | // We can treat single line blocks as "multiline", with only one line in them. |
||
1085 | $lines = array(); |
||
1086 | foreach ( $tag_values as $tag => $values ) { |
||
1087 | // For single-line blocks, we need to squash all the values for this tag into a single value. |
||
1088 | if ( 'multiline' !== $block_def['type'] ) { |
||
1089 | $values = array( implode( "\n", $values ) ); |
||
1090 | } |
||
1091 | |||
1092 | // Handle the special "content" tag. |
||
1093 | if ( 'content' === $tag ) { |
||
1094 | $placeholder = 'content'; |
||
1095 | } else { |
||
1096 | $placeholder = array_search( $tag, $block_def['content'], true ); |
||
1097 | } |
||
1098 | |||
1099 | // Loop over each instance of this value, appling that value to the corresponding line template. |
||
1100 | foreach ( $values as $line_number => $value ) { |
||
1101 | if ( ! isset( $lines[ $line_number ] ) ) { |
||
1102 | $lines[ $line_number ] = $block_def['template']; |
||
1103 | } |
||
1104 | |||
1105 | $lines[ $line_number ] = str_replace( '{{' . $placeholder . '}}', $value, $lines[ $line_number ] ); |
||
1106 | } |
||
1107 | } |
||
1108 | |||
1109 | // Remove any lines that didn't apply any content. |
||
1110 | $empty_template = preg_replace( '/{{.*?}}/', '', $block_def['template'] ); |
||
1111 | $lines = array_filter( |
||
1112 | $lines, |
||
1113 | function ( $line ) use ( $empty_template ) { |
||
1114 | return $line !== $empty_template; |
||
1115 | } |
||
1116 | ); |
||
1117 | |||
1118 | // Join the lines together into a single string. |
||
1119 | $text = implode( self::$line_separator, $lines ); |
||
1120 | |||
1121 | // Trim off any trailing whitespace that we no longer need. |
||
1122 | $text = preg_replace( '/(\s|' . self::$line_separator . ')+$/u', '', $text ); |
||
1123 | |||
1124 | return $text; |
||
1125 | } |
||
1126 | |||
1127 | /** |
||
1128 | * Extracts the tweetable media from a block. |
||
1129 | * |
||
1130 | * @param array $block A single block, as generated by parse_block(). |
||
1131 | * @return array { |
||
1132 | * An array of media. |
||
1133 | * |
||
1134 | * @type string url The URL of the media. |
||
1135 | * @type string alt The alt text of the media. |
||
1136 | * } |
||
1137 | */ |
||
1138 | private static function extract_media_from_block( $block ) { |
||
1191 | |||
1192 | /** |
||
1193 | * Extracts the tweet URL from a Twitter embed block. |
||
1194 | * |
||
1195 | * @param array $block A single block, as generated by parse_block(). |
||
1196 | * @return string The tweet URL. Empty string if there is none available. |
||
1197 | */ |
||
1198 | private static function extract_tweet_from_block( $block ) { |
||
1210 | |||
1211 | /** |
||
1212 | * Extracts URL from an embed block. |
||
1213 | * |
||
1214 | * @param array $block A single block, as generated by parse_block(). |
||
1215 | * @return string The URL. Empty string if there is none available. |
||
1216 | */ |
||
1217 | private static function extract_embed_from_block( $block ) { |
||
1245 | |||
1246 | /** |
||
1247 | * There's a bunch of left-over cruft in the tweets array that we don't need to return. Removing |
||
1248 | * it helps keep the size of the data down. |
||
1249 | */ |
||
1250 | private static function clean_return_tweets() { |
||
1251 | // Before we return, clean out unnecessary cruft from the return data. |
||
1252 | $tweets = array_map( |
||
1253 | function ( $tweet ) { |
||
1254 | // Remove tweets that don't have anything saved in them. eg, if the last block is a |
||
1255 | // header with no text, it'll force a new tweet, but we won't end up putting anything |
||
1256 | // in that tweet. |
||
1257 | if ( ! $tweet['changed'] ) { |
||
1324 | |||
1325 | /** |
||
1326 | * Given a list of tags and a HTML blob, this will extract the text content inside |
||
1327 | * each of the given tags. |
||
1328 | * |
||
1329 | * @param array $tags An array of tag names. |
||
1330 | * @param string $html A blob of HTML. |
||
1331 | * @return array An array of the extract content. The keys in the array are the $tags, |
||
1332 | * each value is an array. The value array is indexed in the same order as the tag |
||
1333 | * appears in the HTML blob, including nested tags. |
||
1334 | */ |
||
1335 | private static function extract_tag_content_from_html( $tags, $html ) { |
||
1480 | |||
1481 | /** |
||
1482 | * Extracts the attribute content from a tag. |
||
1483 | * |
||
1484 | * This method allows for the HTML to have multiple instances of the tag, and will return |
||
1485 | * an array containing the attribute value (or an empty string, if the tag doesn't have the |
||
1486 | * requested attribute) for each occurrence of the tag. |
||
1487 | * |
||
1488 | * @param string $tag The tag we're looking for. |
||
1489 | * @param string $attr The name of the attribute we're looking for. |
||
1490 | * @param string $html The HTML we're searching through. |
||
1491 | * @param array $attr_filters Optional. Filters tags based on whether or not they have attributes with given values. |
||
1492 | * @return array The array of attribute values found. |
||
1493 | */ |
||
1494 | private static function extract_attr_content_from_html( $tag, $attr, $html, $attr_filters = array() ) { |
||
1577 | |||
1578 | /** |
||
1579 | * Generates a placeholder for URLs, using the appropriate number of characters to imitate how |
||
1580 | * Twitter counts the length of URLs in tweets. |
||
1581 | * |
||
1582 | * @param string $url The URL to generate a placeholder for. |
||
1583 | * @return string The placeholder. |
||
1584 | */ |
||
1585 | public static function generate_url_placeholder( $url ) { |
||
1590 | |||
1591 | /** |
||
1592 | * Retrieves the Twitter card data for a list of URLs. |
||
1593 | * |
||
1594 | * @param array $urls The list of URLs to grab Twitter card data for. |
||
1595 | * @return array The Twitter card data. |
||
1596 | */ |
||
1597 | public static function generate_cards( $urls ) { |
||
1673 | |||
1674 | /** |
||
1675 | * Get the WPCOM or self-hosted site ID. |
||
1676 | * |
||
1677 | * @return mixed |
||
1678 | */ |
||
1679 | View Code Duplication | public static function get_site_id() { |
|
1691 | } |
||
1692 |
This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.
If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.
In this case you can add the
@ignore
PhpDoc annotation to the duplicate definition and it will be ignored.