Make WordPress Core


Ignore:
Timestamp:
09/22/2015 03:13:13 AM (11 years ago)
Author:
wonderboymusic
Message:

HTTP: Add some new Cookie helper functions:

  • wp_remote_retrieve_cookies( $response )
  • wp_remote_retrieve_cookie( $response, $name )
  • wp_remote_retrieve_cookie_value( $response, $name )

Adds unit tests.

Props johnbillion.
Fixes #33711.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/http-functions.php

    r33879 r34369  
    284284
    285285    return $response['body'];
     286}
     287
     288/**
     289 * Retrieve only the body from the raw response.
     290 *
     291 * @since 4.4.0
     292 *
     293 * @param array $response HTTP response.
     294 * @return array An array of `WP_Http_Cookie` objects from the response. Empty array if there are none, or the response is a WP_Error.
     295 */
     296function wp_remote_retrieve_cookies( $response ) {
     297    if ( is_wp_error( $response ) || empty( $response['cookies'] ) ) {
     298        return array();
     299    }
     300
     301    return $response['cookies'];
     302}
     303
     304/**
     305 * Retrieve a single cookie by name from the raw response.
     306 *
     307 * @since 4.4.0
     308 *
     309 * @param array  $response HTTP response.
     310 * @param string $name     The name of the cookie to retrieve.
     311 * @return WP_Http_Cookie|string The `WP_Http_Cookie` object. Empty string if the cookie isn't present in the response.
     312 */
     313function wp_remote_retrieve_cookie( $response, $name ) {
     314    $cookies = wp_remote_retrieve_cookies( $response );
     315
     316    if ( empty( $cookies ) ) {
     317        return '';
     318    }
     319
     320    foreach ( $cookies as $cookie ) {
     321        if ( $cookie->name === $name ) {
     322            return $cookie;
     323        }
     324    }
     325
     326    return '';
     327}
     328
     329/**
     330 * Retrieve a single cookie's value by name from the raw response.
     331 *
     332 * @since 4.4.0
     333 *
     334 * @param array  $response HTTP response.
     335 * @param string $name     The name of the cookie to retrieve.
     336 * @return string The value of the cookie. Empty string if the cookie isn't present in the response.
     337 */
     338function wp_remote_retrieve_cookie_value( $response, $name ) {
     339    $cookie = wp_remote_retrieve_cookie( $response, $name );
     340
     341    if ( ! is_a( $cookie, 'WP_Http_Cookie' ) ) {
     342        return '';
     343    }
     344
     345    return $cookie->value;
    286346}
    287347
Note: See TracChangeset for help on using the changeset viewer.