Make WordPress Core

Changeset 52008


Ignore:
Timestamp:
11/04/2021 12:42:26 PM (3 years ago)
Author:
hellofromTonya
Message:

REST API: Improve translations, comments, and readability in URL Details endpoint.

Improvements:

  • Removes HTML tags from translatable strings. Uses sprintf with placeholder and translators comment.
  • Spells out "OG" to "Open Graph" to help translators.
  • Adds @since param to new filters.
  • Improves comments for code standards and consistency.
  • Improves readability by making multiple args multiline.
  • Micro-optimizations to avoid unnecessary variable assignments.

Follow-up to [51973].

Props hellofromTonya, sergeybiryukov, swissspidy.
Fixes #54358.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-url-details-controller.php

    r51973 r52008  
    7070        }
    7171
    72         $schema = array(
     72        $this->schema = array(
    7373            '$schema'    => 'http://json-schema.org/draft-04/schema#',
    7474            'title'      => 'url-details',
     
    7676            'properties' => array(
    7777                'title'       => array(
    78                     'description' => __( 'The contents of the <title> element from the URL.' ),
     78                    'description' => sprintf(
     79                        /* translators: %s: HTML title tag. */
     80                        __( 'The contents of the %s element from the URL.' ),
     81                        '<title>'
     82                    ),
    7983                    'type'        => 'string',
    8084                    'context'     => array( 'view', 'edit', 'embed' ),
     
    8286                ),
    8387                'icon'        => array(
    84                     'description' => __( 'The favicon image link of the <link rel="icon"> element from the URL.' ),
     88                    'description' => sprintf(
     89                        /* translators: %s: HTML link tag. */
     90                        __( 'The favicon image link of the %s element from the URL.' ),
     91                        '<link rel="icon">'
     92                    ),
    8593                    'type'        => 'string',
    8694                    'format'      => 'uri',
     
    8997                ),
    9098                'description' => array(
    91                     'description' => __( 'The content of the <meta name="description"> element from the URL.' ),
     99                    'description' => sprintf(
     100                        /* translators: %s: HTML meta tag. */
     101                        __( 'The content of the %s element from the URL.' ),
     102                        '<meta name="description">'
     103                    ),
    92104                    'type'        => 'string',
    93105                    'context'     => array( 'view', 'edit', 'embed' ),
     
    95107                ),
    96108                'image'       => array(
    97                     'description' => __( 'The OG image link of the <meta property="og:image"> or <meta property="og:image:url"> element from the URL.' ),
     109                    'description' => sprintf(
     110                        /* translators: 1: HTML meta tag, 2: HTML meta tag. */
     111                        __( 'The Open Graph image link of the %1$s or %2$s element from the URL.' ),
     112                        '<meta property="og:image">',
     113                        '<meta property="og:image:url">'
     114                    ),
    98115                    'type'        => 'string',
    99116                    'format'      => 'uri',
     
    104121        );
    105122
    106         $this->schema = $schema;
    107 
    108123        return $this->add_additional_fields_schema( $this->schema );
    109124    }
    110125
    111126    /**
    112      * Retrieves the contents of the <title> tag from the HTML response.
     127     * Retrieves the contents of the `<title>` tag from the HTML response.
    113128     *
    114129     * @since 5.9.0
    115130     *
    116131     * @param WP_REST_REQUEST $request Full details about the request.
    117      * @return WP_REST_Response|WP_Error The parsed details as a response object, or an error.
     132     * @return WP_REST_Response|WP_Error The parsed details as a response object. WP_Error if there are errors.
    118133     */
    119134    public function parse_url_details( $request ) {
     
    163178         * Filters the URL data for the response.
    164179         *
    165          * @param WP_REST_Response $response The response object.
    166          * @param string           $url      The requested URL.
    167          * @param WP_REST_Request  $request  Request object.
    168          * @param array            $remote_url_response HTTP response body from the remote URL.
     180         * @since 5.9.0
     181         *
     182         * @param WP_REST_Response $response            The response object.
     183         * @param string           $url                 The requested URL.
     184         * @param WP_REST_Request  $request             Request object.
     185         * @param string           $remote_url_response HTTP response body from the remote URL.
    169186         */
    170187        return apply_filters( 'rest_prepare_url_details', $response, $url, $request, $remote_url_response );
     
    176193     * @since 5.9.0
    177194     *
    178      * @return WP_Error|bool True if the request has access, or WP_Error object.
     195     * @return WP_Error|bool True if the request has permission, else WP_Error.
    179196     */
    180197    public function permissions_check() {
     
    201218     * @since 5.9.0
    202219     *
    203      * @param string $url The website url whose HTML we want to access.
    204      * @return string|WP_Error The HTTP response from the remote URL, or an error.
     220     * @param string $url The website URL whose HTML to access.
     221     * @return string|WP_Error The HTTP response from the remote URL on success.
     222     *                         WP_Error if no response or no content.
    205223     */
    206224    private function get_remote_url( $url ) {
     
    227245         * Can be used to adjust response size limit and other WP_Http::request args.
    228246         *
    229          * @param array $args Arguments used for the HTTP request
    230          * @param string $url The attempted URL.
     247         * @since 5.9.0
     248         *
     249         * @param array  $args Arguments used for the HTTP request.
     250         * @param string $url  The attempted URL.
    231251         */
    232252        $args = apply_filters( 'rest_url_details_http_request_args', $args, $url );
     
    236256        if ( WP_Http::OK !== wp_remote_retrieve_response_code( $response ) ) {
    237257            // Not saving the error response to cache since the error might be temporary.
    238             return new WP_Error( 'no_response', __( 'URL not found. Response returned a non-200 status code for this URL.' ), array( 'status' => WP_Http::NOT_FOUND ) );
     258            return new WP_Error(
     259                'no_response',
     260                __( 'URL not found. Response returned a non-200 status code for this URL.' ),
     261                array( 'status' => WP_Http::NOT_FOUND )
     262            );
    239263        }
    240264
     
    242266
    243267        if ( empty( $remote_body ) ) {
    244             return new WP_Error( 'no_content', __( 'Unable to retrieve body from response at this URL.' ), array( 'status' => WP_Http::NOT_FOUND ) );
     268            return new WP_Error(
     269                'no_content',
     270                __( 'Unable to retrieve body from response at this URL.' ),
     271                array( 'status' => WP_Http::NOT_FOUND )
     272            );
    245273        }
    246274
     
    254282     *
    255283     * @param string $html The HTML from the remote website at URL.
    256      * @return string The title tag contents on success, or an empty string.
     284     * @return string The title tag contents on success. Empty string if not found.
    257285     */
    258286    private function get_title( $html ) {
     
    260288        preg_match( $pattern, $html, $match_title );
    261289
    262         $title = ! empty( $match_title[1] ) && is_string( $match_title[1] ) ? trim( $match_title[1] ) : '';
    263 
    264         if ( empty( $title ) ) {
     290        if ( empty( $match_title[1] ) || ! is_string( $match_title[1] ) ) {
    265291            return '';
    266292        }
     293
     294        $title = trim( $match_title[1] );
    267295
    268296        return $this->prepare_metadata_for_output( $title );
     
    276304     * @param string $html The HTML from the remote website at URL.
    277305     * @param string $url  The target website URL.
    278      * @return string The icon URI on success, or an empty string.
     306     * @return string The icon URI on success. Empty string if not found.
    279307     */
    280308    private function get_icon( $html, $url ) {
     
    282310        $pattern = '#<link\s[^>]*rel=(?:[\"\']??)\s*(?:icon|shortcut icon|icon shortcut)\s*(?:[\"\']??)[^>]*\/?>#isU';
    283311        preg_match( $pattern, $html, $element );
    284         $element = ! empty( $element[0] ) && is_string( $element[0] ) ? trim( $element[0] ) : '';
    285         if ( empty( $element ) ) {
     312        if ( empty( $element[0] ) || ! is_string( $element[0] ) ) {
    286313            return '';
    287314        }
     315        $element = trim( $element[0] );
    288316
    289317        // Get the icon's href value.
    290318        $pattern = '#href=([\"\']??)([^\" >]*?)\\1[^>]*#isU';
    291319        preg_match( $pattern, $element, $icon );
    292         $icon = ! empty( $icon[2] ) && is_string( $icon[2] ) ? trim( $icon[2] ) : '';
    293         if ( empty( $icon ) ) {
     320        if ( empty( $icon[2] ) || ! is_string( $icon[2] ) ) {
    294321            return '';
    295322        }
     323        $icon = trim( $icon[2] );
    296324
    297325        // If the icon is a data URL, return it.
     
    320348     *
    321349     * @param array $meta_elements {
    322      *     A multi-dimensional indexed array on success, or empty array.
     350     *     A multi-dimensional indexed array on success, else empty array.
    323351     *
    324352     *     @type string[] 0 Meta elements with a content attribute.
     
    326354     *     @type string[] 2 Content attribute's value for each meta element.
    327355     * }
    328      * @return string The meta description contents on success, or an empty string.
     356     * @return string The meta description contents on success. Empty string if not found.
    329357     */
    330358    private function get_description( $meta_elements ) {
     
    334362        }
    335363
    336         $description = $this->get_metadata_from_meta_element( $meta_elements, 'name', '(?:description|og:description)' );
     364        $description = $this->get_metadata_from_meta_element(
     365            $meta_elements,
     366            'name',
     367            '(?:description|og:description)'
     368        );
    337369
    338370        // Bail out if description not found.
     
    345377
    346378    /**
    347      * Parses the Open Graph Image from the provided HTML.
     379     * Parses the Open Graph (OG) Image from the provided HTML.
    348380     *
    349381     * See: https://ogp.me/.
     
    352384     *
    353385     * @param array  $meta_elements {
    354      *     A multi-dimensional indexed array on success, or empty array.
     386     *     A multi-dimensional indexed array on success, else empty array.
    355387     *
    356388     *     @type string[] 0 Meta elements with a content attribute.
     
    359391     * }
    360392     * @param string $url The target website URL.
    361      * @return string The OG image on success, or empty string.
     393     * @return string The OG image on success. Empty string if not found.
    362394     */
    363395    private function get_image( $meta_elements, $url ) {
    364         $image = $this->get_metadata_from_meta_element( $meta_elements, 'property', '(?:og:image|og:image:url)' );
     396        $image = $this->get_metadata_from_meta_element(
     397            $meta_elements,
     398            'property',
     399            '(?:og:image|og:image:url)'
     400        );
    365401
    366402        // Bail out if image not found.
     
    426462     * @param string $key  The cache key under which to store the value.
    427463     * @param string $data The data to be stored at the given cache key.
    428      * @return bool True when transient set. False if fails.
     464     * @return bool True when transient set. False if not set.
    429465     */
    430466    private function set_cache( $key, $data = '' ) {
     
    437473         * of the data retrieved for the given URL.
    438474         *
    439          * @param int $ttl the time until cache expiration in seconds.
     475         * @since 5.9.0
     476         *
     477         * @param int $ttl The time until cache expiration in seconds.
    440478         */
    441479        $cache_expiration = apply_filters( 'rest_url_details_cache_expiration', $ttl );
     
    450488     *
    451489     * @param string $html The string of HTML to parse.
    452      * @return string The `<head>..</head>` section on success, or original HTML.
     490     * @return string The `<head>..</head>` section on success. Given `$html` if not found.
    453491     */
    454492    private function get_document_head( $html ) {
     
    488526     * @param string $html The string of HTML to be parsed.
    489527     * @return array {
    490      *     A multi-dimensional indexed array on success, or empty array.
     528     *     A multi-dimensional indexed array on success, else empty array.
    491529     *
    492530     *     @type string[] 0 Meta elements with a content attribute.
     
    568606     *
    569607     * @param array  $meta_elements {
    570      *     A multi-dimensional indexed array on success, or empty array.
     608     *     A multi-dimensional indexed array on success, else empty array.
    571609     *
    572610     *     @type string[] 0 Meta elements with a content attribute.
     
    574612     *     @type string[] 2 Content attribute's value for each meta element.
    575613     * }
    576      * @param string $attr Attribute that identifies the element with the target metadata.
     614     * @param string $attr       Attribute that identifies the element with the target metadata.
    577615     * @param string $attr_value The attribute's value that identifies the element with the target metadata.
    578      * @return string The metadata on success, or an empty string.
     616     * @return string The metadata on success. Empty string if not found.
    579617     */
    580618    private function get_metadata_from_meta_element( $meta_elements, $attr, $attr_value ) {
Note: See TracChangeset for help on using the changeset viewer.