Completed
Push — milestone/2.0 ( 631282...ba0b77 )
by
unknown
02:33
created

Field::is_simple_root_field()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 3
eloc 8
c 1
b 1
f 0
nc 3
nop 0
dl 0
loc 12
ccs 0
cts 9
cp 0
crap 12
rs 9.4285
1
<?php
2
3
namespace Carbon_Fields\Field;
4
5
use Carbon_Fields\Datastore\Datastore_Interface;
6
use Carbon_Fields\Datastore\Datastore_Holder_Interface;
7
use Carbon_Fields\Value_Set\Value_Set;
8
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
9
10
/**
11
 * Base field class.
12
 * Defines the key container methods and their default implementations.
13
 * Implements factory design pattern.
14
 **/
15
class Field implements Datastore_Holder_Interface {
16
	/**
17
	 * Stores all the field Backbone templates
18
	 *
19
	 * @see factory()
20
	 * @see add_template()
21
	 * @var array
22
	 */
23
	protected $templates = array();
24
25
	/**
26
	 * Globally unique field identificator. Generated randomly
27
	 *
28
	 * @var string
29
	 */
30
	protected $id;
31
32
	/**
33
	 * Stores the initial <kbd>$type</kbd> variable passed to the <code>factory()</code> method
34
	 *
35
	 * @see factory
36
	 * @var string
37
	 */
38
	public $type;
39
40
	/**
41
	 * Array of ancestor field names
42
	 *
43
	 * @var array
44
	 **/
45
	protected $hierarchy = array();
46
47
	/**
48
	 * Array of complex entry ids
49
	 *
50
	 * @var array
51
	 **/
52
	protected $hierarchy_index = array();
53
54
	/**
55
	 * Field value
56
	 *
57
	 * @var Value_Set
58
	 */
59
	protected $value;
60
61
	/**
62
	 * Default field value
63
	 *
64
	 * @var mixed
65
	 */
66
	protected $default_value;
67
68
	/**
69
	 * Sanitized field name used as input name attribute during field render
70
	 *
71
	 * @see factory()
72
	 * @see set_name()
73
	 * @var string
74
	 */
75
	protected $name;
76
77
	/**
78
	 * Field name prefix
79
	 *
80
	 * @see set_name()
81
	 * @var string
82
	 */
83
	protected $name_prefix = '_';
84
85
	/**
86
	 * The base field name which is used in the container.
87
	 *
88
	 * @see set_base_name()
89
	 * @var string
90
	 */
91
	protected $base_name;
92
93
	/**
94
	 * Field name used as label during field render
95
	 *
96
	 * @see factory()
97
	 * @see set_label()
98
	 * @var string
99
	 */
100
	protected $label;
101
102
	/**
103
	 * Additional text containing information and guidance for the user
104
	 *
105
	 * @see help_text()
106
	 * @var string
107
	 */
108
	protected $help_text;
109
110
	/**
111
	 * Field DataStore instance to which save, load and delete calls are delegated
112
	 *
113
	 * @see set_datastore()
114
	 * @see get_datastore()
115
	 * @var Datastore_Interface
116
	 */
117
	protected $datastore;
118
119
	/**
120
	 * Flag whether the datastore is the default one or replaced with a custom one
121
	 *
122
	 * @see set_datastore()
123
	 * @see get_datastore()
124
	 * @var boolean
125
	 */
126
	protected $has_default_datastore = true;
127
128
	/**
129
	 * The type of the container this field is in
130
	 *
131
	 * @see get_context()
132
	 * @var string
133
	 */
134
	protected $context;
135
136
	/**
137
	 * Whether or not this value should be auto loaded. Applicable to theme options only.
138
	 *
139
	 * @see set_autoload()
140
	 * @var bool
141
	 **/
142
	protected $autoload = false;
143
144
	/**
145
	 * Whether or not this field will be initialized when the field is in the viewport (visible).
146
	 *
147
	 * @see set_lazyload()
148
	 * @var bool
149
	 **/
150
	protected $lazyload = false;
151
152
	/**
153
	 * The width of the field.
154
	 *
155
	 * @see set_width()
156
	 * @var int
157
	 **/
158
	protected $width = 0;
159
160
	/**
161
	 * Custom CSS classes.
162
	 *
163
	 * @see add_class()
164
	 * @var array
165
	 **/
166
	protected $classes = array();
167
168
	/**
169
	 * Whether or not this field is required.
170
	 *
171
	 * @see set_required()
172
	 * @var bool
173
	 **/
174
	protected $required = false;
175
176
	/**
177
	 * Stores the field conditional logic rules.
178
	 *
179
	 * @var array
180
	 **/
181
	protected $conditional_logic = array();
182
183
	/**
184
	 * Whether the field should be included in the response of the requests to the REST API
185
	 *
186
	 * @see  set_visible_in_rest_api
187
	 * @see  get_visible_in_rest_api
188
	 * @var boolean
189
	 */
190
	protected $visible_in_rest_api = false;
191
192
	/**
193
	 * Clone the Value_Set object as well
194
	 *
195
	 * @var array
196
	 **/
197
    public function __clone() {
198
        $this->value = clone $this->value();
199
    }
200
201
	/**
202
	 * Create a new field of type $type and name $name and label $label.
203
	 *
204
	 * @param string $type
205
	 * @param string $name lower case and underscore-delimited
206
	 * @param string $label (optional) Automatically generated from $name if not present
207
	 * @return Field
208
	 **/
209 15
	public static function factory( $type, $name, $label = null ) {
210
		// backward compatibility: `file` type used to be called `attachment`
211 15
		if ( $type === 'attachment' ) {
212
			$type = 'file';
213
		}
214
215 15
		$type = str_replace( ' ', '_', ucwords( str_replace( '_', ' ', $type ) ) );
216
217 15
		$class = __NAMESPACE__ . '\\' . $type . '_Field';
218
219 15 View Code Duplication
		if ( ! class_exists( $class ) ) {
220 4
			Incorrect_Syntax_Exception::raise( 'Unknown field "' . $type . '".' );
221 1
			$class = __NAMESPACE__ . '\\Broken_Field';
222 1
		}
223
224 12
		$field = new $class( $name, $label );
225 10
		$field->type = $type;
226
227 10
		return $field;
228
	}
229
230
	/**
231
	 * An alias of factory().
232
	 *
233
	 * @see Field::factory()
234
	 * @return Field
235
	 **/
236 15
	public static function make( $type, $name, $label = null ) {
237 15
		return static::factory( $type, $name, $label );
238
	}
239
240
	/**
241
	 * Create a field from a certain type with the specified label.
242
	 * @param string $name  Field name
243
	 * @param string $label Field label
244
	 */
245 12 View Code Duplication
	protected function __construct( $name, $label ) {
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...
246 12
		\Carbon_Fields\App::verify_boot();
247
		
248 12
		$this->set_base_name( $name );
249 12
		$this->set_name( $name );
250 10
		$this->set_label( $label );
251
252
		// Pick random ID
253 10
		$random_string = md5( mt_rand() . $this->get_name() . $this->get_label() );
254 10
		$random_string = substr( $random_string, 0, 5 ); // 5 chars should be enough
255 10
		$this->id = 'carbon-' . $random_string;
256
257 10
		$this->init();
258 10
	}
259
260
	/**
261
	 * Boot the field once the container is attached.
262
	 **/
263
	public function boot() {
264
		$this->admin_init();
265
266
		$this->add_template( $this->get_type(), array( $this, 'template' ) );
267
268
		add_action( 'admin_footer', array( get_class(), 'admin_hook_scripts' ), 5 );
269
		add_action( 'admin_footer', array( get_class(), 'admin_hook_styles' ), 5 );
270
271
		add_action( 'admin_footer', array( get_class( $this ), 'admin_enqueue_scripts' ), 5 );
272
	}
273
274
	/**
275
	 * Set array of hierarchy field names
276
	 *
277
	 * @return array
278
	 **/
279
	public function set_hierarchy( $hierarchy ) {
280
		$this->hierarchy = $hierarchy;
281
	}
282
283
	/**
284
	 * Get array of hierarchy field names
285
	 *
286
	 * @return array
287
	 **/
288
	public function get_hierarchy() {
289
		return $this->hierarchy;
290
	}
291
292
	/**
293
	 * Set array of hierarchy indexes
294
	 *
295
	 * @return array
296
	 **/
297
	public function set_hierarchy_index( $hierarchy_index ) {
298
		$this->hierarchy_index = $hierarchy_index;
299
	}
300
301
	/**
302
	 * Get array of hierarchy indexes
303
	 *
304
	 * @return array
305
	 **/
306
	public function get_hierarchy_index() {
307
		return $this->hierarchy_index;
308
	}
309
310
	/**
311
	 * Return whether the field is a root field and holds a single value
312
	 *
313
	 * @return bool
314
	 **/
315
	public function is_simple_root_field() {
316
		$hierarchy = $this->get_hierarchy();
317
		return (
318
			empty( $hierarchy )
319
			&&
320
			(
321
				$this->value()->get_type() === Value_Set::TYPE_SINGLE_VALUE
322
				||
323
				$this->value()->get_type() === Value_Set::TYPE_MULTIPLE_PROPERTIES
324
			)
325
		);
326
	}
327
328
	/**
329
	 * Perform instance initialization
330
	 **/
331
	public function init() {}
332
333
	/**
334
	 * Instance initialization when in the admin area.
335
	 * Called during field boot.
336
	 **/
337
	public function admin_init() {}
338
339
	/**
340
	 * Enqueue admin scripts.
341
	 * Called once per field type.
342
	 **/
343
	public static function admin_enqueue_scripts() {}
344
345
	/**
346
	 * Prints the main Underscore template
347
	 **/
348
	public function template() { }
349
350
	/**
351
	 * Returns all the Backbone templates
352
	 *
353
	 * @return array
354
	 **/
355
	public function get_templates() {
356
		return $this->templates;
357
	}
358
359
	/**
360
	 * Adds a new Backbone template
361
	 **/
362
	protected function add_template( $name, $callback ) {
363
		$this->templates[ $name ] = $callback;
364
	}
365
366
	/**
367
	 * Load value from datastore
368
	 **/
369 2
	public function load() {
370 2
		$raw_value_set_tree = $this->get_datastore()->load( $this );
371 2
		$value = null;
372 2
		if ( isset( $raw_value_set_tree[ $this->get_base_name() ] ) ) {
373 1
			$value = $raw_value_set_tree[ $this->get_base_name() ]['value_set'];
374 1
		}
375 2
		$this->set_value( $value );
376
377 2
		if ( $this->get_value() === null ) {
378 1
			$this->set_value( $this->get_default_value() );
379 1
		}
380 2
	}
381
382
	/**
383
	 * Save value to storage
384
	 **/
385 1
	public function save() {
386 1
		if ( ! in_array( $this->value()->get_type(), array( Value_Set::TYPE_SINGLE_VALUE, Value_Set::TYPE_MULTIPLE_PROPERTIES ) ) ) {
387
			$this->delete();
388
		}
389 1
		return $this->get_datastore()->save( $this );
390
	}
391
392
	/**
393
	 * Delete value from storage
394
	 */
395 1
	public function delete() {
396 1
		$this->get_datastore()->delete( $this );
397 1
	}
398
399
	/**
400
	 * Load the field value from an input array based on it's name
401
	 *
402
	 * @param array $input (optional) Array of field names and values. Defaults to $_POST
403
	 **/
404
	public function set_value_from_input( $input = null ) {
405
		if ( is_null( $input ) ) {
406
			$input = $_POST;
0 ignored issues
show
introduced by
Detected access of super global var $_POST, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_POST
Loading history...
407
		}
408
409
		if ( ! isset( $input[ $this->name ] ) ) {
410
			$this->set_value( array() );
411
		} else {
412
			$this->set_value( stripslashes_deep( $input[ $this->name ] ) );
413
		}
414
	}
415
416
	/**
417
	 * Return whether the datastore instance is the default one or has been overriden
418
	 *
419
	 * @return boolean
420
	 **/
421
	public function has_default_datastore() {
422
		return $this->has_default_datastore;
423
	}
424
425
	/**
426
	 * Set datastore instance
427
	 *
428
	 * @param Datastore_Interface $datastore
429
	 * @return object $this
430
	 **/
431 1
	public function set_datastore( Datastore_Interface $datastore, $set_as_default = false ) {
432 1
		if ( $set_as_default && ! $this->has_default_datastore() ) {
433
			return $this; // datastore has been overriden with a custom one - abort changing to a default one
434
		}
435 1
		$this->datastore = $datastore;
436 1
		$this->has_default_datastore = $set_as_default;
437 1
		return $this;
438
	}
439
440
	/**
441
	 * Get the DataStore instance
442
	 *
443
	 * @return Datastore_Interface $datastore
444
	 **/
445 1
	public function get_datastore() {
446 1
		return $this->datastore;
447
	}
448
449
	/**
450
	 * Assign the type of the container this field is in
451
	 *
452
	 * @param string
453
	 * @return object $this
454
	 **/
455
	public function set_context( $context ) {
456
		$this->context = $context;
457
		return $this;
458
	}
459
460
	/**
461
	 * Return the type of the container this field is in
462
	 *
463
	 * @return string
464
	 **/
465
	public function get_context() {
466
		return $this->context;
467
	}
468
469
	/**
470
	 * Return a reference to the Value_Set
471
	 *
472
	 * @return Value_Set
473
	 **/
474
	public function value() {
475
		if ( $this->value === null ) {
476
			$this->value = new Value_Set();
477
		}
478
		return $this->value;
479
	}
480
481
	/**
482
	 * Alias for $this->value()->get();
483
	 *
484
	 * @return mixed
485
	 **/
486 3
	public function get_value() {
487 3
		return $this->value()->get();
488
	}
489
490
	/**
491
	 * Return a differently formatted value for end-users
492
	 *
493
	 * @return mixed
494
	 **/
495
	public function get_formatted_value() {
496
		$value = $this->get_value();
497
		if ( $value === null ) {
498
			$value = $this->get_default_value();
499
		}
500
		return $value;
501
	}
502
503
	/**
504
	 * Alias for $this->value()->set( $value );
505
	 **/
506 1
	public function set_value( $value ) {
507 1
		return $this->value()->set( $value );
508
	}
509
510
	/**
511
	 * Set default field value
512
	 *
513
	 * @param mixed $default_value
514
	 **/
515 1
	public function set_default_value( $default_value ) {
516 1
		$this->default_value = $default_value;
517 1
		return $this;
518
	}
519
520
	/**
521
	 * Get default field value
522
	 *
523
	 * @return mixed
524
	 **/
525 1
	public function get_default_value() {
526 1
		return $this->default_value;
527
	}
528
529
	/**
530
	 * Set field name.
531
	 * Use only if you are completely aware of what you are doing.
532
	 *
533
	 * @param string $name Field name, either sanitized or not
534
	 **/
535 5
	public function set_name( $name ) {
536 5
		$name = mb_strtolower( $name );
537 5
		$name = preg_replace( '~\s+~', '_', $name );
538
539 5
		if ( empty( $name ) ) {
540
			Incorrect_Syntax_Exception::raise( 'Field name can\'t be empty' );
541
		}
542
543 5
		$regex = '/[\|\:]+/';
544 5
		if ( preg_match( $regex, $name ) ) {
545
			Incorrect_Syntax_Exception::raise( 'Field name "' . $name . '" cannot contain "|" or ":" characters.' );
546
		}
547
548 5
		$name_prefix = $this->get_name_prefix();
549 5
		$name = ( substr( $name, 0, strlen( $name_prefix ) ) !== $name_prefix ? $name_prefix . $name : $name );
550
551 5
		$this->name = $name;
552 5
	}
553
554
	/**
555
	 * Return the field name
556
	 *
557
	 * @return string
558
	 **/
559 5
	public function get_name() {
560 5
		return $this->name;
561
	}
562
563
	/**
564
	 * Set field name prefix
565
	 * Use only if you are completely aware of what you are doing.
566
	 *
567
	 * @param string $name_prefix
568
	 **/
569
	public function set_name_prefix( $name_prefix ) {
570
		$old_prefix_length = strlen( $this->name_prefix );
571
		$this->set_name( substr( $this->get_name(), $old_prefix_length ) );
572
		$this->name_prefix = $name_prefix;
573
		$this->set_name( $name_prefix . $this->get_name() );
574
	}
575
576
	/**
577
	 * Return the field name prefix
578
	 *
579
	 * @return string
580
	 **/
581
	public function get_name_prefix() {
582
		return $this->name_prefix;
583
	}
584
585
	/**
586
	 * Set field base name as defined in the container.
587
	 **/
588
	public function set_base_name( $name ) {
589
		$this->base_name = $name;
590
	}
591
592
	/**
593
	 * Return the field base name.
594
	 *
595
	 * @return string
596
	 **/
597
	public function get_base_name() {
598
		return $this->base_name;
599
	}
600
601
	/**
602
	 * Set field label.
603
	 *
604
	 * @param string $label If null, the label will be generated from the field name
605
	 **/
606 View Code Duplication
	public function set_label( $label ) {
1 ignored issue
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...
607
		// Try to guess field label from it's name
608
		if ( is_null( $label ) ) {
609
			// remove the leading underscore(if it's there)
610
			$label = preg_replace( '~^_~', '', $this->name );
611
612
			// remove the leading "crb_"(if it's there)
613
			$label = preg_replace( '~^crb_~', '', $label );
614
615
			// split the name into words and make them capitalized
616
			$label = mb_convert_case( str_replace( '_', ' ', $label ), MB_CASE_TITLE );
617
		}
618
619
		$this->label = $label;
620
	}
621
622
	/**
623
	 * Return field label.
624
	 *
625
	 * @return string
626
	 **/
627
	public function get_label() {
628
		return $this->label;
629
	}
630
631
	/**
632
	 * Set additional text to be displayed during field render,
633
	 * containing information and guidance for the user
634
	 *
635
	 * @return object $this
636
	 **/
637
	public function set_help_text( $help_text ) {
638
		$this->help_text = $help_text;
639
		return $this;
640
	}
641
642
	/**
643
	 * Alias for set_help_text()
644
	 *
645
	 * @see set_help_text()
646
	 * @return object $this
647
	 **/
648
	public function help_text( $help_text ) {
649
		return $this->set_help_text( $help_text );
650
	}
651
652
	/**
653
	 * Return the field help text
654
	 *
655
	 * @return object $this
656
	 **/
657
	public function get_help_text() {
658
		return $this->help_text;
659
	}
660
661
	/**
662
	 * Whether or not this value should be auto loaded. Applicable to theme options only.
663
	 *
664
	 * @param bool $autoload
665
	 * @return object $this
666
	 **/
667
	public function set_autoload( $autoload ) {
668
		$this->autoload = $autoload;
669
		return $this;
670
	}
671
672
	/**
673
	 * Return whether or not this value should be auto loaded.
674
	 *
675
	 * @return bool
676
	 **/
677
	public function get_autoload() {
678
		return $this->autoload;
679
	}
680
681
	/**
682
	 * Whether or not this field will be initialized when the field is in the viewport (visible).
683
	 *
684
	 * @param bool $lazyload
685
	 * @return object $this
686
	 **/
687
	public function set_lazyload( $lazyload ) {
688
		$this->lazyload = $lazyload;
689
		return $this;
690
	}
691
692
	/**
693
	 * Return whether or not this field should be lazyloaded.
694
	 *
695
	 * @return bool
696
	 **/
697
	public function get_lazyload() {
698
		return $this->lazyload;
699
	}
700
701
	/**
702
	 * Set the field width.
703
	 *
704
	 * @param int $width
705
	 * @return object $this
706
	 **/
707
	public function set_width( $width ) {
708
		$this->width = (int) $width;
709
		return $this;
710
	}
711
712
	/**
713
	 * Get the field width.
714
	 *
715
	 * @return int $width
716
	 **/
717
	public function get_width() {
718
		return $this->width;
719
	}
720
721
	/**
722
	 *  Add custom CSS class to the field html container.
723
	 *
724
	 * @param string|array $classes
725
	 * @return object $this
726
	 **/
727
	public function add_class( $classes ) {
728
		if ( ! is_array( $classes ) ) {
729
			$classes = array_values( array_filter( explode( ' ', $classes ) ) );
730
		}
731
732
		$this->classes = array_map( 'sanitize_html_class', $classes );
733
		return $this;
734
	}
735
736
	/**
737
	 * Get the field custom CSS classes.
738
	 *
739
	 * @return array
740
	 **/
741
	public function get_classes() {
742
		return $this->classes;
743
	}
744
745
	/**
746
	 * Whether this field is mandatory for the user
747
	 *
748
	 * @param bool $required
749
	 * @return object $this
750
	 **/
751
	public function set_required( $required = true ) {
752
		$this->required = $required;
753
		return $this;
754
	}
755
756
	/**
757
	 * HTML id attribute getter.
758
	 * @return string
759
	 */
760 1
	public function get_id() {
761 1
		return $this->id;
762
	}
763
764
	/**
765
	 * HTML id attribute setter
766
	 * @param string $id
767
	 */
768 1
	public function set_id( $id ) {
769 1
		$this->id = $id;
770 1
	}
771
772
	/**
773
	 * Return whether this field is mandatory for the user
774
	 *
775
	 * @return bool
776
	 **/
777
	public function is_required() {
778
		return $this->required;
779
	}
780
781
	/**
782
	 * Returns the type of the field based on the class.
783
	 * The class is stripped by the "CarbonFields" prefix.
784
	 * Also the "Field" suffix is removed.
785
	 * Then underscores and backslashes are removed.
786
	 *
787
	 * @return string
788
	 */
789
	public function get_type() {
790
		$class = get_class( $this );
791
792
		return $this->clean_type( $class );
793
	}
794
795
	/**
796
	 * Cleans up an object class for usage as HTML class
797
	 *
798
	 * @return string
799
	 */
800
	protected function clean_type( $type ) {
801
		$remove = array(
802
			'_',
803
			'\\',
804
			'CarbonFields',
805
			'Field',
806
		);
807
		$clean_class = str_replace( $remove, '', $type );
808
809
		return $clean_class;
810
	}
811
812
	/**
813
	 * Return an array of html classes to be used for the field container
814
	 *
815
	 * @return array
816
	 */
817
	public function get_html_class() {
818
		$html_classes = array();
819
820
		$object_class = get_class( $this );
821
		$html_classes[] = $this->get_type();
822
823
		$parent_class = $object_class;
824
		while ( $parent_class = get_parent_class( $parent_class ) ) {
825
			$clean_class = $this->clean_type( $parent_class );
826
827
			if ( $clean_class ) {
828
				$html_classes[] = $clean_class;
829
			}
830
		}
831
832
		return $html_classes;
833
	}
834
835
	/**
836
	 * Returns an array that holds the field data, suitable for JSON representation.
837
	 * This data will be available in the Underscore template and the Backbone Model.
838
	 *
839
	 * @param bool $load  Should the value be loaded from the database or use the value from the current instance.
840
	 * @return array
841
	 */
842
	public function to_json( $load ) {
843
		if ( $load ) {
844
			$this->load();
845
		}
846
847
		$field_data = array(
848
			'id' => $this->get_id(),
849
			'type' => $this->get_type(),
850
			'label' => $this->get_label(),
851
			'name' => $this->get_name(),
852
			'base_name' => $this->get_base_name(),
853
			'value' => $this->get_value(),
854
			'default_value' => $this->get_default_value(),
855
			'help_text' => $this->get_help_text(),
856
			'context' => $this->get_context(),
857
			'required' => $this->is_required(),
858
			'lazyload' => $this->get_lazyload(),
859
			'width' => $this->get_width(),
860
			'classes' => $this->get_classes(),
861
			'conditional_logic' => $this->get_conditional_logic(),
862
		);
863
864
		return $field_data;
865
	}
866
867
	/**
868
	 * Set the field visibility conditional logic.
869
	 *
870
	 * @param array
871
	 */
872 8
	public function set_conditional_logic( $rules ) {
873 8
		$this->conditional_logic = $this->parse_conditional_rules( $rules );
874
875 3
		return $this;
876
	}
877
878
	/**
879
	 * Get the conditional logic rules
880
	 *
881
	 * @return array
882
	 */
883 3
	public function get_conditional_logic() {
884 3
		return $this->conditional_logic;
885
	}
886
887
	/**
888
	 * Validate and parse the conditional logic rules.
889
	 *
890
	 * @param array $rules
891
	 * @return array
892
	 */
893
	protected function parse_conditional_rules( $rules ) {
894
		if ( ! is_array( $rules ) ) {
895
			Incorrect_Syntax_Exception::raise( 'Conditional logic rules argument should be an array.' );
896
		}
897
898
		$allowed_operators = array( '=', '!=', '>', '>=', '<', '<=', 'IN', 'NOT IN' );
899
		$allowed_relations = array( 'AND', 'OR' );
900
901
		$parsed_rules = array(
902
			'relation' => 'AND',
903
			'rules' => array(),
904
		);
905
906
		foreach ( $rules as $key => $rule ) {
907
			// Check if we have a relation key
908 View Code Duplication
			if ( $key === 'relation' ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
909
				$relation = strtoupper( $rule );
910
911
				if ( ! in_array( $relation, $allowed_relations ) ) {
912
					Incorrect_Syntax_Exception::raise( 'Invalid relation type ' . $rule . '. ' .
913
					'The rule should be one of the following: "' . implode( '", "', $allowed_relations ) . '"' );
914
				}
915
916
				$parsed_rules['relation'] = $relation;
917
				continue;
918
			}
919
920
			// Check if the rule is valid
921
			if ( ! is_array( $rule ) || empty( $rule['field'] ) ) {
922
				Incorrect_Syntax_Exception::raise( 'Invalid conditional logic rule format. ' .
923
				'The rule should be an array with the "field" key set.' );
924
			}
925
926
			// Check the compare operator
927
			if ( empty( $rule['compare'] ) ) {
928
				$rule['compare'] = '=';
929
			}
930
			if ( ! in_array( $rule['compare'], $allowed_operators ) ) {
931
				Incorrect_Syntax_Exception::raise( 'Invalid conditional logic compare operator: <code>' .
932
					$rule['compare'] . '</code><br>Allowed operators are: <code>' .
933
				implode( ', ', $allowed_operators ) . '</code>' );
934
			}
935
			if ( $rule['compare'] === 'IN' || $rule['compare'] === 'NOT IN' ) {
936
				if ( ! is_array( $rule['value'] ) ) {
937
					Incorrect_Syntax_Exception::raise( 'Invalid conditional logic value format. ' .
938
					'An array is expected, when using the "' . $rule['compare'] . '" operator.' );
939
				}
940
			}
941
942
			// Check the value
943
			if ( ! isset( $rule['value'] ) ) {
944
				$rule['value'] = '';
945
			}
946
947
			$parsed_rules['rules'][] = $rule;
948
		}
949
950
		return $parsed_rules;
951
	}
952
953
	/**
954
	 * Configuration function for setting the field visibility in the response of the requests to the REST API
955
	 * 
956
	 * @param bool $visible
957
	 * @return Field $this
958
	 */
959
	public function show_in_rest( $visible = true ) {
960
		$this->set_visible_in_rest_api( $visible );
961
		return $this;
962
	}
963
	/**
964
	 * Set the REST visibility of the field
965
	 * 
966
	 * @param bool $visible
967
	 */
968
	public function set_visible_in_rest_api( $visible ) {
969
		$this->visible_in_rest_api = $visible;
970
	}
971
	/**
972
	 * Get the REST visibility of the field
973
	 * 
974
	 * @return bool
975
	 */
976
	public function get_visible_in_rest_api() {
977
		return $this->visible_in_rest_api;
978
	}
979
980
	/**
981
	 * Hook administration scripts.
982
	 */
983
	public static function admin_hook_scripts() {
984
		wp_enqueue_media();
985
		wp_enqueue_script( 'carbon-fields', \Carbon_Fields\URL . '/assets/js/fields.js', array( 'carbon-app', 'carbon-containers' ), \Carbon_Fields\VERSION );
986
		wp_localize_script( 'carbon-fields', 'crbl10n',
987
			array(
988
				'title' => __( 'Files', \Carbon_Fields\TEXT_DOMAIN ),
989
				'geocode_zero_results' => __( 'The address could not be found. ', \Carbon_Fields\TEXT_DOMAIN ),
990
				'geocode_not_successful' => __( 'Geocode was not successful for the following reason: ', \Carbon_Fields\TEXT_DOMAIN ),
991
				'max_num_items_reached' => __( 'Maximum number of items reached (%s items)', \Carbon_Fields\TEXT_DOMAIN ),
992
				'max_num_rows_reached' => __( 'Maximum number of rows reached (%s rows)', \Carbon_Fields\TEXT_DOMAIN ),
993
				'cannot_create_more_rows' => __( 'Cannot create more than %s rows', \Carbon_Fields\TEXT_DOMAIN ),
994
				'complex_no_rows' => __( 'There are no %s yet. Click <a href="#">here</a> to add one.', \Carbon_Fields\TEXT_DOMAIN ),
995
				'complex_add_button' => __( 'Add %s', \Carbon_Fields\TEXT_DOMAIN ),
996
				'complex_min_num_rows_not_reached' => __( 'Minimum number of rows not reached (%1$d %2$s)', \Carbon_Fields\TEXT_DOMAIN ),
997
				'message_form_validation_failed' => __( 'Please fill out all fields correctly. ', \Carbon_Fields\TEXT_DOMAIN ),
998
				'message_required_field' => __( 'This field is required. ', \Carbon_Fields\TEXT_DOMAIN ),
999
				'message_choose_option' => __( 'Please choose an option. ', \Carbon_Fields\TEXT_DOMAIN ),
1000
1001
				'enter_name_of_new_sidebar' => __( 'Please enter the name of the new sidebar:', \Carbon_Fields\TEXT_DOMAIN ),
1002
			)
1003
		);
1004
	}
1005
1006
	/**
1007
	 * Hook administration styles.
1008
	 */
1009
	public static function admin_hook_styles() {
1010
		wp_enqueue_style( 'thickbox' );
1011
	}
1012
}
1013