Skip to content

Commit

Permalink
Filtered the WordPress REST API Index to hide CoCart namespaces and r…
Browse files Browse the repository at this point in the history
…outes
  • Loading branch information
seb86 committed Dec 17, 2023
1 parent 5f3f4e6 commit 45723d9
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
63 changes: 63 additions & 0 deletions includes/class-cocart-security.php
@@ -0,0 +1,63 @@
<?php
/**
* CoCart Security
*
* Responsible for added protection.
*
* @author Sébastien Dumont
* @package CoCart\Classes
* @since 3.7.10 Introduced.
* @license GPL-2.0+
*/

if ( ! defined( 'ABSPATH' ) ) {
exit;
}

class CoCart_Security {

/**
* Setup class.
*
* @access public
*/
public function __construct() {
add_filter( 'rest_index', array( $this, 'hide_from_rest_index' ) );
}

/**
* Hide any CoCart namespace and routes from showing in the WordPress REST API Index.
*
* @access public
*
* @param WP_REST_Response $response Response data.
*
* @return object $response Altered response.
*/
public function hide_from_rest_index( $response ) {
// Check if WP_DEBUG is not defined or is false.
if ( ! defined( 'WP_DEBUG' ) || ( defined( 'WP_DEBUG' ) && WP_DEBUG !== true ) ) {

// Loop through each registered route
foreach ( $response->data['routes'] as $route => $endpoints ) {
// Check if the current namespace matches any CoCart namespace.
if ( ! empty( $route ) && strpos( $route, 'cocart' ) !== false ) {
unset( $response->data['routes'][ $route ] );
}
}

// Loop through each registered namespace.
foreach ( $response->data['namespaces'] as $key => $namespace ) {
// Check if the current namespace matches any CoCart namespace.
if ( ! empty( $namespace ) && strpos( $namespace, 'cocart' ) !== false ) {
unset( $response->data['namespaces'][ $key ] );
}
}
}

return $response;
} // END hide_from_rest_index()

} // END class

return new CoCart_Security();
3 changes: 2 additions & 1 deletion includes/class-cocart.php
Expand Up @@ -337,10 +337,11 @@ public static function deactivate_plugin() {
* @access public
* @static
* @since 2.6.0
* @version 3.0.0
* @version 3.10.0
*/
public static function load_rest_api() {
include_once COCART_ABSPATH . 'includes/class-cocart-rest-api.php';
include_once COCART_ABSPATH . 'includes/class-cocart-security.php';
} // END load_rest_api()

/**
Expand Down

0 comments on commit 45723d9

Please sign in to comment.