| 1 |
<?php |
| 2 |
|
| 3 |
namespace Code_Snippets; |
| 4 |
|
| 5 |
/** |
| 6 |
* Class for loading active snippets of various types. |
| 7 |
* |
| 8 |
* @package Code_Snippets |
| 9 |
*/ |
| 10 |
class Active_Snippets { |
| 11 |
|
| 12 |
/** |
| 13 |
* Cached list of active snippets. |
| 14 |
* |
| 15 |
* @var Snippet[] |
| 16 |
*/ |
| 17 |
private array $active_snippets = []; |
| 18 |
|
| 19 |
/** |
| 20 |
* Class constructor. |
| 21 |
*/ |
| 22 |
public function __construct() { |
| 23 |
add_action( 'init', array( $this, 'init' ) ); |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Initialise class functions. |
| 28 |
*/ |
| 29 |
public function init() { |
| 30 |
add_action( 'wp_head', [ $this, 'load_head_content' ] ); |
| 31 |
add_action( 'wp_footer', [ $this, 'load_footer_content' ] ); |
| 32 |
} |
| 33 |
|
| 34 |
/** |
| 35 |
* Fetch active snippets for a given scope, and cache the data in this class. |
| 36 |
* |
| 37 |
* @param string|string[] $scope Snippet scope. |
| 38 |
* |
| 39 |
* @return array[][] |
| 40 |
*/ |
| 41 |
protected function fetch_active_snippets( $scope ) { |
| 42 |
$scope_key = is_array( $scope ) ? implode( '|', $scope ) : $scope; |
| 43 |
|
| 44 |
if ( ! isset( $this->active_snippets[ $scope_key ] ) ) { |
| 45 |
$this->active_snippets[ $scope_key ] = code_snippets()->db->fetch_active_snippets( $scope ); |
| 46 |
} |
| 47 |
|
| 48 |
return $this->active_snippets[ $scope_key ]; |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Print snippet code fetched from the database from a certain scope. |
| 53 |
* |
| 54 |
* @param string $scope Name of scope to print. |
| 55 |
*/ |
| 56 |
private function print_content_snippets( string $scope ) { |
| 57 |
$snippets_list = $this->fetch_active_snippets( [ 'head-content', 'footer-content' ] ); |
| 58 |
|
| 59 |
foreach ( $snippets_list as $snippets ) { |
| 60 |
foreach ( $snippets as $snippet ) { |
| 61 |
if ( $scope === $snippet['scope'] ) { |
| 62 |
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped |
| 63 |
echo "\n", $snippet['code'], "\n"; |
| 64 |
} |
| 65 |
} |
| 66 |
} |
| 67 |
} |
| 68 |
|
| 69 |
/** |
| 70 |
* Print head content snippets. |
| 71 |
*/ |
| 72 |
public function load_head_content() { |
| 73 |
$this->print_content_snippets( 'head-content' ); |
| 74 |
} |
| 75 |
|
| 76 |
/** |
| 77 |
* Print footer content snippets. |
| 78 |
*/ |
| 79 |
public function load_footer_content() { |
| 80 |
$this->print_content_snippets( 'footer-content' ); |
| 81 |
} |
| 82 |
} |
| 83 |
|