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

Rest_Field::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
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
		if ( ! function_exists( 'register_rest_field' ) ) {
16
			return;
17
		}
18
19
20
		$post_types = Wordlift_Entity_Service::valid_entity_post_types();
21
22
		foreach ( $post_types as $post_type ) {
23
24
			register_rest_field(
25
				$post_type,
26
				\Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY,
27
				array(
28
					'get_callback'    => array( $this, 'get_value' ),
29
					'update_callback' => array( $this, 'update_value' )
30
				)
31
			);
32
33
		}
34
35
36
	}
37
38
	/**
39
	 * @param $meta_values array
40
	 * @param $post \WP_Post
41
	 * @param $meta_key string
42
	 */
43
	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...
44
45
		if ( ! is_array( $meta_values ) ) {
46
			return;
47
		}
48
		delete_post_meta( $post->ID, Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY );
49
50
		// @todo: check if the keys have to be unique.
51
		$meta_values = array_unique( $meta_values );
52
53
		foreach ( $meta_values as $item ) {
54
			add_post_meta( $post->ID, \Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY, $item );
55
		}
56
	}
57
58
	/**
59
	 * @param $post array Post array.
60
	 *
61
	 * @return array|mixed
62
	 */
63
	public function get_value( $post ) {
64
		$data = get_post_meta( (int) $post["id"], \Wordlift_Entity_Service::ALTERNATIVE_LABEL_META_KEY );
65
		if ( ! is_array( $data ) ) {
66
			return array();
67
		}
68
69
		return $data;
70
	}
71
72
73
}