Completed
Push — milestone/2.0 ( 27edeb...debc3a )
by
unknown
02:20
created

Post_Meta_Container::show_on_template()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 6
nop 1
dl 0
loc 18
ccs 11
cts 11
cp 1
crap 4
rs 9.2
c 0
b 0
f 0
1
<?php
2
3
namespace Carbon_Fields\Container;
4
5
use Carbon_Fields\Datastore\Datastore;
6
use Carbon_Fields\Exception\Incorrect_Syntax_Exception;
7
8
/**
9
 * Field container designed to extend WordPress custom fields functionality,
10
 * providing easier user interface to add, edit and delete text, media files,
11
 * location information and more.
12
 */
13
class Post_Meta_Container extends Container {
14
	/**
15
	 * ID of the post the container is working with
16
	 *
17
	 * @see init()
18
	 * @var int
19
	 */
20
	protected $post_id;
21
22
	/**
23
	 * List of default container settings
24
	 *
25
	 * @see init()
26
	 * @var array
27
	 */
28
	public $settings = array(
29
		'post_type' => array( 'post' ),
30
		'panel_context' => 'normal',
31
		'panel_priority' => 'high',
32
		'show_on' => array(
33
			'category' => null,
34
			'template_names' => array(),
35
			'not_in_template_names' => array(),
36
			'post_formats' => array(),
37
			'level_limit' => null,
38
			'tax_term_id' => null,
39
			'page_id' => null,
40
			'parent_page_id' => null,
41
			'post_path' => null,
42
		),
43
	);
44
45
	/**
46
	 * Create a new container
47
	 *
48
	 * @param string $unique_id Unique id of the container
49
	 * @param string $title title of the container
50
	 * @param string $type Type of the container
51
	 **/
52 View Code Duplication
	public function __construct( $unique_id, $title, $type ) {
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...
53
		parent::__construct( $unique_id, $title, $type );
54
55
		if ( ! $this->get_datastore() ) {
56
			$this->set_datastore( Datastore::make( 'post_meta' ), $this->has_default_datastore() );
57
		}
58
	}
59
60
	/**
61
	 * Create DataStore instance, set post ID to operate with (if such exists).
62
	 * Bind attach() and save() to the appropriate WordPress actions.
63
	 **/
64
	public function init() {
65
		if ( isset( $_GET['post'] ) ) {
1 ignored issue
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
66
			$this->set_post_id( $_GET['post'] );
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
67
		}
68
69
		// force post_type to be array
70
		if ( ! is_array( $this->settings['post_type'] ) ) {
71
			$this->settings['post_type'] = array( $this->settings['post_type'] );
72
		}
73
74
		add_action( 'admin_init', array( $this, '_attach' ) );
75
		add_action( 'save_post', array( $this, '_save' ) );
76
77
		// support for attachments
78
		add_action( 'add_attachment', array( $this, '_save' ) );
79
		add_action( 'edit_attachment', array( $this, '_save' ) );
80
	}
81
82
	/**
83
	 * Perform save operation after successful is_valid_save() check.
84
	 * The call is propagated to all fields in the container.
85
	 *
86
	 * @param int $post_id ID of the post against which save() is ran
87
	 **/
88 View Code Duplication
	public function save( $post_id ) {
89
		// Unhook action to garantee single save
90
		remove_action( 'save_post', array( $this, '_save' ) );
91
92
		$this->set_post_id( $post_id );
93
94
		foreach ( $this->fields as $field ) {
95
			$field->set_value_from_input();
96
			$field->save();
97
		}
98
99
		do_action( 'carbon_after_save_custom_fields', $post_id );
100
		do_action( 'carbon_after_save_post_meta', $post_id );
101
	}
102
103
	/**
104
	 * Perform checks whether the current save() request is valid
105
	 * Possible errors are triggering save() for autosave requests
106
	 * or performing post save outside of the post edit page (like Quick Edit)
107
	 *
108
	 * @see is_valid_save_conditions()
109
	 * @param int $post_id ID of the post against which save() is ran
110
	 * @return bool
111
	 **/
112
	public function is_valid_save( $post_id = 0 ) {
113
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
114
			return false;
115 View Code Duplication
		} else if ( ! isset( $_REQUEST[ $this->get_nonce_name() ] ) || ! wp_verify_nonce( $_REQUEST[ $this->get_nonce_name() ], $this->get_nonce_name() ) ) { // Input var okay.
0 ignored issues
show
introduced by
Detected usage of a non-sanitized input variable: $_REQUEST
Loading history...
116
			return false;
117
		} else if ( $post_id < 1 ) {
118
			return false;
119
		}
120
121
		return $this->is_valid_save_conditions( $post_id );
122
	}
123
124
	/**
125
	 * Perform checks whether the current save() request is valid
126
	 * Possible errors are triggering save() for autosave requests
127
	 * or performing post save outside of the post edit page (like Quick Edit)
128
	 *
129
	 * @param int $post_id ID of the post against which save() is ran
130
	 * @return bool
131
	 **/
132
	public function is_valid_save_conditions( $post_id ) {
133
		$valid = true;
134
		$post = get_post( $post_id );
135
136
		// Check post type
137
		if ( ! in_array( $post->post_type, $this->settings['post_type'] ) ) {
138
			return false;
139
		}
140
141
		// Check show on conditions
142
		foreach ( $this->settings['show_on'] as $condition => $value ) {
143
			if ( is_null( $value ) ) {
144
				continue;
145
			}
146
147
			switch ( $condition ) {
148
				// show_on_post_format
149
				case 'post_formats':
150
					if ( empty( $value ) || $post->post_type != 'post' ) {
151
						break;
152
					}
153
154
					$current_format = get_post_format( $post_id );
155
					if ( ! in_array( $current_format, $value ) ) {
156
						$valid = false;
157
						break 2;
158
					}
159
160
					break;
161
162
				// show_on_taxonomy_term or show_on_category
163
				case 'category':
164
					$this->show_on_category( $value );
165
166
					/* fall-through intended */
167
				case 'tax_term_id':
168
					$current_terms = wp_get_object_terms( $post_id, $this->settings['show_on']['tax_slug'], array( 'fields' => 'ids' ) );
169
170
					if ( ! is_array( $current_terms ) || ! in_array( $this->settings['show_on']['tax_term_id'], $current_terms ) ) {
171
						$valid = false;
172
						break 2;
173
					}
174
175
					break;
176
177
				// show_on_level
178
				case 'level_limit':
179
					$post_level = count( get_post_ancestors( $post_id ) ) + 1;
180
181
					if ( $post_level != $value ) {
182
						$valid = false;
183
						break 2;
184
					}
185
186
					break;
187
188
				// show_on_page
189
				case 'page_id':
190
					if ( $post_id != $value ) {
191
						$valid = false;
192
						break 2;
193
					}
194
195
					break;
196
197
				// show_on_page_children
198
				case 'parent_page_id':
199
					if ( $post->post_parent != $value ) {
200
						$valid = false;
201
						break 2;
202
					}
203
204
					break;
205
206
				// show_on_template
207 View Code Duplication
				case 'template_names':
1 ignored issue
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...
208
					if ( empty( $value ) || $post->post_type != 'page' ) {
209
						break;
210
					}
211
					$current_template = get_post_meta( $post_id, '_wp_page_template', 1 );
212
213
					if ( ! in_array( $current_template, $value ) ) {
214
						$valid = false;
215
						break 2;
216
					}
217
218
					break;
219
220
				// hide_on_template
221 View Code Duplication
				case 'not_in_template_names':
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...
222
					if ( empty( $value ) || $post->post_type != 'page' ) {
223
						break;
224
					}
225
					$current_template = get_post_meta( $post_id, '_wp_page_template', 1 );
226
227
					if ( in_array( $current_template, $value ) ) {
228
						$valid = false;
229
						break 2;
230
					}
231
232
					break;
233
			}
234
		}
235
236
		return $valid;
237
	}
238
239
	/**
240
	 * Perform checks whether the container should be attached during the current request
241
	 *
242
	 * @return bool True if the container is allowed to be attached
243
	 **/
244
	public function _is_valid_attach() {
245
		global $pagenow;
246
247
		if ( $pagenow !== 'post.php' && $pagenow !== 'post-new.php' ) {
248
			return false;
249
		}
250
251
		// Post types check
252
		if ( ! empty( $this->settings['post_type'] ) ) {
253
			$post_type = '';
254
255
			if ( $this->post_id ) {
256
				$post_type = get_post_type( $this->post_id );
257
			} elseif ( ! empty( $_GET['post_type'] ) ) {
258
				$post_type = $_GET['post_type'];
0 ignored issues
show
introduced by
Detected access of super global var $_GET, probably need manual inspection.
Loading history...
introduced by
Detected usage of a non-sanitized input variable: $_GET
Loading history...
259
			} elseif ( $pagenow === 'post-new.php' ) {
260
				$post_type = 'post';
261
			}
262
263
			if ( ! $post_type || ! in_array( $post_type, $this->settings['post_type'] ) ) {
264
				return false;
265
			}
266
		}
267
268
		// Check show on conditions
269
		foreach ( $this->settings['show_on'] as $condition => $value ) {
270
			if ( is_null( $value ) ) {
271
				continue;
272
			}
273
274
			switch ( $condition ) {
275
				case 'page_id':
276
					if ( $value < 1 || $this->post_id != $value ) {
277
						return false;
278
					}
279
					break;
280
				case 'parent_page_id':
281
					// Check if such page exists
282
					if ( $value < 1 ) {
283
						return false;
284
					}
285
					break;
286
			}
287
		}
288
289
		return true;
290
	}
291
292
	/**
293
	 * Add meta box for each of the container post types
294
	 **/
295
	public function attach() {
296
		foreach ( $this->settings['post_type'] as $post_type ) {
297
			add_meta_box(
298
				$this->id,
299
				$this->title,
300
				array( $this, 'render' ),
301
				$post_type,
302
				$this->settings['panel_context'],
303
				$this->settings['panel_priority']
304
			);
305
		}
306
307
		foreach ( $this->settings['post_type'] as $post_type ) {
308
			add_filter( "postbox_classes_{$post_type}_{$this->id}", array( $this, 'add_postbox_classes' ) );
309
		}
310
	}
311
312
	/**
313
	 * Classes to add to the post meta box
314
	 */
315
	public function add_postbox_classes( $classes ) {
316
		$classes[] = 'carbon-box';
317
		return $classes;
318
	}
319
320
	/**
321
	 * Output the container markup
322
	 **/
323
	public function render() {
324
		include \Carbon_Fields\DIR . '/templates/Container/post_meta.php';
325
	}
326
327
	/**
328
	 * Set the post ID the container will operate with.
329
	 *
330
	 * @param int $post_id
331
	 **/
332
	public function set_post_id( $post_id ) {
333
		$this->post_id = $post_id;
334
		$this->get_datastore()->set_id( $post_id );
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Carbon_Fields\Datastore\Datastore_Interface as the method set_id() does only exist in the following implementations of said interface: Carbon_Fields\Datastore\Comment_Meta_Datastore, Carbon_Fields\Datastore\Meta_Datastore, Carbon_Fields\Datastore\Nav_Menu_Item_Datastore, Carbon_Fields\Datastore\Post_Meta_Datastore, Carbon_Fields\Datastore\Term_Meta_Datastore, Carbon_Fields\Datastore\User_Meta_Datastore.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
335
	}
336
337
	/**
338
	 * COMMON USAGE METHODS
339
	 */
340
341
	/**
342
	 * Show the container only on particular page referenced by it's path.
343
	 *
344
	 * @param int|string $page page ID or page path
345
	 * @return object $this
346
	 **/
347 4
	public function show_on_page( $page ) {
348 4
		$page_id = absint( $page );
349
350 4
		if ( $page_id && $page_id == $page ) {
351 2
			$page_obj = get_post( $page_id );
352 2
		} else {
353 2
			$page_obj = get_page_by_path( $page );
354
		}
355
356 4
		$this->show_on_post_type( 'page' );
357
358 4
		if ( $page_obj ) {
359 4
			$this->settings['show_on']['page_id'] = $page_obj->ID;
360 4
		} else {
361
			$this->settings['show_on']['page_id'] = -1;
362
		}
363
364 4
		return $this;
365
	}
366
367
	/**
368
	 * Show the container only on pages whose parent is referenced by $parent_page_path.
369
	 *
370
	 * @param string $parent_page_path
371
	 * @return object $this
372
	 **/
373 1
	public function show_on_page_children( $parent_page_path ) {
374 1
		$page = get_page_by_path( $parent_page_path );
375
376 1
		$this->show_on_post_type( 'page' );
377
378 1
		if ( $page ) {
379 1
			$this->settings['show_on']['parent_page_id'] = $page->ID;
380 1
		} else {
381
			$this->settings['show_on']['parent_page_id'] = -1;
382
		}
383
384 1
		return $this;
385
	}
386
387
	/**
388
	 * Show the container only on posts from the specified category.
389
	 *
390
	 * @see show_on_taxonomy_term()
391
	 *
392
	 * @param string $category_slug
393
	 * @return object $this
394
	 **/
395
	public function show_on_category( $category_slug ) {
396
		$this->settings['show_on']['category'] = $category_slug;
397
398
		return $this->show_on_taxonomy_term( $category_slug, 'category' );
399
	}
400
401
	/**
402
	 * Show the container only on pages whose template has filename $template_path.
403
	 *
404
	 * @param string|array $template_path
405
	 * @return object $this
406
	 **/
407 2
	public function show_on_template( $template_path ) {
408
		// Backwards compatibility where only pages support templates
409 2
		if ( version_compare( get_bloginfo( 'version' ), '4.7', '<' ) ) {
410 2
			$this->show_on_post_type( 'page' );
411 2
		}
412
413 2
		if ( is_array( $template_path ) ) {
414 1
			foreach ( $template_path as $path ) {
415 1
				$this->show_on_template( $path );
416 1
			}
417
418 1
			return $this;
419
		}
420
421 2
		$this->settings['show_on']['template_names'][] = $template_path;
422
423 2
		return $this;
424
	}
425
426
	/**
427
	 * Hide the container from pages whose template has filename $template_path.
428
	 *
429
	 * @param string|array $template_path
430
	 * @return object $this
431
	 **/
432
	public function hide_on_template( $template_path ) {
433
		if ( is_array( $template_path ) ) {
434
			foreach ( $template_path as $path ) {
435
				$this->hide_on_template( $path );
436
			}
437
			return $this;
438
		}
439
440
		$this->settings['show_on']['not_in_template_names'][] = $template_path;
441
442
		return $this;
443
	}
444
445
	/**
446
	 * Show the container only on hierarchical posts of level $level.
447
	 * Levels start from 1 (top level post)
448
	 *
449
	 * @param int $level
450
	 * @return object $this
451
	 **/
452
	public function show_on_level( $level ) {
453
		if ( $level < 0 ) {
454
			Incorrect_Syntax_Exception::raise( 'Invalid level limitation (' . $level . ')' );
455
		}
456
457
		$this->settings['show_on']['level_limit'] = $level;
458
459
		return $this;
460
	}
461
462
	/**
463
	 * Show the container only on posts which have term $term_slug from the $taxonomy_slug taxonomy.
464
	 *
465
	 * @param string $taxonomy_slug
466
	 * @param string $term_slug
467
	 * @return object $this
468
	 **/
469
	public function show_on_taxonomy_term( $term_slug, $taxonomy_slug ) {
470
		$term = get_term_by( 'slug', $term_slug, $taxonomy_slug );
471
472
		$this->settings['show_on']['tax_slug'] = $taxonomy_slug;
473
		$this->settings['show_on']['tax_term'] = $term_slug;
474
		$this->settings['show_on']['tax_term_id'] = $term ? $term->term_id : null;
475
476
		return $this;
477
	}
478
479
	/**
480
	 * Show the container only on posts from the specified format.
481
	 * Learn more about {@link http://codex.wordpress.org/Post_Formats Post Formats (Codex)}
482
	 *
483
	 * @param string|array $post_format Name of the format as listed on Codex
484
	 * @return object $this
485
	 **/
486
	public function show_on_post_format( $post_format ) {
487
		if ( is_array( $post_format ) ) {
488
			foreach ( $post_format as $format ) {
489
				$this->show_on_post_format( $format );
490
			}
491
			return $this;
492
		}
493
494
		if ( $post_format === 'standard' ) {
495
			$post_format = 0;
496
		}
497
498
		$this->settings['show_on']['post_formats'][] = strtolower( $post_format );
499
500
		return $this;
501
	}
502
503
	/**
504
	 * Show the container only on posts from the specified type(s).
505
	 *
506
	 * @param string|array $post_types
507
	 * @return object $this
508
	 **/
509
	public function show_on_post_type( $post_types ) {
510
		$post_types = (array) $post_types;
511
512
		$this->settings['post_type'] = $post_types;
513
514
		return $this;
515
	}
516
517
	/**
518
	 * Sets the meta box container context
519
	 *
520
	 * @see https://codex.wordpress.org/Function_Reference/add_meta_box
521
	 * @param string $context ('normal', 'advanced' or 'side')
522
	 */
523
	public function set_context( $context ) {
524
		$this->settings['panel_context'] = $context;
525
526
		return $this;
527
	}
528
529
	/**
530
	 * Sets the meta box container priority
531
	 *
532
	 * @see https://codex.wordpress.org/Function_Reference/add_meta_box
533
	 * @param string $priority ('high', 'core', 'default' or 'low')
534
	 */
535
	public function set_priority( $priority ) {
536
		$this->settings['panel_priority'] = $priority;
537
538
		return $this;
539
	}
540
}
541