| 1 |
<?php |
| 2 |
namespace Code_Snippets; |
| 3 |
|
| 4 |
class Snippet_Config_Repository implements Snippet_Config_Repository_Interface { |
| 5 |
|
| 6 |
const CONFIG_FILE_NAME = 'index.php'; |
| 7 |
|
| 8 |
private File_System_Interface $fs; |
| 9 |
|
| 10 |
public function __construct( File_System_Interface $fs ) { |
| 11 |
$this->fs = $fs; |
| 12 |
} |
| 13 |
|
| 14 |
public function load( string $base_dir ): array { |
| 15 |
$config_file_path = trailingslashit( $base_dir ) . static::CONFIG_FILE_NAME; |
| 16 |
|
| 17 |
if ( is_file( $config_file_path ) ) { |
| 18 |
if ( function_exists( 'opcache_invalidate' ) ) { |
| 19 |
opcache_invalidate( $config_file_path, true ); |
| 20 |
} |
| 21 |
return require $config_file_path; |
| 22 |
} |
| 23 |
return []; |
| 24 |
} |
| 25 |
|
| 26 |
public function save( string $base_dir, array $active_snippets ): void { |
| 27 |
$config_file_path = trailingslashit( $base_dir ) . static::CONFIG_FILE_NAME; |
| 28 |
|
| 29 |
ksort( $active_snippets ); |
| 30 |
|
| 31 |
$file_content = "<?php\n\nif ( ! defined( 'ABSPATH' ) ) { return; }\n\nreturn " . |
| 32 |
var_export( $active_snippets, true ) . |
| 33 |
";\n"; |
| 34 |
|
| 35 |
$this->fs->put_contents( $config_file_path, $file_content, FS_CHMOD_FILE ); |
| 36 |
|
| 37 |
if ( is_file( $config_file_path ) ) { |
| 38 |
if ( function_exists( 'opcache_invalidate' ) ) { |
| 39 |
opcache_invalidate( $config_file_path, true ); |
| 40 |
} |
| 41 |
} |
| 42 |
} |
| 43 |
|
| 44 |
public function update( string $base_dir, Snippet $snippet, ?bool $remove = false ): void { |
| 45 |
$active_snippets = $this->load( $base_dir ); |
| 46 |
|
| 47 |
if ( $remove ) { |
| 48 |
unset( $active_snippets[ $snippet->id ] ); |
| 49 |
} else { |
| 50 |
$active_snippets[ $snippet->id ] = $snippet->get_fields(); |
| 51 |
} |
| 52 |
|
| 53 |
$this->save( $base_dir, $active_snippets ); |
| 54 |
} |
| 55 |
} |
| 56 |
|