Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add WP CLI commands for Caching & Skip404 #97

Merged
merged 2 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 24 additions & 9 deletions includes/CacheManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,21 @@
* Cache manager.
*/
class CacheManager {

/**
* The option name where the cache level is stored.
*
* @var string
*/
public const OPTION_CACHE_LEVEL = 'newfold_cache_level';

/**
* Allowed cache level values.
*
* @var array
*/
public const VALID_CACHE_LEVELS = array( 0, 1, 2, 3 );

/**
* Dependency injection container.
*
Expand Down Expand Up @@ -57,20 +72,20 @@ public function registeredCacheTypes() {
* @return array
*/
public function enabledCacheTypes() {
$cacheTypes = array();
$default_cache_types = array( 'browser', 'skip404' );

if ( $this->container->has( 'cache_types' ) ) {
$providedTypes = $this->container->get( 'cache_types' );
if ( is_array( $providedTypes ) ) {
$cacheTypes = array_intersect(
array_map( 'strtolower', $providedTypes ),
$this->registeredCacheTypes()
);
}
$provided_types = $this->container->get( 'cache_types' );
} else {
$provided_types = $default_cache_types;
}

return $cacheTypes;
return is_array( $provided_types )
? array_intersect( array_map( 'strtolower', $provided_types ), $this->registeredCacheTypes() )
: $default_cache_types;
}


/**
* Get an array of page cache type instances based on the enabled cache types.
*
Expand Down
4 changes: 2 additions & 2 deletions includes/CacheTypes/Browser.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
namespace NewfoldLabs\WP\Module\Performance\CacheTypes;

use NewfoldLabs\WP\Module\Performance\OptionListener;
use NewfoldLabs\WP\Module\Performance\Performance;
use NewfoldLabs\WP\ModuleLoader\Container;
use WP_Forge\WP_Htaccess_Manager\htaccess;
use NewfoldLabs\WP\Module\Performance\CacheExclusion;
use NewfoldLabs\WP\Module\Performance\CacheManager;

use function NewfoldLabs\WP\Module\Performance\getCacheLevel;
use function WP_Forge\WP_Htaccess_Manager\removeMarkers;
Expand Down Expand Up @@ -38,7 +38,7 @@ public static function shouldEnable( Container $container ) {
*/
public function __construct() {

new OptionListener( Performance::OPTION_CACHE_LEVEL, array( __CLASS__, 'maybeAddRules' ) );
new OptionListener( CacheManager::OPTION_CACHE_LEVEL, array( __CLASS__, 'maybeAddRules' ) );

new OptionListener( CacheExclusion::OPTION_CACHE_EXCLUSION, array( __CLASS__, 'exclusionChange' ) );

Expand Down
4 changes: 2 additions & 2 deletions includes/CacheTypes/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@

use NewfoldLabs\WP\Module\Performance\Concerns\Purgeable;
use NewfoldLabs\WP\Module\Performance\OptionListener;
use NewfoldLabs\WP\Module\Performance\Performance;
use NewfoldLabs\WP\ModuleLoader\Container;
use NewfoldLabs\WP\Module\Performance\CacheExclusion;
use NewfoldLabs\WP\Module\Performance\CacheManager;
use WP_Forge\WP_Htaccess_Manager\htaccess;
use wpscholar\Url;

Expand Down Expand Up @@ -49,7 +49,7 @@ public static function shouldEnable( Container $container ) {
*/
public function __construct() {

new OptionListener( Performance::OPTION_CACHE_LEVEL, array( __CLASS__, 'maybeAddRules' ) );
new OptionListener( CacheManager::OPTION_CACHE_LEVEL, array( __CLASS__, 'maybeAddRules' ) );
new OptionListener( CacheExclusion::OPTION_CACHE_EXCLUSION, array( __CLASS__, 'exclusionChange' ) );

add_action( 'init', array( $this, 'maybeGeneratePageCache' ) );
Expand Down
8 changes: 6 additions & 2 deletions includes/CacheTypes/Skip404.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace NewfoldLabs\WP\Module\Performance\CacheTypes;

use NewfoldLabs\WP\Module\Performance\OptionListener;
use NewfoldLabs\WP\Module\Performance\Performance;
use NewfoldLabs\WP\ModuleLoader\Container;

use function NewfoldLabs\WP\Module\Performance\getSkip404Option;
Expand All @@ -20,6 +19,11 @@ class Skip404 extends CacheBase {
*/
const MARKER = 'Newfold Skip 404 Handling for Static Files';

/**
* The option name.
*/
public const OPTION_SKIP_404 = 'newfold_skip_404_handling';

/**
* Whether or not the code for this cache type should be loaded.
*
Expand All @@ -36,7 +40,7 @@ public static function shouldEnable( Container $container ) {
*/
public function __construct() {

new OptionListener( Performance::OPTION_SKIP_404, array( __CLASS__, 'maybeAddRules' ) );
new OptionListener( self::OPTION_SKIP_404, array( __CLASS__, 'maybeAddRules' ) );

add_filter( 'newfold_update_htaccess', array( $this, 'onUpdateHtaccess' ) );
}
Expand Down
141 changes: 141 additions & 0 deletions includes/CacheTypes/WPCLI/CacheTypesCommandHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
<?php

namespace NewfoldLabs\WP\Module\Performance\CacheTypes\WPCLI;

use NewfoldLabs\WP\Module\Performance\CacheExclusion;
use NewfoldLabs\WP\Module\Performance\CacheManager;
use NewfoldLabs\WP\Module\Performance\NFD_WPCLI;
use NewfoldLabs\WP\Module\Performance\CacheTypes\Skip404;

/**
* Handles WP-CLI commands for Cache settings.
*/
class CacheTypesCommandHandler {

/**
* Validates cache level.
*
* @param mixed $level The cache level value.
*
* @return int The validated cache level.
*/
private function validate_cache_level( $level ) {
if ( ! is_numeric( $level ) || ! in_array( (int) $level, CacheManager::VALID_CACHE_LEVELS, true ) ) {
NFD_WPCLI::error(
sprintf(
/* translators: %s is the list of valid cache levels. */
__( 'Invalid cache level. Use one of the following: %s.', 'wp-module-performance' ),
implode( ', ', CacheManager::VALID_CACHE_LEVELS )
)
);
}
return (int) $level;
}

/**
* Toggles the newfold_cache_level setting.
*
* ## OPTIONS
*
* <level>
* : Set cache level (0, 1, 2, or 3).
*
* ## EXAMPLES
*
* wp nfd performance cache level 2
*
* @param array $args Positional arguments.
*
* @return void
*/
public function level( $args ) {
if ( ! isset( $args[0] ) ) {
NFD_WPCLI::error(
sprintf(
/* translators: %s is the list of valid cache levels. */
__( 'A value for cache level is required. Use one of the following: %s.', 'wp-module-performance' ),
implode( ', ', CacheManager::VALID_CACHE_LEVELS )
)
);
}
$level = $this->validate_cache_level( $args[0] );
update_option( CacheManager::OPTION_CACHE_LEVEL, $level );
NFD_WPCLI::success(
sprintf(
/* translators: %s is the new cache level. */
__( "Setting 'newfold_cache_level' has been set to '%s'.", 'wp-module-performance' ),
$level
)
);
}

/**
* Toggles the newfold_skip_404_handling setting.
*
* ## OPTIONS
*
* <status>
* : Enable or disable skipping 404 handling. Accepts 'true' or 'false'.
*
* ## EXAMPLES
*
* wp nfd performance cache skip_404 true
* wp nfd performance cache skip_404 false
*
* @param array $args Positional arguments.
*
* @return void
*/
public function skip_404( $args ) {
if ( ! isset( $args[0] ) || ! in_array( strtolower( $args[0] ), array( 'true', 'false' ), true ) ) {
NFD_WPCLI::error( __( "Invalid value. Use 'true' or 'false' for skip_404 handling.", 'wp-module-performance' ) );
}
$status = filter_var( $args[0], FILTER_VALIDATE_BOOLEAN );
update_option( Skip404::OPTION_SKIP_404, $status );
NFD_WPCLI::success(
sprintf(
/* translators: %s is the new boolean status. */
__( "Setting 'newfold_skip_404_handling' has been set to '%s'.", 'wp-module-performance' ),
$status ? 'true' : 'false'
)
);
}

/**
* Updates the cache exclusion list.
*
* ## OPTIONS
*
* <exclusions>
* : Comma-separated list of URLs or patterns to exclude from caching.
*
* ## EXAMPLES
*
* wp nfd performance cache exclude "checkout,cart,my-account"
*
* @param array $args Positional arguments.
*
* @return void
*/
public function exclude( $args ) {
if ( ! isset( $args[0] ) ) {
NFD_WPCLI::error( __( 'A value for cache exclusion is required.', 'wp-module-performance' ) );
}

// Sanitize the entire input
$value = sanitize_text_field( $args[0] );

// Sanitize each keyword since it's a comma-separated list
$exclusions = array_map( 'trim', explode( ',', $value ) );
$sanitized_value = implode( ',', $exclusions );

update_option( CacheExclusion::OPTION_CACHE_EXCLUSION, $sanitized_value );
NFD_WPCLI::success(
sprintf(
/* translators: %s is the new cache exclusion list. */
__( "Setting 'newfold_cache_exclusion' has been updated to: '%s'.", 'wp-module-performance' ),
$sanitized_value
)
);
}
}
31 changes: 14 additions & 17 deletions includes/Performance.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use NewfoldLabs\WP\Module\Performance\Data\Constants;
use NewfoldLabs\WP\Module\Performance\HealthChecks;
use NewfoldLabs\WP\Module\Performance\LinkPrefetch\LinkPrefetch;
use NFD_CLI;

use function NewfoldLabs\WP\Module\Performance\is_settings_page;

Expand All @@ -20,21 +21,6 @@
*/
class Performance {

/**
* The option name where the cache level is stored.
*
* @var string
*/
const OPTION_CACHE_LEVEL = 'newfold_cache_level';


/**
* The option name where the "Skip WordPress 404 Handling for Static Files" option is stored.
*
* @var string
*/
const OPTION_SKIP_404 = 'newfold_skip_404_handling';

/**
* URL parameter used to purge the entire cache.
*
Expand Down Expand Up @@ -111,7 +97,18 @@ public function __construct( Container $container ) {
*/
public function configureContainer( Container $container ) {

global $is_apache;
$is_apache = false;

// Ensure $is_apache is properly set, with a fallback for WP-CLI environment
if ( NFD_WPCLI::is_executing_wp_cli() ) {
// Attempt to detect Apache based on the SERVER_SOFTWARE header
$is_apache = isset( $_SERVER['SERVER_SOFTWARE'] ) && stripos( $_SERVER['SERVER_SOFTWARE'], 'apache' ) !== false;

// Check for the existence of an .htaccess file (commonly used in Apache environments)
if ( ! $is_apache && file_exists( ABSPATH . '.htaccess' ) ) {
$is_apache = true;
}
}

$container->set( 'isApache', $is_apache );

Expand All @@ -132,7 +129,7 @@ public function hooks() {

add_action( 'admin_init', array( $this, 'remove_epc_settings' ), 99 );

new OptionListener( self::OPTION_CACHE_LEVEL, array( $this, 'onCacheLevelChange' ) );
new OptionListener( CacheManager::OPTION_CACHE_LEVEL, array( $this, 'onCacheLevelChange' ) );

/**
* On CLI requests, mod_rewrite is unavailable, so it fails to update
Expand Down
2 changes: 2 additions & 0 deletions includes/PerformanceWPCLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use NewfoldLabs\WP\Module\Performance\Images\WPCLI\ImageCommandHandler;
use NewfoldLabs\WP\Module\Performance\LinkPrefetch\WPCLI\LinkPrefetchCommandHandler;
use NewfoldLabs\WP\Module\Performance\CacheTypes\WPCLI\CacheTypesCommandHandler;

/**
* Manages all "wp nfd performance" WP-CLI commands.
Expand All @@ -24,6 +25,7 @@ class PerformanceWPCLI {
private static $commands = array(
'images' => ImageCommandHandler::class,
'link_prefetch' => LinkPrefetchCommandHandler::class,
'cache' => CacheTypesCommandHandler::class,
);

/**
Expand Down
4 changes: 2 additions & 2 deletions includes/RestApi/SettingsController.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php
namespace NewfoldLabs\WP\Module\Performance\RestApi;

use NewfoldLabs\WP\Module\Performance\Performance;
use NewfoldLabs\WP\Module\Performance\CacheTypes\Skip404;

/**
* Class Settings
Expand Down Expand Up @@ -79,7 +79,7 @@ public function set_options( $request ) {

switch ( $field['id'] ) {
case 'skip404':
$result = update_option( Performance::OPTION_SKIP_404, $field['value'] );
$result = update_option( Skip404::OPTION_SKIP_404, $field['value'] );
break;

default:
Expand Down
10 changes: 5 additions & 5 deletions includes/burstSafetyModeFunctions.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

if ( defined( 'BURST_SAFETY_MODE' ) && BURST_SAFETY_MODE ) {
if ( false === $newfold_burst_safety_mode ) {
$current_level = get_option( Performance::OPTION_CACHE_LEVEL );
$current_level = get_option( CacheManager::OPTION_CACHE_LEVEL );
update_option( 'newfold_burst_safety_mode', true );
update_option( 'newfold_burst_safety_mode_site_cache_level', $current_level );
$browser = new Browser();
Expand All @@ -21,8 +21,8 @@
$skip404 = new Skip404();
$skip404::maybeAddRules( true );
}
$responseHeaderManager = new ResponseHeaderManager();
$responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', 3 );
$response_header_manager = new ResponseHeaderManager();
$response_header_manager->addHeader( 'X-Newfold-Cache-Level', 3 );
}
} elseif ( $newfold_burst_safety_mode ) {
$cache_level = get_option( 'newfold_burst_safety_mode_site_cache_level' );
Expand All @@ -32,8 +32,8 @@
$skip404 = new Skip404();
$skip404::maybeAddRules( false );
}
$responseHeaderManager = new ResponseHeaderManager();
$responseHeaderManager->addHeader( 'X-Newfold-Cache-Level', $cache_level );
$response_header_manager = new ResponseHeaderManager();
$response_header_manager->addHeader( 'X-Newfold-Cache-Level', $cache_level );
delete_option( 'newfold_burst_safety_mode' );
delete_option( 'newfold_burst_safety_mode_site_cache_level' );
}
Loading