Completed
Push — test/legacy-storage-service ( 13c02e...9939d7 )
by
unknown
02:29
created

Container::admin_hook_scripts()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 0
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
ccs 0
cts 7
cp 0
crap 2
1
<?php
2
3
namespace Carbon_Fields\Container;
4
5
use Carbon_Fields\App;
6
use Carbon_Fields\Field\Field;
7
use Carbon_Fields\Field\Group_Field;
8
use Carbon_Fields\Datastore\Datastore_Interface;
9
use Carbon_Fields\Datastore\Datastore_Holder_Interface;
10
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
11
12
/**
13
 * Base container class.
14
 * Defines the key container methods and their default implementations.
15
 */
16
abstract class Container implements Datastore_Holder_Interface {
17
	/**
18
	 * Where to put a particular tab -- at the head or the tail. Tail by default
19
	 */
20
	const TABS_TAIL = 1;
21
	const TABS_HEAD = 2;
22
23
	/**
24
	 * Stores if the container is active on the current page
25
	 *
26
	 * @see activate()
27
	 * @var bool
28
	 */
29
	protected $active = false;
30
31
	/**
32
	 * List of registered unique field names for this container instance
33
	 *
34
	 * @see verify_unique_field_name()
35
	 * @var array
36
	 */
37
	protected $registered_field_names = array();
38
39
	/**
40
	 * Stores all the container Backbone templates
41
	 *
42
	 * @see factory()
43
	 * @see add_template()
44
	 * @var array
45
	 */
46
	protected $templates = array();
47
48
	/**
49
	 * Tabs available
50
	 */
51
	protected $tabs = array();
52
53
	/**
54
	 * List of default container settings
55
	 *
56
	 * @see init()
57
	 * @var array
58
	 */
59
	public $settings = array();
60
61
	/**
62
	 * Title of the container
63
	 *
64
	 * @var string
65
	 */
66
	public $title = '';
67
68
	/**
69
	 * List of notification messages to be displayed on the front-end
70
	 *
71
	 * @var array
72
	 */
73
	protected $notifications = array();
74
75
	/**
76
	 * List of error messages to be displayed on the front-end
77
	 *
78
	 * @var array
79
	 */
80
	protected $errors = array();
81
82
	/**
83
	 * List of container fields
84
	 *
85
	 * @see add_fields()
86
	 * @var array
87
	 */
88
	protected $fields = array();
89
90
	/**
91
	 * Container datastores. Propagated to all container fields
92
	 *
93
	 * @see set_datastore()
94
	 * @see get_datastore()
95
	 * @var object
96
	 */
97
	protected $datastore;
98
99
	/**
100
	 * Flag whether the datastore is the default one or replaced with a custom one
101
	 *
102
	 * @see set_datastore()
103
	 * @see get_datastore()
104
	 * @var boolean
105
	 */
106
	protected $has_default_datastore = true;
107
108
	/**
109
	 * Normalizes a container type string to an expected format
110
	 *
111
	 * @param string $type
112
	 * @return string $normalized_type
113
	 **/
114
	protected static function normalize_container_type( $type ) {
115
		// backward compatibility: post_meta container used to be called custom_fields
116
		if ( $type === 'custom_fields' ) {
117
			$type = 'post_meta';
118
		}
119
120
		$normalized_type = str_replace( ' ', '_', ucwords( str_replace( '_', ' ', $type ) ) );
121
		return $normalized_type;
122
	}
123
124
	/**
125
	 * Resolves a string-based type to a fully qualified container class name
126
	 *
127
	 * @param string $type
128
	 * @return string $class_name
129
	 **/
130
	protected static function container_type_to_class( $type ) {
131
		$class = __NAMESPACE__ . '\\' . $type . '_Container';
132 View Code Duplication
		if ( ! class_exists( $class ) ) {
133
			Incorrect_Syntax_Exception::raise( 'Unknown container "' . $type . '".' );
134
			$class = __NAMESPACE__ . '\\Broken_Container';
135
		}
136
		return $class;
137
	}
138
139
	/**
140
	 * Create a new container of type $type and name $name.
141
	 *
142
	 * @param string $type
143
	 * @param string $name Human-readable name of the container
144
	 * @return object $container
145
	 **/
146 9
	public static function factory( $type, $name ) {
147 9
		$repository = App::resolve( 'container_repository' );
148 9
		$unique_id = $repository->get_unique_panel_id( $name );
149
		
150 9
		$normalized_type = static::normalize_container_type( $type );
151 9
		$class = static::container_type_to_class( $normalized_type );
152 7
		$container = new $class( $unique_id, $name, $normalized_type );
153 7
		$repository->register_container( $container );
154
155 7
		return $container;
156
	}
157
158
	/**
159
	 * An alias of factory().
160
	 *
161
	 * @see Container::factory()
162
	 **/
163
	public static function make( $type, $name ) {
164
		return static::factory( $type, $name );
165
	}
166
167
	/**
168
	 * Create a new container
169
	 *
170
	 * @param string $unique_id Unique id of the container
171
	 * @param string $title title of the container
172
	 * @param string $type Type of the container
173
	 **/
174 2
	public function __construct( $unique_id, $title, $type ) {
175 2
		App::verify_boot();
176
177 2
		if ( empty( $title ) ) {
178 1
			Incorrect_Syntax_Exception::raise( 'Empty container title is not supported' );
179
		}
180
181 1
		$this->id = $unique_id;
182 1
		$this->title = $title;
183 1
		$this->type = $type;
184 1
	}
185
186
	/**
187
	 * Return whether the container is active
188
	 **/
189
	public function active() {
190
		return $this->active;
191
	}
192
193
	/**
194
	 * Activate the container and trigger an action
195
	 **/
196
	protected function activate() {
197
		$this->active = true;
198
		$this->boot();
199
		do_action( 'crb_container_activated', $this );
200
201
		$fields = $this->get_fields();
202
		foreach ( $fields as $field ) {
203
			$field->activate();
204
		}
205
	}
206
207
	/**
208
	 * Perform instance initialization
209
	 **/
210
	abstract public function init();
211
212
	/**
213
	 * Prints the container Underscore template
214
	 **/
215
	public function template() {
216
		?>
217
		<div class="{{{ classes.join(' ') }}}">
218
			<# _.each(fields, function(field) { #>
219
				<div class="{{{ field.classes.join(' ') }}}">
220
					<label for="{{{ field.id }}}">
221
						{{ field.label }}
222
223
						<# if (field.required) { #>
224
							 <span class="carbon-required">*</span>
225
						<# } #>
226
					</label>
227
228
					<div class="field-holder {{{ field.id }}}"></div>
229
230
					<# if (field.help_text) { #>
231
						<em class="help-text">
232
							{{{ field.help_text }}}
233
						</em>
234
					<# } #>
235
236
					<em class="carbon-error"></em>
237
				</div>
238
			<# }); #>
239
		</div>
240
		<?php
241
	}
242
243
	/**
244
	 * Boot the container once it's attached.
245
	 **/
246
	protected function boot() {
247
		$this->add_template( $this->type, array( $this, 'template' ) );
248
249
		add_action( 'admin_footer', array( get_class(), 'admin_hook_scripts' ), 5 );
250
		add_action( 'admin_footer', array( get_class(), 'admin_hook_styles' ), 5 );
251
	}
252
253
	/**
254
	 * Load the value for each field in the container.
255
	 * Could be used internally during container rendering
256
	 **/
257
	public function load() {
258
		foreach ( $this->fields as $field ) {
259
			$field->load();
260
		}
261
	}
262
263
	/**
264
	 * Called first as part of the container save procedure.
265
	 * Responsible for checking the request validity and
266
	 * calling the container-specific save() method
267
	 *
268
	 * @see save()
269
	 * @see is_valid_save()
270
	 **/
271
	public function _save() {
272
		$param = func_get_args();
273
		if ( call_user_func_array( array( $this, 'is_valid_save' ), $param ) ) {
274
			call_user_func_array( array( $this, 'save' ), $param );
275
		}
276
	}
277
278
	/**
279
	 * Load submitted data and save each field in the container
280
	 *
281
	 * @see is_valid_save()
282
	 **/
283
	public function save( $data = null ) {
284
		foreach ( $this->fields as $field ) {
285
			$field->set_value_from_input( stripslashes_deep( $_POST ) );
1 ignored issue
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
286
			$field->save();
287
		}
288
	}
289
290
	/**
291
	 * Checks whether the current request is valid
292
	 *
293
	 * @return bool
294
	 **/
295
	public function is_valid_save() {
296
		return false;
297
	}
298
299
	/**
300
	 * Called first as part of the container attachment procedure.
301
	 * Responsible for checking it's OK to attach the container
302
	 * and if it is, calling the container-specific attach() method
303
	 *
304
	 * @see attach()
305
	 * @see is_valid_attach()
306
	 **/
307
	public function _attach() {
308
		$param = func_get_args();
309
		if ( call_user_func_array( array( $this, 'is_valid_attach' ), $param ) ) {
310
			call_user_func_array( array( $this, 'attach' ), $param );
311
312
			// Allow containers to activate but not load (useful in cases such as theme options)
313
			if ( $this->should_activate() ) {
314
				$this->activate();
315
			}
316
		}
317
	}
318
319
	/**
320
	 * Attach the container rendering and helping methods
321
	 * to concrete WordPress Action hooks
322
	 **/
323
	public function attach() {}
324
325
	/**
326
	 * Perform checks whether the container should be attached during the current request
327
	 *
328
	 * @return bool True if the container is allowed to be attached
329
	 **/
330
	final public function is_valid_attach() {
331
		$is_valid_attach = $this->is_valid_attach_for_request();
332
		return apply_filters( 'carbon_fields_container_is_valid_attach', $is_valid_attach, $this );
333
	}
334
335
	/**
336
	 * Check container attachment rules against current page request (in admin)
337
	 *
338
	 * @return bool
339
	 **/
340
	abstract protected function is_valid_attach_for_request();
341
342
	/**
343
	 * Check container attachment rules against object id
344
	 *
345
	 * @param int $object_id
346
	 * @return bool
347
	 **/
348
	abstract public function is_valid_attach_for_object( $object_id = null );
349
350
	/**
351
	 * Whether this container is currently viewed.
352
	 **/
353
	public function should_activate() {
354
		return $this->is_valid_attach();
355
	}
356
357
	/**
358
	 * Returns all the Backbone templates
359
	 *
360
	 * @return array
361
	 **/
362
	public function get_templates() {
363
		return $this->templates;
364
	}
365
366
	/**
367
	 * Adds a new Backbone template
368
	 **/
369
	protected function add_template( $name, $callback ) {
370
		$this->templates[ $name ] = $callback;
371
	}
372
373
	/**
374
	 * Perform a check whether the current container has fields
375
	 *
376
	 * @return bool
377
	 **/
378
	public function has_fields() {
379
		return (bool) $this->fields;
380
	}
381
382
	/**
383
	 * Returns the private container array of fields.
384
	 * Use only if you are completely aware of what you are doing.
385
	 *
386
	 * @return array
387
	 **/
388
	public function get_fields() {
389
		return $this->fields;
390
	}
391
392
	/**
393
	 * Return root field from container with specified name
394
	 * 
395
	 * @example crb_complex
396
	 * 
397
	 * @param string $field_name
398
	 * @return Field
399
	 **/
400
	public function get_root_field_by_name( $field_name ) {
401
		$fields = $this->get_fields();
402
		foreach ( $fields as $field ) {
403
			if ( $field->get_base_name() === $field_name ) {
404
				return $field;
405
			}
406
		}
407
		return null;
408
	}
409
410
	/**
411
	 * Return field from container with specified name
412
	 * 
413
	 * @example crb_complex/text_field
414
	 * @example crb_complex/complex_2
415
	 * @example crb_complex/complex_2:text_group/text_field
416
	 * 
417
	 * @param string $field_name Can specify a field inside a complex with a / (slash) separator
418
	 * @return Field
419
	 **/
420
	public function get_field_by_name( $field_name ) {
421
		$hierarchy = array_filter( explode( '/', $field_name ) );
422
		$field = null;
423
424
		$field_group = $this->get_fields();
425
		$hierarchy_left = $hierarchy;
426
427
		while ( ! empty( $hierarchy_left ) ) {
428
			$segment = array_shift( $hierarchy_left );
429
			$segment_pieces = explode( ':', $segment, 2 );
430
			$field_name = $segment_pieces[0];
431
			$group_name = isset( $segment_pieces[1] ) ? $segment_pieces[1] : Group_Field::DEFAULT_GROUP_NAME;
432
433
			foreach ( $field_group as $f ) {
434
				if ( $f->get_base_name() === $field_name ) {
435
					if ( empty( $hierarchy_left ) ) {
436
						$field = $f;
437
					} else {
438
						if ( is_a( $f, 'Carbon_Fields\\Field\\Complex_Field' ) ) {
439
							$group = $f->get_group_by_name( $group_name );
440
							if ( ! $group ) {
441
								Incorrect_Syntax_Exception::raise( 'Unknown group name specified when fetching a value inside a complex field: "' . $group_name . '".' );
442
							}
443
							$field_group = $group->get_fields();
444
						} else {
445
							Incorrect_Syntax_Exception::raise( 'Attempted to look for a nested field inside a non-complex field.' );
446
						}
447
					}
448
					break;
449
				}
450
			}
451
		}
452
453
		return $field;
454
	}
455
456
	/**
457
	 * Perform checks whether there is a field registered with the name $name.
458
	 * If not, the field name is recorded.
459
	 *
460
	 * @param string $name
461
	 **/
462 View Code Duplication
	public function verify_unique_field_name( $name ) {
463
		if ( in_array( $name, $this->registered_field_names ) ) {
464
			Incorrect_Syntax_Exception::raise( 'Field name "' . $name . '" already registered' );
465
		}
466
467
		$this->registered_field_names[] = $name;
468
	}
469
470
	/**
471
	 * Remove field name $name from the list of unique field names
472
	 *
473
	 * @param string $name
474
	 **/
475
	public function drop_unique_field_name( $name ) {
476
		$index = array_search( $name, $this->registered_field_names );
477
478
		if ( $index !== false ) {
479
			unset( $this->registered_field_names[ $index ] );
480
		}
481
	}
482
483
	/**
484
	 * Return whether the datastore instance is the default one or has been overriden
485
	 *
486
	 * @return boolean
487
	 **/
488 6
	public function has_default_datastore() {
489 6
		return $this->has_default_datastore;
490
	}
491
492
	/**
493
	 * Set datastore instance
494
	 *
495
	 * @param Datastore_Interface $datastore
496
	 * @return object $this
497
	 **/
498 6 View Code Duplication
	public function set_datastore( Datastore_Interface $datastore, $set_as_default = false ) {
499 6
		if ( $set_as_default && ! $this->has_default_datastore() ) {
500 1
			return $this; // datastore has been overriden with a custom one - abort changing to a default one
501
		}
502 6
		$this->datastore = $datastore;
503 6
		$this->has_default_datastore = $set_as_default;
504
505 6
		foreach ( $this->fields as $field ) {
506
			$field->set_datastore( $this->get_datastore(), true );
507 6
		}
508 6
		return $this;
509
	}
510
511
	/**
512
	 * Get the DataStore instance
513
	 *
514
	 * @return Datastore_Interface $datastore
515
	 **/
516 6
	public function get_datastore() {
517 6
		return $this->datastore;
518
	}
519
520
	/**
521
	 * Return WordPress nonce name used to identify the current container instance
522
	 *
523
	 * @return string
524
	 **/
525
	public function get_nonce_name() {
526
		return 'carbon_panel_' . $this->id . '_nonce';
527
	}
528
529
	/**
530
	 * Return WordPress nonce field
531
	 *
532
	 * @return string
533
	 **/
534
	public function get_nonce_field() {
535
		return wp_nonce_field( $this->get_nonce_name(), $this->get_nonce_name(), /*referer?*/ false, /*echo?*/ false );
536
	}
537
538
	/**
539
	 * Check if the nonce is present in the request and that it is verified
540
	 *
541
	 * @return bool
542
	 **/
543
	protected function verified_nonce_in_request() {
544
		$nonce_name = $this->get_nonce_name();
545
		$nonce_value = isset( $_REQUEST[ $nonce_name ] ) ? $_REQUEST[ $nonce_name ] : '';
0 ignored issues
show
introduced by
Detected access of super global var $_REQUEST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
546
		return wp_verify_nonce( $nonce_value, $nonce_name );
547
	}
548
549
	/**
550
	 * Internal function that creates the tab and associates it with particular field set
551
	 *
552
	 * @param string $tab_name
553
	 * @param array $fields
554
	 * @param int $queue_end
555
	 * @return object $this
556
	 */
557
	private function create_tab( $tab_name, $fields, $queue_end = self::TABS_TAIL ) {
558
		if ( isset( $this->tabs[ $tab_name ] ) ) {
559
			Incorrect_Syntax_Exception::raise( "Tab name duplication for $tab_name" );
560
		}
561
562
		if ( $queue_end === static::TABS_TAIL ) {
563
			$this->tabs[ $tab_name ] = array();
564
		} else if ( $queue_end === static::TABS_HEAD ) {
565
			$this->tabs = array_merge(
566
				array( $tab_name => array() ),
567
				$this->tabs
568
			);
569
		}
570
571
		foreach ( $fields as $field ) {
572
			$field_name = $field->get_name();
573
			$this->tabs[ $tab_name ][ $field_name ] = $field;
574
		}
575
576
		$this->settings['tabs'] = $this->get_tabs_json();
577
	}
578
579
	/**
580
	 * Whether the container is tabbed or not
581
	 *
582
	 * @return bool
583
	 */
584
	public function is_tabbed() {
585
		return (bool) $this->tabs;
586
	}
587
588
	/**
589
	 * Retrieve all fields that are not defined under a specific tab
590
	 *
591
	 * @return array
592
	 */
593
	protected function get_untabbed_fields() {
594
		$tabbed_fields_names = array();
595
		foreach ( $this->tabs as $tab_fields ) {
596
			$tabbed_fields_names = array_merge( $tabbed_fields_names, array_keys( $tab_fields ) );
597
		}
598
599
		$all_fields_names = array();
600
		foreach ( $this->fields as $field ) {
601
			$all_fields_names[] = $field->get_name();
602
		}
603
604
		$fields_not_in_tabs = array_diff( $all_fields_names, $tabbed_fields_names );
605
606
		$untabbed_fields = array();
607
		foreach ( $this->fields as $field ) {
608
			if ( in_array( $field->get_name(), $fields_not_in_tabs ) ) {
609
				$untabbed_fields[] = $field;
610
			}
611
		}
612
613
		return $untabbed_fields;
614
	}
615
616
	/**
617
	 * Retrieve all tabs.
618
	 * Create a default tab if there are any untabbed fields.
619
	 *
620
	 * @return array
621
	 */
622
	protected function get_tabs() {
623
		$untabbed_fields = $this->get_untabbed_fields();
624
625
		if ( ! empty( $untabbed_fields ) ) {
626
			$this->create_tab( __( 'General', \Carbon_Fields\TEXT_DOMAIN ), $untabbed_fields, static::TABS_HEAD );
627
		}
628
629
		return $this->tabs;
630
	}
631
632
	/**
633
	 * Build the tabs JSON
634
	 *
635
	 * @return array
636
	 */
637
	protected function get_tabs_json() {
638
		$tabs_json = array();
639
		$tabs = $this->get_tabs();
640
641
		foreach ( $tabs as $tab_name => $fields ) {
642
			foreach ( $fields as $field_name => $field ) {
643
				$tabs_json[ $tab_name ][] = $field_name;
644
			}
645
		}
646
647
		return $tabs_json;
648
	}
649
650
	/**
651
	 * Underscore template for tabs
652
	 */
653
	public function template_tabs() {
654
		?>
655
		<div class="carbon-tabs">
656
			<ul class="carbon-tabs-nav">
657
				<# _.each(tabs, function (tab, tabName) { #>
658
					<li><a href="#" data-id="{{{ tab.id }}}">{{{ tabName }}}</a></li>
659
				<# }); #>
660
			</ul>
661
662
			<div class="carbon-tabs-body">
663
				<# _.each(tabs, function (tab) { #>
664
					<div class="carbon-fields-collection carbon-tab">
665
						{{{ tab.html }}}
666
					</div>
667
				<# }); #>
668
			</div>
669
		</div>
670
		<?php
671
	}
672
673
	/**
674
	 * Returns an array that holds the container data, suitable for JSON representation.
675
	 * This data will be available in the Underscore template and the Backbone Model.
676
	 *
677
	 * @param bool $load  Should the value be loaded from the database or use the value from the current instance.
678
	 * @return array
679
	 */
680
	public function to_json( $load ) {
681
		$container_data = array(
682
			'id' => $this->id,
683
			'type' => $this->type,
684
			'title' => $this->title,
685
			'settings' => $this->settings,
686
			'fields' => array(),
687
		);
688
689
		$fields = $this->get_fields();
690
		foreach ( $fields as $field ) {
691
			$field_data = $field->to_json( $load );
692
			$container_data['fields'][] = $field_data;
693
		}
694
695
		return $container_data;
696
	}
697
698
	/**
699
	 * Enqueue admin scripts
700
	 */
701
	public static function admin_hook_scripts() {
702
		wp_enqueue_script( 'carbon-containers', \Carbon_Fields\URL . '/assets/js/containers.js', array( 'carbon-app' ), \Carbon_Fields\VERSION );
703
704
		wp_localize_script( 'carbon-containers', 'carbon_containers_l10n',
705
			array(
706
				'please_fill_the_required_fields' => __( 'Please fill out all required fields highlighted below.', \Carbon_Fields\TEXT_DOMAIN ),
707
				'changes_made_save_alert' => __( 'The changes you made will be lost if you navigate away from this page.', \Carbon_Fields\TEXT_DOMAIN ),
708
			)
709
		);
710
	}
711
712
	/**
713
	 * Enqueue admin styles
714
	 */
715
	public static function admin_hook_styles() {
716
		wp_enqueue_style( 'carbon-main', \Carbon_Fields\URL . '/assets/bundle.css', array(), \Carbon_Fields\VERSION );
717
	}
718
719
	/**
720
	 * COMMON USAGE METHODS
721
	 */
722
723
	/**
724
	 * Append array of fields to the current fields set. All items of the array
725
	 * must be instances of Field and their names should be unique for all
726
	 * Carbon containers.
727
	 * If a field does not have DataStore already, the container datastore is
728
	 * assigned to them instead.
729
	 *
730
	 * @param array $fields
731
	 * @return object $this
732
	 **/
733
	public function add_fields( $fields ) {
734
		foreach ( $fields as $field ) {
735
			if ( ! is_a( $field, 'Carbon_Fields\\Field\\Field' ) ) {
736
				Incorrect_Syntax_Exception::raise( 'Object must be of type Carbon_Fields\\Field\\Field' );
737
			}
738
739
			$this->verify_unique_field_name( $field->get_name() );
740
741
			$field->set_context( $this->type );
742
			if ( ! $field->get_datastore() ) {
743
				$field->set_datastore( $this->get_datastore(), $this->has_default_datastore() );
744
			}
745
		}
746
747
		$this->fields = array_merge( $this->fields, $fields );
748
749
		return $this;
750
	}
751
752
	/**
753
	 * Configuration function for adding tab with fields
754
	 *
755
	 * @param string $tab_name
756
	 * @param array $fields
757
	 * @return object $this
758
	 */
759
	public function add_tab( $tab_name, $fields ) {
760
		$this->add_template( 'tabs', array( $this, 'template_tabs' ) );
761
762
		$this->add_fields( $fields );
763
		$this->create_tab( $tab_name, $fields );
764
765
		return $this;
766
	}
767
}
768