Completed
Push — milestone/2.0 ( 371be2...8a1186 )
by
unknown
02:18
created

Container::_attach()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 0
dl 0
loc 15
rs 9.2
c 0
b 0
f 0
ccs 0
cts 13
cp 0
crap 20
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
		\Carbon_Fields\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
202
	/**
203
	 * Activates and boots a field recursively
204
	 **/
205
	protected function activate_field( $field ) {
206
		if ( method_exists( $field, 'get_fields' ) ) {
207
			$fields = $field->get_fields();
208
209
			foreach ( $fields as $inner_field ) {
210
				$this->activate_field( $inner_field );
211
			}
212
		}
213
214
		$field->boot();
215
216
		do_action( 'crb_field_activated', $field );
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
	 * Called first as part of the container save procedure.
267
	 * Responsible for checking the request validity and
268
	 * calling the container-specific save() method
269
	 *
270
	 * @see save()
271
	 * @see is_valid_save()
272
	 **/
273
	public function _save() {
274
		$param = func_get_args();
275
		if ( call_user_func_array( array( $this, 'is_valid_save' ), $param ) ) {
276
			call_user_func_array( array( $this, 'save' ), $param );
277
		}
278
	}
279
280
	/**
281
	 * Load submitted data and save each field in the container
282
	 *
283
	 * @see is_valid_save()
284
	 **/
285
	public function save( $data ) {
286
		foreach ( $this->fields as $field ) {
287
			$field->set_value_from_input();
288
			$field->save();
289
		}
290
	}
291
292
	/**
293
	 * Checks whether the current request is valid
294
	 *
295
	 * @return bool
296
	 **/
297
	public function is_valid_save() {
298
		return false;
299
	}
300
301
	/**
302
	 * Load the value for each field in the container.
303
	 * Could be used internally during container rendering
304
	 **/
305
	public function load() {
306
		foreach ( $this->fields as $field ) {
307
			$field->load();
308
		}
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
			if ( call_user_func_array( array( $this, 'is_active' ), $param ) ) {
325
				$this->activate();
326
327
				$fields = $this->get_fields();
328
				foreach ( $fields as $field ) {
329
					$this->activate_field( $field );
330
				}
331
			}
332
		}
333
	}
334
335
	/**
336
	 * Returns all the Backbone templates
337
	 *
338
	 * @return array
339
	 **/
340
	public function get_templates() {
341
		return $this->templates;
342
	}
343
344
	/**
345
	 * Adds a new Backbone template
346
	 **/
347
	protected function add_template( $name, $callback ) {
348
		$this->templates[ $name ] = $callback;
349
	}
350
351
	/**
352
	 * Attach the container rendering and helping methods
353
	 * to concrete WordPress Action hooks
354
	 **/
355
	public function attach() {}
356
357
	/**
358
	 * Perform checks whether the container should be attached during the current request
359
	 *
360
	 * @return bool True if the container is allowed to be attached
361
	 **/
362
	final public function is_valid_attach() {
363
		$is_valid_attach = $this->_is_valid_attach();
364
		return apply_filters( 'carbon_container_is_valid_attach', $is_valid_attach, $this );
365
	}
366
367
	/**
368
	 * Require extending containers to define their own attach rules
369
	 *
370
	 * @return bool True if the container is allowed to be attached
371
	 **/
372
	abstract protected function _is_valid_attach();
373
374
	/**
375
	 * Whether this container is currently viewed.
376
	 **/
377
	public function is_active() {
378
		return $this->is_valid_attach();
379
	}
380
381
	/**
382
	 * Perform a check whether the current container has fields
383
	 *
384
	 * @return bool
385
	 **/
386
	public function has_fields() {
387
		return (bool) $this->fields;
388
	}
389
390
	/**
391
	 * Returns the private container array of fields.
392
	 * Use only if you are completely aware of what you are doing.
393
	 *
394
	 * @return array
395
	 **/
396
	public function get_fields() {
397
		return $this->fields;
398
	}
399
400
	/**
401
	 * Return root field from container with specified name
402
	 * 
403
	 * @example crb_complex
404
	 * 
405
	 * @param string $field_name
406
	 * @return Field
407
	 **/
408
	public function get_root_field_by_name( $field_name ) {
409
		$fields = $this->get_fields();
410
		foreach ( $fields as $field ) {
411
			if ( $field->get_base_name() === $field_name ) {
412
				return $field;
413
			}
414
		}
415
		return null;
416
	}
417
418
	/**
419
	 * Return field from container with specified name
420
	 * 
421
	 * @example crb_complex/text_field
422
	 * @example crb_complex/complex_2
423
	 * @example crb_complex/complex_2:text_group/text_field
424
	 * 
425
	 * @param string $field_name Can specify a field inside a complex with a / (slash) separator
426
	 * @return Field
427
	 **/
428
	public function get_field_by_name( $field_name ) {
429
		$hierarchy = array_filter( explode( '/', $field_name ) );
430
		$field = null;
431
432
		$field_group = $this->get_fields();
433
		$hierarchy_left = $hierarchy;
434
435
		while ( ! empty( $hierarchy_left ) ) {
436
			$segment = array_shift( $hierarchy_left );
437
			$segment_pieces = explode( ':', $segment, 2 );
438
			$field_name = $segment_pieces[0];
439
			$group_name = isset( $segment_pieces[1] ) ? $segment_pieces[1] : Group_Field::DEFAULT_GROUP_NAME;
440
441
			foreach ( $field_group as $f ) {
442
				if ( $f->get_base_name() === $field_name ) {
443
					if ( empty( $hierarchy_left ) ) {
444
						$field = $f;
445
					} else {
446
						if ( is_a( $f, '\\Carbon_Fields\\Field\\Complex_Field' ) ) {
447
							$group = $f->get_group_by_name( $group_name );
448
							if ( ! $group ) {
449
								Incorrect_Syntax_Exception::raise( 'Unknown group name specified when fetching a value inside a complex field: "' . $group_name . '".' );
450
							}
451
							$field_group = $group->get_fields();
452
						} else {
453
							Incorrect_Syntax_Exception::raise( 'Attempted to look for a nested field inside a non-complex field.' );
454
						}
455
					}
456
					break;
457
				}
458
			}
459
		}
460
461
		return $field;
462
	}
463
464
	/**
465
	 * Perform checks whether there is a field registered with the name $name.
466
	 * If not, the field name is recorded.
467
	 *
468
	 * @param string $name
469
	 **/
470 View Code Duplication
	public function verify_unique_field_name( $name ) {
471
		if ( in_array( $name, $this->registered_field_names ) ) {
472
			Incorrect_Syntax_Exception::raise( 'Field name "' . $name . '" already registered' );
473
		}
474
475
		$this->registered_field_names[] = $name;
476
	}
477
478
	/**
479
	 * Remove field name $name from the list of unique field names
480
	 *
481
	 * @param string $name
482
	 **/
483
	public function drop_unique_field_name( $name ) {
484
		$index = array_search( $name, $this->registered_field_names );
485
486
		if ( $index !== false ) {
487
			unset( $this->registered_field_names[ $index ] );
488
		}
489
	}
490
491
	/**
492
	 * Return whether the datastore instance is the default one or has been overriden
493
	 *
494
	 * @return boolean
495
	 **/
496 6
	public function has_default_datastore() {
497 6
		return $this->has_default_datastore;
498
	}
499
500
	/**
501
	 * Set datastore instance
502
	 *
503
	 * @param Datastore_Interface $datastore
504
	 * @return object $this
505
	 **/
506 6 View Code Duplication
	public function set_datastore( Datastore_Interface $datastore, $set_as_default = false ) {
507 6
		if ( $set_as_default && ! $this->has_default_datastore() ) {
508 1
			return $this; // datastore has been overriden with a custom one - abort changing to a default one
509
		}
510 6
		$this->datastore = $datastore;
511 6
		$this->has_default_datastore = $set_as_default;
512
513 6
		foreach ( $this->fields as $field ) {
514
			$field->set_datastore( $this->get_datastore(), true );
515 6
		}
516 6
		return $this;
517
	}
518
519
	/**
520
	 * Get the DataStore instance
521
	 *
522
	 * @return Datastore_Interface $datastore
523
	 **/
524 6
	public function get_datastore() {
525 6
		return $this->datastore;
526
	}
527
528
	/**
529
	 * Return WordPress nonce name used to identify the current container instance
530
	 *
531
	 * @return string
532
	 **/
533
	public function get_nonce_name() {
534
		return 'carbon_panel_' . $this->id . '_nonce';
535
	}
536
537
	/**
538
	 * Return WordPress nonce field
539
	 *
540
	 * @return string
541
	 **/
542
	public function get_nonce_field() {
543
		return wp_nonce_field( $this->get_nonce_name(), $this->get_nonce_name(), /*referer?*/ false, /*echo?*/ false );
544
	}
545
546
	/**
547
	 * Check if the nonce is present in the request and that it is verified
548
	 *
549
	 * @return bool
550
	 **/
551
	protected function verified_nonce_in_request() {
552
		$nonce_name = $this->get_nonce_name();
553
		$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...
554
		return wp_verify_nonce( $nonce_value, $nonce_name );
555
	}
556
557
	/**
558
	 * Internal function that creates the tab and associates it with particular field set
559
	 *
560
	 * @param string $tab_name
561
	 * @param array $fields
562
	 * @param int $queue_end
563
	 * @return object $this
564
	 */
565
	private function create_tab( $tab_name, $fields, $queue_end = self::TABS_TAIL ) {
566
		if ( isset( $this->tabs[ $tab_name ] ) ) {
567
			Incorrect_Syntax_Exception::raise( "Tab name duplication for $tab_name" );
568
		}
569
570
		if ( $queue_end === static::TABS_TAIL ) {
571
			$this->tabs[ $tab_name ] = array();
572
		} else if ( $queue_end === static::TABS_HEAD ) {
573
			$this->tabs = array_merge(
574
				array( $tab_name => array() ),
575
				$this->tabs
576
			);
577
		}
578
579
		foreach ( $fields as $field ) {
580
			$field_name = $field->get_name();
581
			$this->tabs[ $tab_name ][ $field_name ] = $field;
582
		}
583
584
		$this->settings['tabs'] = $this->get_tabs_json();
585
	}
586
587
	/**
588
	 * Whether the container is tabbed or not
589
	 *
590
	 * @return bool
591
	 */
592
	public function is_tabbed() {
593
		return (bool) $this->tabs;
594
	}
595
596
	/**
597
	 * Retrieve all fields that are not defined under a specific tab
598
	 *
599
	 * @return array
600
	 */
601
	protected function get_untabbed_fields() {
602
		$tabbed_fields_names = array();
603
		foreach ( $this->tabs as $tab_fields ) {
604
			$tabbed_fields_names = array_merge( $tabbed_fields_names, array_keys( $tab_fields ) );
605
		}
606
607
		$all_fields_names = array();
608
		foreach ( $this->fields as $field ) {
609
			$all_fields_names[] = $field->get_name();
610
		}
611
612
		$fields_not_in_tabs = array_diff( $all_fields_names, $tabbed_fields_names );
613
614
		$untabbed_fields = array();
615
		foreach ( $this->fields as $field ) {
616
			if ( in_array( $field->get_name(), $fields_not_in_tabs ) ) {
617
				$untabbed_fields[] = $field;
618
			}
619
		}
620
621
		return $untabbed_fields;
622
	}
623
624
	/**
625
	 * Retrieve all tabs.
626
	 * Create a default tab if there are any untabbed fields.
627
	 *
628
	 * @return array
629
	 */
630
	protected function get_tabs() {
631
		$untabbed_fields = $this->get_untabbed_fields();
632
633
		if ( ! empty( $untabbed_fields ) ) {
634
			$this->create_tab( __( 'General', \Carbon_Fields\TEXT_DOMAIN ), $untabbed_fields, static::TABS_HEAD );
635
		}
636
637
		return $this->tabs;
638
	}
639
640
	/**
641
	 * Build the tabs JSON
642
	 *
643
	 * @return array
644
	 */
645
	protected function get_tabs_json() {
646
		$tabs_json = array();
647
		$tabs = $this->get_tabs();
648
649
		foreach ( $tabs as $tab_name => $fields ) {
650
			foreach ( $fields as $field_name => $field ) {
651
				$tabs_json[ $tab_name ][] = $field_name;
652
			}
653
		}
654
655
		return $tabs_json;
656
	}
657
658
	/**
659
	 * Underscore template for tabs
660
	 */
661
	public function template_tabs() {
662
		?>
663
		<div class="carbon-tabs">
664
			<ul class="carbon-tabs-nav">
665
				<# _.each(tabs, function (tab, tabName) { #>
666
					<li><a href="#" data-id="{{{ tab.id }}}">{{{ tabName }}}</a></li>
667
				<# }); #>
668
			</ul>
669
670
			<div class="carbon-tabs-body">
671
				<# _.each(tabs, function (tab) { #>
672
					<div class="carbon-fields-collection carbon-tab">
673
						{{{ tab.html }}}
674
					</div>
675
				<# }); #>
676
			</div>
677
		</div>
678
		<?php
679
	}
680
681
	/**
682
	 * Returns an array that holds the container data, suitable for JSON representation.
683
	 * This data will be available in the Underscore template and the Backbone Model.
684
	 *
685
	 * @param bool $load  Should the value be loaded from the database or use the value from the current instance.
686
	 * @return array
687
	 */
688
	public function to_json( $load ) {
689
		$container_data = array(
690
			'id' => $this->id,
691
			'type' => $this->type,
692
			'title' => $this->title,
693
			'settings' => $this->settings,
694
			'fields' => array(),
695
		);
696
697
		$fields = $this->get_fields();
698
		foreach ( $fields as $field ) {
699
			$field_data = $field->to_json( $load );
700
			$container_data['fields'][] = $field_data;
701
		}
702
703
		return $container_data;
704
	}
705
706
	/**
707
	 * Enqueue admin scripts
708
	 */
709
	public static function admin_hook_scripts() {
710
		wp_enqueue_script( 'carbon-containers', \Carbon_Fields\URL . '/assets/js/containers.js', array( 'carbon-app' ), \Carbon_Fields\VERSION );
711
712
		wp_localize_script( 'carbon-containers', 'carbon_containers_l10n',
713
			array(
714
				'please_fill_the_required_fields' => __( 'Please fill out all required fields highlighted below.', \Carbon_Fields\TEXT_DOMAIN ),
715
				'changes_made_save_alert' => __( 'The changes you made will be lost if you navigate away from this page.', \Carbon_Fields\TEXT_DOMAIN ),
716
			)
717
		);
718
	}
719
720
	/**
721
	 * Enqueue admin styles
722
	 */
723
	public static function admin_hook_styles() {
724
		wp_enqueue_style( 'carbon-main', \Carbon_Fields\URL . '/assets/bundle.css', array(), \Carbon_Fields\VERSION );
725
	}
726
727
	/**
728
	 * COMMON USAGE METHODS
729
	 */
730
731
	/**
732
	 * Append array of fields to the current fields set. All items of the array
733
	 * must be instances of Field and their names should be unique for all
734
	 * Carbon containers.
735
	 * If a field does not have DataStore already, the container datastore is
736
	 * assigned to them instead.
737
	 *
738
	 * @param array $fields
739
	 * @return object $this
740
	 **/
741
	public function add_fields( $fields ) {
742
		foreach ( $fields as $field ) {
743
			if ( ! is_a( $field, 'Carbon_Fields\\Field\\Field' ) ) {
744
				Incorrect_Syntax_Exception::raise( 'Object must be of type Carbon_Fields\\Field\\Field' );
745
			}
746
747
			$this->verify_unique_field_name( $field->get_name() );
748
749
			$field->set_context( $this->type );
750
			if ( ! $field->get_datastore() ) {
751
				$field->set_datastore( $this->get_datastore(), $this->has_default_datastore() );
752
			}
753
		}
754
755
		$this->fields = array_merge( $this->fields, $fields );
756
757
		return $this;
758
	}
759
760
	/**
761
	 * Configuration function for adding tab with fields
762
	 *
763
	 * @param string $tab_name
764
	 * @param array $fields
765
	 * @return object $this
766
	 */
767
	public function add_tab( $tab_name, $fields ) {
768
		$this->add_template( 'tabs', array( $this, 'template_tabs' ) );
769
770
		$this->add_fields( $fields );
771
		$this->create_tab( $tab_name, $fields );
772
773
		return $this;
774
	}
775
}
776