Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* Plugin Name: NGINX FastCGI cache purge
* Version: 0.1
* Description: Flush NGINX FastCGI cache purge
* Author: The Shipyard Crew
* Author URI: https://theshipyard.se/
* Plugin URI: https://theshipyard.se/
* Text Domain: nginx-fastcgi-cache-purge
* @package NGINX FastCGI cache purge
*/
if ( ! defined( 'NGINX_CACHE_PATH' ) ) {
define( 'NGINX_CACHE_PATH', '/var/run/nginx-cache' );
}
final class NGINX_FastCGI_cache_purge {
public static $instance = null;
private function __construct() {
add_action( 'edit_post', [ $this, 'purge_cache' ] );
}
/**
* Creates or returns an instance of this class.
*
* @return A single instance of this class.
*/
public static function init() {
if ( self::$instance === null ) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Purge a page from the NGINX FastCGI cache.
*
* @param int $post_id WP_Post ID.
*/
public function purge_cache( $post_id ) {
if ( 'publish' !== get_post_status( $post_id ) ) {
return;
}
$public_post_types = get_post_types([ 'public' => true ]);
$post_type = get_post_type( $post_id );
if ( ! in_array( $post_type, $public_post_types ) ) {
return;
}
$url = get_permalink( $post_id );
if ( ! $url ) {
return;
}
$path = $this->get_cache_path( $url );
if ( $path ) {
$this->flush_cache( $path );
}
}
/**
* Get the path to the cached file from the URL.
*
* @param string $url URL to parse.
*
* @return string path to the cached page.
*/
protected function get_cache_path( $url ) {
if ( ! $url ) {
return false;
}
$url = parse_url( $url );
$hash = md5( $url['scheme'] . 'GET' . $url['host'] . $url['path'] );
$path = trailingslashit( NGINX_CACHE_PATH );
return $path . substr( $hash, -1 ) . '/' . substr( $hash, -3, 2 ) . '/' . $hash;
}
/**
* Flush the cache from the path to the cached file.
*
* @param string $path Path to the cached file to flush.
*
* @return bool True on success or false.
*/
protected function flush_cache( $path ) {
if ( file_exists( $path ) ) {
return unlink( $path );
}
return false;
}
}
NGINX_FastCGI_cache_purge::init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment