Skip to content
Open
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
2 changes: 0 additions & 2 deletions src/php/Admin/Menus/Settings_Menu.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
use const Code_Snippets\PLUGIN_VERSION;
use const Code_Snippets\Settings\OPTION_GROUP;
use const Code_Snippets\Settings\OPTION_NAME;
use const Code_Snippets\Settings\CACHE_KEY;

/**
* This class handles the settings admin menu.
Expand Down Expand Up @@ -364,7 +363,6 @@ public function update_network_options() {
// Retrieve the saved options and save them to the database.
$value = map_deep( wp_unslash( $_POST[ OPTION_NAME ] ), 'sanitize_key' );
update_site_option( OPTION_NAME, $value );
wp_cache_delete( CACHE_KEY );

// Add an updated notice.
if ( ! count( get_settings_errors() ) ) {
Expand Down
9 changes: 9 additions & 0 deletions src/php/Flat_Files/Handler_Registry.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,13 @@ public function register_handler( string $type, Snippet_Type_Handler $handler ):
public function get_handler( string $type ): ?Snippet_Type_Handler {
return $this->handlers[ $type ] ?? null;
}

/**
* Gets every registered handler.
*
* @return array<string, Snippet_Type_Handler> Handlers, keyed by type.
*/
public function get_handlers(): array {
return $this->handlers;
}
}
91 changes: 69 additions & 22 deletions src/php/Flat_Files/Snippet_Files.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Code_Snippets\Flat_Files\Interfaces\Snippet_Config_Repository;
use Code_Snippets\Flat_Files\Interfaces\Snippet_Type_Handler;
use Code_Snippets\Model\Snippet;
use function Code_Snippets\clean_active_snippets_cache;
use function Code_Snippets\code_snippets;
use function Code_Snippets\get_snippet;
use function wp_hash;
Expand Down Expand Up @@ -155,17 +156,28 @@ public function activate_snippets( array $valid_snippets, string $table ): void
* @return void
*/
private function write_snippet( Snippet $snippet, string $table, Snippet_Type_Handler $handler ): void {
$hashed_table = self::get_hashed_table_name( $table );
$base_dir = self::get_base_dir( $hashed_table, $handler->get_dir_name() );
$base_dir = $this->write_code_file( $snippet, $table, $handler );
$this->config_repo->update( $base_dir, $snippet );
}

/**
* Write the code file for a snippet.
*
* @param Snippet $snippet Snippet to write.
* @param string $table Snippet database table name.
* @param Snippet_Type_Handler $handler Snippet type handler.
*
* @return string Directory the file was written to.
*/
private function write_code_file( Snippet $snippet, string $table, Snippet_Type_Handler $handler ): string {
$base_dir = self::get_base_dir( self::get_hashed_table_name( $table ), $handler->get_dir_name() );
$this->maybe_create_directory( $base_dir );

$file_path = $this->get_snippet_file_path( $base_dir, $snippet->id, $handler->get_file_extension() );

$contents = $handler->wrap_code( $snippet->code );
$this->fs->put_contents( $file_path, $handler->wrap_code( $snippet->code ), FS_CHMOD_FILE );

$this->fs->put_contents( $file_path, $contents, FS_CHMOD_FILE );

$this->config_repo->update( $base_dir, $snippet );
return $base_dir;
}

/**
Expand Down Expand Up @@ -440,7 +452,7 @@ public static function get_active_snippets_from_flat_files(
'table' => $db->table,
'network' => false,
'priority' => intval( $snippet['priority'] ),
'condition_id' => intval( $snippet['condition_id'] ),
'condition_id' => intval( $snippet['condition_id'] ?? 0 ),
];
}
}
Expand Down Expand Up @@ -481,7 +493,7 @@ public static function get_active_snippets_from_flat_files(
'table' => $db->ms_table,
'network' => true,
'priority' => intval( $snippet['priority'] ),
'condition_id' => intval( $snippet['condition_id'] ),
'condition_id' => intval( $snippet['condition_id'] ?? 0 ),
];
}

Expand Down Expand Up @@ -639,38 +651,73 @@ public function create_all_flat_files( array $settings ): void {
/**
* Create snippet code files and config indexes for all active snippets.
*
* Each index is rebuilt from the database rather than merged into, as snippets
* can be deactivated or deleted while file-based execution is switched off.
*
* @return void
*/
private function create_snippet_flat_files(): void {
$db = code_snippets()->db;
$indexes = [];

$scopes = Snippet::get_all_scopes();

$data = $db->fetch_active_snippets( $scopes );

foreach ( $data as $snippet ) {
$snippet_obj = get_snippet( $snippet['id'], $db->ms_table === $snippet['table'] );
$this->handle_snippet( $snippet_obj, $snippet['table'] );
}
$this->collect_active_snippets( $indexes );

if ( is_multisite() ) {
$sites = get_sites( [ 'fields' => 'ids' ] );
foreach ( $sites as $site_id ) {
switch_to_blog( $site_id );
$db->set_table_vars();

$site_data = $db->fetch_active_snippets( $scopes );
foreach ( $site_data as $snippet ) {
$table_name = $snippet['table'];
$snippet_obj = get_snippet( $snippet['id'], false );
$this->handle_snippet( $snippet_obj, $table_name );
}
$this->collect_active_snippets( $indexes );

restore_current_blog();
}

$db->set_table_vars();
}

foreach ( $indexes as $table => $table_indexes ) {
foreach ( $table_indexes as $base_dir => $snippets ) {
if ( $snippets || $this->fs->is_dir( $base_dir ) ) {
$this->config_repo->save( $base_dir, $snippets );
}
}

clean_active_snippets_cache( $table );
}
}

/**
* Write code files for the active snippets of the current site, and collect their index entries.
*
* @param array<string, array<string, array<int, array<string, mixed>>>> $indexes Index entries, keyed by table and directory.
*
* @return void
*/
private function collect_active_snippets( array &$indexes ): void {
$db = code_snippets()->db;
$tables = is_multisite() ? [ $db->table, $db->ms_table ] : [ $db->table ];

foreach ( $tables as $table ) {
clean_active_snippets_cache( $table, Snippet::get_all_scopes() );

foreach ( $this->handler_registry->get_handlers() as $handler ) {
$base_dir = self::get_base_dir( self::get_hashed_table_name( $table ), $handler->get_dir_name() );
$indexes[ $table ][ $base_dir ] = $indexes[ $table ][ $base_dir ] ?? [];
}
}

foreach ( $db->fetch_active_snippets( Snippet::get_all_scopes() ) as $row ) {
$snippet = get_snippet( $row['id'], $db->ms_table === $row['table'] );
$handler = $this->handler_registry->get_handler( $snippet->type );

if ( 0 === $snippet->id || ! $handler ) {
continue;
}

$base_dir = $this->write_code_file( $snippet, $row['table'], $handler );
$indexes[ $row['table'] ][ $base_dir ][ $snippet->id ] = $snippet->get_fields();
}
}

/**
Expand Down
17 changes: 17 additions & 0 deletions src/php/Settings/settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,23 @@ function register_plugin_settings() {

add_action( 'admin_init', __NAMESPACE__ . '\\register_plugin_settings' );

/**
* Clear the cached settings once new values are written.
*
* Saving runs the values through sanitize_settings(), which caches the
* previous values before the option is updated.
*
* @return void
*/
function clear_settings_cache() {
wp_cache_delete( CACHE_KEY, CACHE_GROUP );
}

add_action( 'add_option_' . OPTION_NAME, __NAMESPACE__ . '\\clear_settings_cache' );
add_action( 'update_option_' . OPTION_NAME, __NAMESPACE__ . '\\clear_settings_cache' );
add_action( 'add_site_option_' . OPTION_NAME, __NAMESPACE__ . '\\clear_settings_cache' );
add_action( 'update_site_option_' . OPTION_NAME, __NAMESPACE__ . '\\clear_settings_cache' );

/**
* Determine whether a setting field should be rendered.
*
Expand Down
181 changes: 181 additions & 0 deletions tests/unit/Flat_Files/Snippet_Files_Test.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,181 @@
<?php

namespace Code_Snippets\Flat_Files;

use Code_Snippets\Model\Snippet;
use Code_Snippets\UnitTestCase;
use function Code_Snippets\clean_active_snippets_cache;
use function Code_Snippets\code_snippets;
use function Code_Snippets\deactivate_snippet;
use function Code_Snippets\delete_snippet;
use function Code_Snippets\save_snippet;

/**
* Tests for writing and reading snippet flat files.
*
* @group flat-files
*/
class Snippet_Files_Test extends UnitTestCase {

/**
* Whether the flat-files directory existed before the test.
*
* @var bool
*/
private bool $had_base_dir;

/**
* Whether file-based execution was enabled before the test.
*
* @var bool
*/
private bool $was_active;

/**
* Set up before each test.
*
* @return void
*/
public function set_up() {
parent::set_up();

$this->had_base_dir = is_dir( Snippet_Files::get_base_dir() );
$this->was_active = Snippet_Files::is_active();

// The plugin's own listeners would keep the index in step, hiding a stale entry.
remove_all_actions( 'code_snippets/deactivate_snippet' );
remove_all_actions( 'code_snippets/delete_snippet' );
remove_all_actions( 'code_snippets/trash_snippet' );
}

/**
* Restore the flat-files directory after each test.
*
* @return void
*/
public function tear_down() {
if ( ! $this->was_active ) {
$this->build_snippet_files()->create_all_flat_files( $this->settings( false ) );
}

if ( ! $this->had_base_dir ) {
( new WP_Filesystem_Adapter() )->rmdir( Snippet_Files::get_base_dir(), true );
}

parent::tear_down();
}

/**
* Build a Snippet_Files instance writing to the real filesystem.
*
* @return Snippet_Files
*/
private function build_snippet_files(): Snippet_Files {
$fs = new WP_Filesystem_Adapter();

return new Snippet_Files( code_snippets()->snippet_handler_registry, $fs, new Flat_File_Config_Repository( $fs ) );
}

/**
* Directory holding the index of PHP snippets for the site table.
*
* @return string
*/
private function php_dir(): string {
return Snippet_Files::get_base_dir( Snippet_Files::get_hashed_table_name( code_snippets()->db->table ), 'php' );
}

/**
* IDs listed in the index of PHP snippets for the site table.
*
* @return int[]
*/
private function indexed_ids(): array {
return array_keys( ( new Flat_File_Config_Repository( new WP_Filesystem_Adapter() ) )->load( $this->php_dir() ) );
}

/**
* Settings data with file-based execution switched on or off.
*
* @param bool $enabled Whether file-based execution is enabled.
*
* @return array<string, array<string, bool>>
*/
private function settings( bool $enabled ): array {
return [ 'general' => [ 'enable_flat_files' => $enabled ] ];
}

/**
* Save an active snippet.
*
* @param string $name Snippet name.
*
* @return Snippet
*/
private function active_snippet( string $name ): Snippet {
return save_snippet(
new Snippet(
[
'name' => $name,
'code' => '/* test */',
'scope' => 'global',
'active' => true,
]
)
);
}

/**
* Snippets switched off or deleted while file-based execution was off are left out when it is switched on again.
*
* @return void
*/
public function test_enabling_rebuilds_the_index_from_active_snippets(): void {
$kept = $this->active_snippet( 'Kept' );
$deactivated = $this->active_snippet( 'Deactivated while off' );
$deleted = $this->active_snippet( 'Deleted while off' );

$snippet_files = $this->build_snippet_files();
$snippet_files->create_all_flat_files( $this->settings( true ) );

$this->assertContains( $deactivated->id, $this->indexed_ids() );
$this->assertContains( $deleted->id, $this->indexed_ids() );

$snippet_files->create_all_flat_files( $this->settings( false ) );
deactivate_snippet( $deactivated->id );
delete_snippet( $deleted->id );
$snippet_files->create_all_flat_files( $this->settings( true ) );

$this->assertContains( $kept->id, $this->indexed_ids() );
$this->assertNotContains( $deactivated->id, $this->indexed_ids() );
$this->assertNotContains( $deleted->id, $this->indexed_ids() );
}

/**
* An index entry written before snippets had conditions loads with no condition.
*
* @return void
*/
public function test_entry_without_condition_id_loads_without_a_condition(): void {
wp_mkdir_p( $this->php_dir() );

( new Flat_File_Config_Repository( new WP_Filesystem_Adapter() ) )->save(
$this->php_dir(),
[
999 => [
'id' => 999,
'code' => '/* old */',
'scope' => 'global',
'active' => true,
'priority' => 10,
],
]
);

clean_active_snippets_cache( code_snippets()->db->table, [ 'global' ] );

$snippets = array_column( Snippet_Files::get_active_snippets_from_flat_files( [ 'global' ] ), null, 'id' );

$this->assertSame( 0, $snippets[999]['condition_id'] );
}
}
Loading
Loading