Completed
Push — develop ( c1be74...f8bbf2 )
by David
06:55
created

Sync_Hooks_Entity_Relation::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Wordlift\Dataset;
4
5
use Wordlift\Object_Type_Enum;
6
7
/**
8
 * @since 3.28.0
9
 * @author Naveen Muthusamy <[email protected]>
10
 */
11
12
/**
13
 * This class adds `relation` property to entity jsonld by using `wl_entity_jsonld_array hook`.
14
 * Class Entity_Dct_Relation
15
 */
16
class Sync_Hooks_Entity_Relation {
17
18
	/**
19
	 * @var \Wordlift_Entity_Service
20
	 */
21
	private $entity_service;
22
23
	/**
24
	 * Entity_Dct_Relation constructor.
25
	 *
26
	 * @param $entity_service \Wordlift_Entity_Service
27
	 */
28
	public function __construct( $entity_service ) {
29
		$this->entity_service = $entity_service;
30
31
		add_filter( 'wl_dataset__sync_service__sync_item__jsonld', array( $this, 'jsonld' ), 10, 3 );
32
	}
33
34
	public function jsonld( $jsonld, $type, $post_id ) {
35
36
		// @@todo add support for terms.
37
		if ( Object_Type_Enum::TERM === $type ) {
38
			return $jsonld;
39
		}
40
41
		// Choose the dcterm property according to the post type.
42
		$property = $this->entity_service->is_entity( $post_id )
43
			? 'http://purl.org/dc/terms/relation'
44
			: 'http://purl.org/dc/terms/references';
45
46
		$references = array_unique( $this->entity_service->get_related_entities( $post_id ) );
47
48
		// Bail out if there are no references.
49
		if ( empty( $references ) ) {
50
			return $jsonld;
51
		}
52
53
		if ( ! isset( $jsonld[0][ $property ] ) ) {
54
			$jsonld[0][ $property ] = array();
55
		}
56
57
		if ( ! is_array( $jsonld[0][ $property ] ) ) {
58
			$jsonld[0][ $property ] = array( $jsonld[0][ $property ] );
59
		}
60
61
		$that             = $this;
62
		$references_array = array_values( array_map( function ( $item ) use ( $that ) {
63
			return array( '@id' => $that->entity_service->get_uri( $item ) );
64
		}, $references ) );
65
66
		$jsonld[0][ $property ] = array_merge( $jsonld[0][ $property ], $references_array );
67
68
		return $jsonld;
69
	}
70
71
}
72