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