Completed
Push — development ( 261752...44c3a4 )
by
unknown
02:39
created

Loader::enqueue_scripts()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 77
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Importance

Changes 9
Bugs 1 Features 2
Metric Value
cc 3
eloc 56
nc 4
nop 0
dl 0
loc 77
rs 8.9342
c 9
b 1
f 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Carbon_Fields\Loader;
4
5
use Carbon_Fields\Pimple\Container as PimpleContainer;
6
use Carbon_Fields\Container\Repository as ContainerRepository;
7
use Carbon_Fields\Service\Legacy_Storage_Service_v_1_5;
8
use Carbon_Fields\Service\Meta_Query_Service;
9
use Carbon_Fields\Service\REST_API_Service;
10
use Carbon_Fields\Libraries\Sidebar_Manager\Sidebar_Manager;
11
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
12
13
/**
14
 * Loader and main initialization
15
 */
16
class Loader {
17
18
	protected $sidebar_manager;
19
20
	protected $container_repository;
21
22
	public function __construct( Sidebar_Manager $sidebar_manager, ContainerRepository $container_repository ) {
23
		$this->sidebar_manager = $sidebar_manager;
24
		$this->container_repository = $container_repository;
25
	}
26
27
	/**
28
	 * Hook the main Carbon Fields initialization functionality.
29
	 */
30
	public function boot() {
31
		if ( ! defined( 'ABSPATH' ) ) {
32
			throw new \Exception( 'Carbon Fields cannot be booted outside of a WordPress environment.' );
33
		}
34
35
		if ( did_action( 'init' ) ) {
36
			throw new \Exception( 'Carbon Fields must be booted before the "init" WordPress action has fired.' );
37
		}
38
39
		include_once( dirname( dirname( __DIR__ ) ) . '/config.php' );
40
		include_once( \Carbon_Fields\DIR . '/core/functions.php' );
41
42
		add_action( 'after_setup_theme', array( $this, 'load_textdomain' ), 9999 );
43
		add_action( 'init', array( $this, 'trigger_fields_register' ), 0 );
44
		add_action( 'carbon_fields_fields_registered', array( $this, 'initialize_containers' ) );
45
		add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_media_browser' ), 0 );
46
		add_action( 'admin_print_footer_scripts', array( $this, 'enqueue_scripts' ), 0 );
47
		add_action( 'admin_print_footer_scripts', array( $this, 'print_json_data_script' ), 9 );
48
		add_action( 'admin_print_footer_scripts', array( $this, 'print_bootstrap_js' ), 100 );
49
		add_action( 'edit_form_after_title', array( $this, 'add_carbon_fields_meta_box_contexts' ) );
50
51
		# Enable the legacy storage service
52
		\Carbon_Fields\Carbon_Fields::service( 'legacy_storage' )->enable();
53
54
		# Enable the meta query service
55
		\Carbon_Fields\Carbon_Fields::service( 'meta_query' )->enable();
56
57
		# Enable the REST API service
58
		\Carbon_Fields\Carbon_Fields::service( 'rest_api' )->enable();
59
60
		# Initialize sidebar manager
61
		$this->sidebar_manager->boot();
62
	}
63
64
	/**
65
	 * Load the plugin textdomain.
66
	 */
67
	public function load_textdomain() {
68
		$dir = \Carbon_Fields\DIR . '/languages/';
69
		$domain = 'carbon-fields';
70
		$locale = get_locale();
71
		$path = $dir . $domain . '-' . $locale . '.mo';
72
		load_textdomain( $domain, $path );
73
	}
74
75
	/**
76
	 * Register containers and fields.
77
	 */
78
	public function trigger_fields_register() {
79
		try {
80
			do_action( 'carbon_fields_register_fields' );
81
			do_action( 'carbon_fields_fields_registered' );
82
		} catch ( Incorrect_Syntax_Exception $e ) {
83
			$callback = '';
84
			foreach ( $e->getTrace() as $trace ) {
85
				$callback .= '<br/>' . ( isset( $trace['file'] ) ? $trace['file'] . ':' . $trace['line'] : $trace['function'] . '()' );
86
			}
87
			wp_die( '<h3>' . $e->getMessage() . '</h3><small>' . $callback . '</small>' );
88
		}
89
	}
90
91
	/**
92
	 * Initialize containers.
93
	 */
94
	public function initialize_containers() {
95
		$this->container_repository->initialize_containers();
96
	}
97
98
	/**
99
	 * Initialize the media browser.
100
	 */
101
	public function enqueue_media_browser() {
102
		wp_enqueue_media();
103
	}
104
105
	/**
106
	 * Initialize main scripts
107
	 */
108
	public function enqueue_scripts() {
109
		$suffix = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
110
111
		wp_enqueue_style( 'carbon-fields-core', \Carbon_Fields\URL . '/assets/dist/carbon.css', array(), \Carbon_Fields\VERSION );
112
113
		wp_enqueue_script( 'carbon-fields-vendor', \Carbon_Fields\URL . '/assets/dist/carbon.vendor' . $suffix . '.js', array( 'jquery' ), \Carbon_Fields\VERSION );
114
		wp_enqueue_script( 'carbon-fields-core', \Carbon_Fields\URL . '/assets/dist/carbon.core' . $suffix . '.js', array( 'carbon-fields-vendor', 'quicktags', 'editor' ), \Carbon_Fields\VERSION );
115
		wp_enqueue_script( 'carbon-fields-boot', \Carbon_Fields\URL . '/assets/dist/carbon.boot' . $suffix . '.js', array( 'carbon-fields-core' ), \Carbon_Fields\VERSION );
116
117
		wp_localize_script( 'carbon-fields-vendor', 'carbonFieldsL10n', apply_filters( 'carbon_fields_l10n', array(
118
			'container' => array(
119
				'pleaseFillTheRequiredFields' => __( 'Please fill out all required fields highlighted below.', 'carbon-fields' ),
120
				'changesMadeSaveAlert' => __( 'The changes you made will be lost if you navigate away from this page.', 'carbon-fields' ),
121
			),
122
			'field' => array(
123
				'geocodeZeroResults' => __( 'The address could not be found. ', 'carbon-fields' ),
124
				'geocodeNotSuccessful' => __( 'Geocode was not successful for the following reason: ', 'carbon-fields' ),
125
				'mapLocateAddress' => __( 'Locate address on the map:', 'carbon-fields' ),
126
				'minNumItemsNotReached' => __( 'Minimum number of items not reached (%s items)', 'carbon-fields' ),
127
				'maxNumItemsReached' => __( 'Maximum number of items reached (%s items)', 'carbon-fields' ),
128
129
				'complexNoRows' => __( 'There are no %s yet. Click <a href="#">here</a> to add one.', 'carbon-fields' ),
130
				'complexMinNumRowsNotReached' => __( 'Minimum number of rows not reached (%1$d %2$s)', 'carbon-fields' ),
131
				'complexMaxNumRowsExceeded' => __( 'Maximum number of rows exceeded (%1$d %2$s)', 'carbon-fields' ),
132
				'complexAddButton' => _x( 'Add %s', 'Complex field', 'carbon-fields' ),
133
				'complexCloneButton' => _x( 'Clone', 'Complex field', 'carbon-fields' ),
134
				'complexRemoveButton' => _x( 'Remove', 'Complex field', 'carbon-fields' ),
135
				'complexCollapseExpandButton' => _x( 'Collapse/Expand', 'Complex field', 'carbon-fields' ),
136
137
				'messageFormValidationFailed' => __( 'Please fill out all fields correctly. ', 'carbon-fields' ),
138
				'messageRequiredField' => __( 'This field is required. ', 'carbon-fields' ),
139
				'messageChooseOption' => __( 'Please choose an option. ', 'carbon-fields' ),
140
141
				'enterNameOfNewSidebar' => __( 'Please enter the name of the new sidebar:', 'carbon-fields' ),
142
143
				'selectTime' => __( 'Select Time', 'carbon-fields' ),
144
				'selectDate' => __( 'Select Date', 'carbon-fields' ),
145
146
				'associationSelectedItem' => __( '%1$d selected item', 'carbon-fields' ),
147
				'associationSelectedItems' => __( '%1$d selected items', 'carbon-fields' ),
148
				'associationSelectedItemOutOf' => __( '%1$d selected item out of %2$d', 'carbon-fields' ),
149
				'associationSelectedItemsOutOf' => __( '%1$d selected items out of %2$d', 'carbon-fields' ),
150
151
				'colorSelectColor' => __( 'Select a color', 'carbon-fields' ),
152
153
				'noOptions' => __( 'No options.', 'carbon-fields' ),
154
155
				'setShowAll' => __( 'Show all options', 'carbon-fields' ),
156
157
				'searchPlaceholder' => __( 'Search...', 'carbon-fields' ),
158
159
				'editAttachmentUrl' => _x( 'URL', 'WordPress media attachment', 'carbon-fields' ),
160
				'editAttachmentTitle' => _x( 'Title', 'WordPress media attachment', 'carbon-fields' ),
161
				'editAttachmentArtist' => _x( 'Artist', 'WordPress media attachment', 'carbon-fields' ),
162
				'editAttachmentAlbum' => _x( 'Album', 'WordPress media attachment', 'carbon-fields' ),
163
				'editAttachmentCaption' => _x( 'Caption', 'WordPress media attachment', 'carbon-fields' ),
164
				'editAttachmentAlt' => _x( 'Alt Text', 'WordPress media attachment', 'carbon-fields' ),
165
				'editAttachmentDescription' => _x( 'Description', 'WordPress media attachment', 'carbon-fields' ),
166
				'editAttachmentClose' => _x( 'Close', 'WordPress media attachment', 'carbon-fields' ),
167
				'editAttachmentSave' => _x( 'Save', 'WordPress media attachment', 'carbon-fields' ),
168
169
				'oembedNotFound' => _x( 'Not Found', 'oEmbed field', 'carbon-fields' ),
170
171
				'mediaGalleryButtonLabel' => __( 'Add File', 'carbon-fields' ),
172
				'mediaGalleryBrowserTitle' => _x( 'Files', 'WordPress Media Browser', 'carbon-fields' ),
173
				'mediaGalleryBrowserButtonLabel' => _x( 'Select File', 'WordPress Media Browser', 'carbon-fields' ),
174
175
				'fileButtonLabel' => __( 'Select File', 'carbon-fields' ),
176
				'fileBrowserTitle' => _x( 'Files', 'WordPress Media Browser', 'carbon-fields' ),
177
				'fileBrowserButtonLabel' => _x( 'Select File', 'WordPress Media Browser', 'carbon-fields' ),
178
179
				'imageButtonLabel' => __( 'Select Image', 'carbon-fields' ),
180
				'imageBrowserTitle' => _x( 'Images', 'WordPress Media Browser', 'carbon-fields' ),
181
				'imageBrowserButtonLabel' => _x( 'Select Image', 'WordPress Media Browser', 'carbon-fields' ),
182
			),
183
		) ) );
184
	}
185
186
	/**
187
	 * Add custom meta box contexts
188
	 */
189
	public function add_carbon_fields_meta_box_contexts() {
190
		global $post, $wp_meta_boxes;
191
192
		$context = 'carbon_fields_after_title';
193
		foreach ( $wp_meta_boxes as $post_type => $meta_boxes ) {
194
			if ( empty( $meta_boxes[ $context ] ) ) {
195
				continue;
196
			}
197
			do_meta_boxes( get_current_screen(), $context, $post );
198
			unset( $wp_meta_boxes[ $post_type ][ $context ] );
199
		}
200
	}
201
202
	/**
203
	 * Retrieve containers and sidebars for use in the JS.
204
	 *
205
	 * @return array $carbon_data
206
	 */
207
	public function get_json_data() {
208
		global $wp_registered_sidebars;
209
		global $pagenow;
210
211
		$carbon_data = array(
212
			'containers' => array(),
213
			'sidebars' => array(),
214
			'pagenow' => $pagenow,
215
		);
216
217
		$containers = $this->container_repository->get_active_containers();
218
219
		foreach ( $containers as $container ) {
220
			$container_data = $container->to_json( true );
221
222
			$carbon_data['containers'][] = $container_data;
223
		}
224
225
		foreach ( $wp_registered_sidebars as $sidebar ) {
226
			// Check if we have inactive sidebars
227
			if ( isset( $sidebar['class'] ) && strpos( $sidebar['class'], 'inactive-sidebar' ) !== false ) {
228
				continue;
229
			}
230
231
			$carbon_data['sidebars'][] = array(
232
				'name' => $sidebar['name'],
233
				'id'   => $sidebar['id'],
234
			);
235
		}
236
237
		return $carbon_data;
238
	}
239
240
	/**
241
	 * Print the carbon JSON data script.
242
	 */
243
	public function print_json_data_script() {
244
		?>
245
<script type="text/javascript">
246
<!--//--><![CDATA[//><!--
247
var carbon_json = <?php echo wp_json_encode( $this->get_json_data() ); ?>;
248
//--><!]]>
249
</script>
250
		<?php
251
	}
252
253
	/**
254
	 * Print the bootstrap code for the fields.
255
	 */
256
	public function print_bootstrap_js() {
257
		?>
258
		<script type="text/javascript">
259
			if (window['carbon.boot'] && typeof window['carbon.boot'].default === 'function') {
260
				window['carbon.boot'].default();
261
			}
262
		</script>
263
		<?php
264
	}
265
}
266