PluginProbe
Code Snippets / 3.6.3
Code Snippets v3.6.3
3.10.2 3.10.1 3.10.0 3.10.0-beta.2 3.10.0-beta.1 4.0.0-beta.1 3.9.6 trunk 2.10.0 2.10.1 2.12.0 2.12.1 2.13.0 2.13.1 2.13.2 2.13.3 2.14.0 2.14.1 2.14.2 2.14.3 2.14.4 2.14.5 2.14.6 3.0.0 3.0.1 All 64 releases
code-snippets / php / class-active-snippets.php

class-active-snippets.php in Code Snippets 3.6.3, at php/class-active-snippets.php

83 lines 1.8 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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 $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