<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[53333] trunk: REST API: Fixes `/wp/v2/pattern-directory/patterns` endpoint response for `slug` parameter.</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { white-space: pre-line; overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta" style="font-size: 105%">
<dt style="float: left; width: 6em; font-weight: bold">Revision</dt> <dd><a style="font-weight: bold" href="https://core.trac.wordpress.org/changeset/53333">53333</a><script type="application/ld+json">{"@context":"http://schema.org","@type":"EmailMessage","description":"Review this Commit","action":{"@type":"ViewAction","url":"https://core.trac.wordpress.org/changeset/53333","name":"Review Commit"}}</script></dd>
<dt style="float: left; width: 6em; font-weight: bold">Author</dt> <dd>hellofromTonya</dd>
<dt style="float: left; width: 6em; font-weight: bold">Date</dt> <dd>2022-05-02 13:58:48 +0000 (Mon, 02 May 2022)</dd>
</dl>

<pre style='padding-left: 1em; margin: 2em 0; border-left: 2px solid #ccc; line-height: 1.25; font-size: 105%; font-family: sans-serif'>REST API: Fixes `/wp/v2/pattern-directory/patterns` endpoint response for `slug` parameter.

<a href="https://core.trac.wordpress.org/changeset/53218">[53218]</a> introduced a bug of a wrong response from the `wp/v2/pattern-directory/patterns` endpoint with a `slug` parameter. As the response is cached, it can result in an incorrect list of available patterns supported by the current theme.

This commit resolves by:

* Limiting the `slug` to an `array` in the query parameters.
* When set, parsing and sorting the slug(s) and then serializing the sorted query args as part of the hashed transient keys.

Props antonvlasenko, timothyblynjacobs, spacedmonkey, costdev, hellofromTonya.

Follow-up to <a href="https://core.trac.wordpress.org/changeset/53218">[53218]</a>, <a href="https://core.trac.wordpress.org/changeset/53152">[53152]</a>, <a href="https://core.trac.wordpress.org/changeset/51208">[51208]</a>.
Fixes <a href="https://core.trac.wordpress.org/ticket/55617">#55617</a>.</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunksrcwpincludesrestapiendpointsclasswprestpatterndirectorycontrollerphp">trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php</a></li>
<li><a href="#trunktestsphpunittestsrestapirestpatterndirectorycontrollerphp">trunk/tests/phpunit/tests/rest-api/rest-pattern-directory-controller.php</a></li>
<li><a href="#trunktestsqunitfixtureswpapigeneratedjs">trunk/tests/qunit/fixtures/wp-api-generated.js</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunksrcwpincludesrestapiendpointsclasswprestpatterndirectorycontrollerphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php   2022-05-02 13:30:47 UTC (rev 53332)
+++ trunk/src/wp-includes/rest-api/endpoints/class-wp-rest-pattern-directory-controller.php     2022-05-02 13:58:48 UTC (rev 53333)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -119,16 +119,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        $query_args['slug'] = $slug;
</span><span class="cx" style="display: block; padding: 0 10px">                }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                /*
-                * Include a hash of the query args, so that different requests are stored in
-                * separate caches.
-                *
-                * MD5 is chosen for its speed, low-collision rate, universal availability, and to stay
-                * under the character limit for `_site_transient_timeout_{...}` keys.
-                *
-                * @link https://stackoverflow.com/questions/3665247/fastest-hash-for-non-cryptographic-uses
-                */
-               $transient_key = 'wp_remote_block_patterns_' . md5( implode( '-', $query_args ) );
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $transient_key = $this->get_transient_key( $query_args );
</ins><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                /*
</span><span class="cx" style="display: block; padding: 0 10px">                 * Use network-wide transient to improve performance. The locale is the only site
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -337,6 +328,11 @@
</span><span class="cx" style="display: block; padding: 0 10px">                        'minimum'     => 1,
</span><span class="cx" style="display: block; padding: 0 10px">                );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                $query_params['slug'] = array(
+                       'description' => __( 'Limit results to those matching a pattern (slug).' ),
+                       'type'        => 'array',
+               );
+
</ins><span class="cx" style="display: block; padding: 0 10px">                 /**
</span><span class="cx" style="display: block; padding: 0 10px">                 * Filter collection parameters for the block pattern directory controller.
</span><span class="cx" style="display: block; padding: 0 10px">                 *
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -346,4 +342,36 @@
</span><span class="cx" style="display: block; padding: 0 10px">                 */
</span><span class="cx" style="display: block; padding: 0 10px">                return apply_filters( 'rest_pattern_directory_collection_params', $query_params );
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+       /*
+        * Include a hash of the query args, so that different requests are stored in
+        * separate caches.
+        *
+        * MD5 is chosen for its speed, low-collision rate, universal availability, and to stay
+        * under the character limit for `_site_transient_timeout_{...}` keys.
+        *
+        * @link https://stackoverflow.com/questions/3665247/fastest-hash-for-non-cryptographic-uses
+        *
+        * @since 6.0.0
+        *
+        * @param array $query_args Query arguments to generate a transient key from.
+        * @return string Transient key.
+        */
+       protected function get_transient_key( $query_args ) {
+
+               if ( isset( $query_args['slug'] ) ) {
+                       // This is an additional precaution because the "sort" function expects an array.
+                       $query_args['slug'] = wp_parse_list( $query_args['slug'] );
+
+                       // Empty arrays should not affect the transient key.
+                       if ( empty( $query_args['slug'] ) ) {
+                               unset( $query_args['slug'] );
+                       } else {
+                               // Sort the array so that the transient key doesn't depend on the order of slugs.
+                               sort( $query_args['slug'] );
+                       }
+               }
+
+               return 'wp_remote_block_patterns_' . md5( serialize( $query_args ) );
+       }
</ins><span class="cx" style="display: block; padding: 0 10px"> }
</span></span></pre></div>
<a id="trunktestsphpunittestsrestapirestpatterndirectorycontrollerphp"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/phpunit/tests/rest-api/rest-pattern-directory-controller.php</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/phpunit/tests/rest-api/rest-pattern-directory-controller.php  2022-05-02 13:30:47 UTC (rev 53332)
+++ trunk/tests/phpunit/tests/rest-api/rest-pattern-directory-controller.php    2022-05-02 13:58:48 UTC (rev 53333)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -22,6 +22,15 @@
</span><span class="cx" style="display: block; padding: 0 10px">        protected static $contributor_id;
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * An instance of WP_REST_Pattern_Directory_Controller class.
+        *
+        * @since 6.0.0
+        *
+        * @var WP_REST_Pattern_Directory_Controller
+        */
+       private static $controller;
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * Set up class test fixtures.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="cx" style="display: block; padding: 0 10px">         * @since 5.8.0
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -34,6 +43,8 @@
</span><span class="cx" style="display: block; padding: 0 10px">                                'role' => 'contributor',
</span><span class="cx" style="display: block; padding: 0 10px">                        )
</span><span class="cx" style="display: block; padding: 0 10px">                );
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+
+               static::$controller = new WP_REST_Pattern_Directory_Controller();
</ins><span class="cx" style="display: block; padding: 0 10px">         }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -42,7 +53,7 @@
</span><span class="cx" style="display: block; padding: 0 10px">         * @param WP_REST_Response[] $pattern An individual pattern from the REST API response.
</span><span class="cx" style="display: block; padding: 0 10px">         */
</span><span class="cx" style="display: block; padding: 0 10px">        public function assertPatternMatchesSchema( $pattern ) {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $schema     = ( new WP_REST_Pattern_Directory_Controller() )->get_item_schema();
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $schema     = static::$controller->get_item_schema();
</ins><span class="cx" style="display: block; padding: 0 10px">                 $pattern_id = isset( $pattern->id ) ? $pattern->id : '{pattern ID is missing}';
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $this->assertTrue(
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -322,12 +333,11 @@
</span><span class="cx" style="display: block; padding: 0 10px">         * @since 5.8.0
</span><span class="cx" style="display: block; padding: 0 10px">         */
</span><span class="cx" style="display: block; padding: 0 10px">        public function test_prepare_item() {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $controller                   = new WP_REST_Pattern_Directory_Controller();
</del><span class="cx" style="display: block; padding: 0 10px">                 $raw_patterns                 = json_decode( self::get_raw_response( 'browse-all' ) );
</span><span class="cx" style="display: block; padding: 0 10px">                $raw_patterns[0]->extra_field = 'this should be removed';
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $prepared_pattern = $controller->prepare_response_for_collection(
-                       $controller->prepare_item_for_response( $raw_patterns[0], new WP_REST_Request() )
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $prepared_pattern = static::$controller->prepare_response_for_collection(
+                       static::$controller->prepare_item_for_response( $raw_patterns[0], new WP_REST_Request() )
</ins><span class="cx" style="display: block; padding: 0 10px">                 );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $this->assertPatternMatchesSchema( $prepared_pattern );
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -340,12 +350,11 @@
</span><span class="cx" style="display: block; padding: 0 10px">         * @since 5.8.0
</span><span class="cx" style="display: block; padding: 0 10px">         */
</span><span class="cx" style="display: block; padding: 0 10px">        public function test_prepare_item_search() {
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $controller                   = new WP_REST_Pattern_Directory_Controller();
</del><span class="cx" style="display: block; padding: 0 10px">                 $raw_patterns                 = json_decode( self::get_raw_response( 'search' ) );
</span><span class="cx" style="display: block; padding: 0 10px">                $raw_patterns[0]->extra_field = 'this should be removed';
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><del style="background-color: #fdd; text-decoration:none; display:block; padding: 0 10px">-                $prepared_pattern = $controller->prepare_response_for_collection(
-                       $controller->prepare_item_for_response( $raw_patterns[0], new WP_REST_Request() )
</del><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         $prepared_pattern = static::$controller->prepare_response_for_collection(
+                       static::$controller->prepare_item_for_response( $raw_patterns[0], new WP_REST_Request() )
</ins><span class="cx" style="display: block; padding: 0 10px">                 );
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">                $this->assertPatternMatchesSchema( $prepared_pattern );
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -400,6 +409,96 @@
</span><span class="cx" style="display: block; padding: 0 10px">        }
</span><span class="cx" style="display: block; padding: 0 10px"> 
</span><span class="cx" style="display: block; padding: 0 10px">        /**
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+         * Tests if the transient key gets generated correctly.
+        *
+        * @dataProvider data_get_query_parameters
+        *
+        * @covers WP_REST_Pattern_Directory_Controller::get_transient_key
+        *
+        * @since 6.0.0
+        *
+        * @ticket 55617
+        *
+        * @param array     $parameters_1   Expected query arguments.
+        * @param array     $parameters_2   Actual query arguments.
+        * @param string    $message        An error message to display.
+        * @param bool      $assert_same    Assertion type (assertSame vs assertNotSame).
+        */
+       public function test_transient_keys_get_generated_correctly( $parameters_1, $parameters_2, $message, $assert_same = true ) {
+               $reflection_method = new ReflectionMethod( static::$controller, 'get_transient_key' );
+               $reflection_method->setAccessible( true );
+
+               $result_1 = $reflection_method->invoke( self::$controller, $parameters_1 );
+               $result_2 = $reflection_method->invoke( self::$controller, $parameters_2 );
+
+               $this->assertIsString( $result_1, 'Transient key #1 must be a string.' );
+               $this->assertNotEmpty( $result_1, 'Transient key #1 must not be empty.' );
+
+               $this->assertIsString( $result_2, 'Transient key #2 must be a string.' );
+               $this->assertNotEmpty( $result_2, 'Transient key #2 must not be empty.' );
+
+               if ( $assert_same ) {
+                       $this->assertSame( $result_1, $result_2, $message );
+               } else {
+                       $this->assertNotSame( $result_1, $result_2, $message );
+               }
+
+       }
+
+       /**
+        * @since 6.0.0
+        *
+        * @ticket 55617
+        */
+       public function data_get_query_parameters() {
+               return array(
+                       'same key and empty slugs'              => array(
+                               'parameters_1' => array(
+                                       'parameter_1' => 1,
+                                       'slug'        => array(),
+                               ),
+                               'parameters_2' => array(
+                                       'parameter_1' => 1,
+                               ),
+                               'message'      => 'Empty slugs should not affect the transient key.',
+                       ),
+                       'same key and slugs in different order' => array(
+                               'parameters_1' => array(
+                                       'parameter_1' => 1,
+                                       'slug'        => array( 0, 2 ),
+                               ),
+                               'parameters_2' => array(
+                                       'parameter_1' => 1,
+                                       'slug'        => array( 2, 0 ),
+                               ),
+                               'message'      => 'The order of slugs should not affect the transient key.',
+                       ),
+                       'same key and different slugs'          => array(
+                               'parameters_1' => array(
+                                       'parameter_1' => 1,
+                                       'slug'        => array( 'some_slug' ),
+                               ),
+                               'parameters_2' => array(
+                                       'parameter_1' => 1,
+                                       'slug'        => array( 'some_other_slug' ),
+                               ),
+                               'message'      => 'Transient keys must not match.',
+                               false,
+                       ),
+                       'different keys'                        => array(
+                               'parameters_1' => array(
+                                       'parameter_1' => 1,
+                               ),
+                               'parameters_2' => array(
+                                       'parameter_2' => 1,
+                               ),
+                               'message'      => 'Transient keys must depend on array keys.',
+                               false,
+                       ),
+               );
+       }
+
+       /**
</ins><span class="cx" style="display: block; padding: 0 10px">          * Simulate a successful outbound HTTP requests, to keep tests pure and performant.
</span><span class="cx" style="display: block; padding: 0 10px">         *
</span><span class="cx" style="display: block; padding: 0 10px">         * @param string $action          Pass a case from `get_raw_response()` to determine returned data.
</span></span></pre></div>
<a id="trunktestsqunitfixtureswpapigeneratedjs"></a>
<div class="modfile"><h4 style="background-color: #eee; color: inherit; margin: 1em 0; padding: 1.3em; font-size: 115%">Modified: trunk/tests/qunit/fixtures/wp-api-generated.js</h4>
<pre class="diff"><span>
<span class="info" style="display: block; padding: 0 10px; color: #888">--- trunk/tests/qunit/fixtures/wp-api-generated.js    2022-05-02 13:30:47 UTC (rev 53332)
+++ trunk/tests/qunit/fixtures/wp-api-generated.js      2022-05-02 13:58:48 UTC (rev 53333)
</span><span class="lines" style="display: block; padding: 0 10px; color: #888">@@ -10385,6 +10385,11 @@
</span><span class="cx" style="display: block; padding: 0 10px">                             "type": "integer",
</span><span class="cx" style="display: block; padding: 0 10px">                             "minimum": 1,
</span><span class="cx" style="display: block; padding: 0 10px">                             "required": false
</span><ins style="background-color: #dfd; text-decoration:none; display:block; padding: 0 10px">+                        },
+                        "slug": {
+                            "description": "Limit results to those matching a pattern (slug).",
+                            "type": "array",
+                            "required": false
</ins><span class="cx" style="display: block; padding: 0 10px">                         }
</span><span class="cx" style="display: block; padding: 0 10px">                     }
</span><span class="cx" style="display: block; padding: 0 10px">                 }
</span></span></pre>
</div>
</div>

</body>
</html>