Completed
Pull Request — master (#1409)
by Naveen
03:01
created

Rest_Field   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 0
Metric Value
dl 0
loc 62
rs 10
c 0
b 0
f 0
wmc 8
lcom 0
cbo 1

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A register_rest_field() 0 19 2
A update_value() 0 14 3
A get_value() 0 8 2
1
<?php
2
3
namespace Wordlift\Synonym;
4
5
use Wordlift_Entity_Service;
6
7
class Rest_Field {
8
9
	public function __construct() {
10
		add_action( 'rest_api_init', array( $this, 'register_rest_field' ) );
11
	}
12
13
	public function register_rest_field() {
14
15
		$post_types = Wordlift_Entity_Service::valid_entity_post_types();
16
17
		foreach ( $post_types as $post_type ) {
18
19
			register_rest_field(
20
				$post_type,
21
				\Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY,
22
				array(
23
					'get_callback'    => array( $this, 'get_value' ),
24
					'update_callback' => array( $this, 'update_value' )
25
				)
26
			);
27
28
		}
29
30
31
	}
32
33
	/**
34
	 * @param $meta_values array
35
	 * @param $post \WP_Post
36
	 * @param $meta_key string
37
	 */
38
	public function update_value( $meta_values, $post, $meta_key ) {
0 ignored issues
show
Unused Code introduced by
The parameter $meta_key is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
39
40
		if ( ! is_array( $meta_values ) ) {
41
			return;
42
		}
43
		delete_post_meta( $post->ID, Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY );
44
45
		// @todo: check if the keys have to be unique.
46
		$meta_values = array_unique( $meta_values );
47
48
		foreach ( $meta_values as $item ) {
49
			add_post_meta( $post->ID, \Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY, $item );
50
		}
51
	}
52
53
	/**
54
	 * @param $post array Post array.
55
	 *
56
	 * @return array|mixed
57
	 */
58
	public function get_value( $post ) {
59
		$data = get_post_meta( (int) $post["id"], \Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY );
60
		if ( ! is_array( $data ) ) {
61
			return array();
62
		}
63
64
		return $data;
65
	}
66
67
68
}