Completed
Push — master ( d1e129...9da8d2 )
by
unknown
17:46 queued 10:59
created

Loader::initialize_ui()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace Carbon_Fields\Loader;
4
5
use Carbon_Fields\Container\Repository as ContainerRepository;
6
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
7
use Carbon_Fields\Helper\Helper;
8
use Carbon_Fields\Libraries\Sidebar_Manager\Sidebar_Manager;
9
use Carbon_Fields\Pimple\Container as PimpleContainer;
10
use Carbon_Fields\Service\Legacy_Storage_Service_v_1_5;
11
use Carbon_Fields\Service\Meta_Query_Service;
12
use Carbon_Fields\Service\REST_API_Service;
13
14
/**
15
 * Loader and main initialization
16
 */
17
class Loader {
18
19
	protected $sidebar_manager;
20
21
	protected $container_repository;
22
23
	public function __construct( Sidebar_Manager $sidebar_manager, ContainerRepository $container_repository ) {
24
		$this->sidebar_manager = $sidebar_manager;
25
		$this->container_repository = $container_repository;
26
	}
27
28
	/**
29
	 * Hook the main Carbon Fields initialization functionality.
30
	 */
31
	public function boot() {
32
		if ( ! defined( 'ABSPATH' ) ) {
33
			throw new \Exception( 'Carbon Fields cannot be booted outside of a WordPress environment.' );
34
		}
35
36
		if ( did_action( 'init' ) ) {
37
			throw new \Exception( 'Carbon Fields must be booted before the "init" WordPress action has fired.' );
38
		}
39
40
		include_once( dirname( dirname( __DIR__ ) ) . '/config.php' );
41
		include_once( \Carbon_Fields\DIR . '/core/functions.php' );
42
43
		add_action( 'after_setup_theme', array( $this, 'load_textdomain' ), 9999 );
44
		add_action( 'init', array( $this, 'trigger_fields_register' ), 0 );
45
		add_action( 'carbon_fields_fields_registered', array( $this, 'initialize_containers' ) );
46
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_media_browser' ), 0 );
47
		add_action( 'admin_print_footer_scripts', array( $this, 'enqueue_assets' ), 9 );
48
		add_action( 'admin_print_footer_scripts', array( $this, 'initialize_ui' ), 9999 );
49
		add_action( 'edit_form_after_title', array( $this, 'add_carbon_fields_meta_box_contexts' ) );
50
		add_action( 'wp_ajax_carbon_fields_fetch_association_options', array( $this, 'fetch_association_options' ) );
51
52
		# Enable the legacy storage service
53
		\Carbon_Fields\Carbon_Fields::service( 'legacy_storage' )->enable();
54
55
		# Enable the meta query service
56
		\Carbon_Fields\Carbon_Fields::service( 'meta_query' )->enable();
57
58
		# Enable the REST API service
59
		\Carbon_Fields\Carbon_Fields::service( 'rest_api' )->enable();
60
61
		# Enable post meta revisions service
62
		\Carbon_Fields\Carbon_Fields::service( 'revisions' )->enable();
63
64
		# Initialize sidebar manager
65
		$this->sidebar_manager->boot();
66
	}
67
68
	/**
69
	 * Load the plugin textdomain.
70
	 */
71
	public function load_textdomain() {
72
		$dir = \Carbon_Fields\DIR . '/languages/';
73
		$domain = 'carbon-fields';
74
		$domain_ui = 'carbon-fields-ui';
75
		$locale = get_locale();
76
		$path = $dir . $domain . '-' . $locale . '.mo';
77
		$path_ui = $dir . $domain_ui . '-' . $locale . '.mo';
78
		load_textdomain( $domain, $path );
79
		load_textdomain( $domain_ui, $path_ui );
80
	}
81
82
	/**
83
	 * Load the ui textdomain
84
	 */
85
	public function get_ui_translations() {
86
		$domain ='carbon-fields-ui';
0 ignored issues
show
introduced by
Expected 1 space after "="; 0 found
Loading history...
87
		$translations = get_translations_for_domain( $domain );
88
89
		$locale = array(
90
			'' => array(
91
				'domain' => $domain,
92
				'lang'   => is_admin() ? get_user_locale() : get_locale(),
93
			),
94
		);
95
96
		if ( ! empty( $translations->headers['Plural-Forms'] ) ) {
97
			$locale['']['plural_forms'] = $translations->headers['Plural-Forms'];
98
		}
99
100
		foreach ( $translations->entries as $msgid => $entry ) {
101
			$locale[ $msgid ] = $entry->translations;
102
		}
103
104
		return $locale;
105
	}
106
107
	/**
108
	 * Register containers and fields.
109
	 */
110
	public function trigger_fields_register() {
111
		try {
112
			do_action( 'carbon_fields_register_fields' );
113
			do_action( 'carbon_fields_fields_registered' );
114
		} catch ( Incorrect_Syntax_Exception $e ) {
115
			$callback = '';
116
			foreach ( $e->getTrace() as $trace ) {
117
				$callback .= '<br/>' . ( isset( $trace['file'] ) ? $trace['file'] . ':' . $trace['line'] : $trace['function'] . '()' );
118
			}
119
			wp_die( '<h3>' . $e->getMessage() . '</h3><small>' . $callback . '</small>' );
120
		}
121
	}
122
123
	/**
124
	 * Initialize containers.
125
	 */
126
	public function initialize_containers() {
127
		$this->container_repository->initialize_containers();
128
	}
129
130
	/**
131
	 * Initialize the media browser.
132
	 */
133
	public function enqueue_media_browser() {
134
		wp_enqueue_media();
135
	}
136
137
	/**
138
	 * Returns the rendering context for the assets.
139
	 *
140
	 * @return string
141
	 */
142
	protected function get_assets_context() {
143
		return wp_script_is( 'wp-element' ) ? 'gutenberg' : 'classic';
144
	}
145
146
	/**
147
	 * Returns the suffix that should be applied to the assets.
148
	 *
149
	 * @return string
150
	 */
151
	protected function get_assets_suffix() {
152
		return defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
153
	}
154
155
	/**
156
	 * Registers and enqueues a style.
157
	 *
158
	 * @param  string $src
159
	 * @param  array  $deps
160
	 * @return void
161
	 */
162 View Code Duplication
	protected function enqueue_style( $src, $deps = array() ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
163
		$suffix = $this->get_assets_suffix();
164
		$context = $this->get_assets_context();
165
166
		wp_enqueue_style(
167
			'carbon-fields-' . $src,
168
			\Carbon_Fields\URL . '/build/' . $context . '/' . $src . $suffix . '.css',
169
			$deps,
170
			\Carbon_Fields\VERSION
171
		);
172
	}
173
174
	/**
175
	 * Registers and enqueues a script.
176
	 *
177
	 * @param  string $src
178
	 * @param  array  $deps
179
	 * @return void
180
	 */
181 View Code Duplication
	protected function enqueue_script( $src, $deps = array() ) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
182
		$suffix = $this->get_assets_suffix();
183
		$context = $this->get_assets_context();
184
185
		wp_enqueue_script(
186
			'carbon-fields-' . $src,
187
			\Carbon_Fields\URL . '/build/' . $context . '/' . $src . $suffix . '.js',
188
			$deps,
189
			\Carbon_Fields\VERSION
190
		);
191
	}
192
193
	/**
194
	 * Enqueues the assets.
195
	 *
196
	 * @return void
197
	 */
198
	public function enqueue_assets() {
199
		global $pagenow;
200
201
		$this->enqueue_style( 'core' );
202
		$this->enqueue_style( 'metaboxes' );
203
204
		$this->enqueue_script( 'vendor', array( 'jquery' ) );
205
		$this->enqueue_script( 'core', array( 'carbon-fields-vendor' ) );
206
		$this->enqueue_script( 'metaboxes', array( 'carbon-fields-vendor', 'carbon-fields-core' ) );
207
208
		if ( $this->get_assets_context() === 'gutenberg' ) {
209
			$this->enqueue_style( 'blocks' );
210
			$this->enqueue_script( 'blocks', array( 'carbon-fields-vendor', 'carbon-fields-core' ) );
211
		}
212
213
		wp_add_inline_script( 'carbon-fields-vendor', 'window.cf = window.cf || {}', 'before' );
214
		wp_add_inline_script( 'carbon-fields-vendor', sprintf( 'window.cf.preloaded = %s', wp_json_encode( $this->get_json_data() ) ), 'before' );
215
216
		$revisions = \Carbon_Fields\Carbon_Fields::service( 'revisions' );
217
218
		wp_localize_script( 'carbon-fields-vendor', 'cf', apply_filters( 'carbon_fields_config', array(
219
			'config' => array(
220
				'locale' => $this->get_ui_translations(),
221
				'pagenow' => $pagenow,
222
				'compactInput' => \Carbon_Fields\COMPACT_INPUT,
223
				'compactInputKey' => \Carbon_Fields\COMPACT_INPUT_KEY,
224
				'revisionsInputKey' => $revisions::CHANGE_KEY,
225
			)
226
		) ) );
227
	}
228
229
	/**
230
	 * Trigger the initialization of the UI.
231
	 *
232
	 * @return void
233
	 */
234
	public function initialize_ui() {
235
		?>
236
			<script>
237
				if ( typeof cf.core.initialize === 'function' ) {
238
					cf.core.initialize();
239
				}
240
			</script>
241
		<?php
242
	}
243
244
	/**
245
	 * Add custom meta box contexts
246
	 */
247
	public function add_carbon_fields_meta_box_contexts() {
248
		global $post, $wp_meta_boxes;
249
250
		$context = 'carbon_fields_after_title';
251
		do_meta_boxes( get_current_screen(), $context, $post );
252
	}
253
254
	/**
255
	 * Retrieve containers and sidebars for use in the JS.
256
	 *
257
	 * @return array $carbon_data
258
	 */
259
	public function get_json_data() {
260
		$carbon_data = array(
261
			'blocks' => array(),
262
			'containers' => array(),
263
			'sidebars' => array(),
264
		);
265
266
		$containers = $this->container_repository->get_active_containers();
267
268
		foreach ( $containers as $container ) {
269
			$container_data = $container->to_json( true );
270
271
			if ( is_a($container, '\\Carbon_Fields\\Container\\Block_Container', true ) ) {
0 ignored issues
show
Coding Style introduced by
Expected 1 spaces after opening bracket; 0 found
Loading history...
272
				$carbon_data['blocks'][] = $container_data;
273
			} else {
274
				$carbon_data['containers'][] = $container_data;
275
			}
276
		}
277
278
		$carbon_data['sidebars'] = Helper::get_active_sidebars();
279
280
		return $carbon_data;
281
	}
282
283
	/**
284
	 * Handle association field options fetch.
285
	 *
286
	 * @access public
287
	 *
288
	 * @return array
289
	 */
290
	public function fetch_association_options() {
291
		$page = isset( $_GET['page'] ) ? absint( $_GET['page'] )              : 1;
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
292
		$term = isset( $_GET['term'] ) ? sanitize_text_field( $_GET['term'] ) : '';
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
293
294
		$container_id = $_GET['container_id'];
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
295
		$field_name   = $_GET['field_name'];
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
296
297
		$field = Helper::get_field( null, $container_id, $field_name );
298
299
		return wp_send_json_success( $field->get_options( array(
0 ignored issues
show
Bug introduced by
The method get_options cannot be called on $field (of type boolean).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
300
			'page' => $page,
301
			'term' => $term,
302
		) ) );
303
	}
304
}
305