Completed
Push — milestone/2.0 ( 9939d7...e0608a )
by
unknown
03:03
created

Container::add_template()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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