Repository navigation
Expand file tree
/
Copy pathclass-wp-agent-citation-metadata.php
More file actions
98 lines (82 loc) · 2.14 KB
/
Copy pathclass-wp-agent-citation-metadata.php
File metadata and controls
98 lines (82 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php
/**
* Canonical citation metadata normalizer.
*
* @package AgentsAPI
*/
namespace AgentsAPI\AI;
defined( 'ABSPATH' ) || exit;
/**
* Normalizes generic retrieved-context citation metadata.
*/
class WP_Agent_Citation_Metadata {
/**
* Canonical citation metadata key.
*/
public const KEY = 'citations';
/**
* Normalize metadata and canonicalize metadata.citations when present.
*
* @param mixed $metadata Raw metadata.
* @return array<mixed>
*/
public static function normalize_metadata( $metadata ): array {
if ( ! is_array( $metadata ) ) {
return array();
}
if ( array_key_exists( self::KEY, $metadata ) ) {
$metadata[ self::KEY ] = self::normalize_many( $metadata[ self::KEY ] );
}
return $metadata;
}
/**
* Normalize a list of citations.
*
* @param mixed $citations Raw citation list.
* @return array<int, array<string, mixed>>
*/
public static function normalize_many( $citations ): array {
if ( ! is_array( $citations ) ) {
return array();
}
$normalized = array();
foreach ( $citations as $citation ) {
if ( ! is_array( $citation ) ) {
continue;
}
$citation = self::normalize( $citation );
if ( ! empty( $citation ) ) {
$normalized[] = $citation;
}
}
return $normalized;
}
/**
* Normalize one citation to the substrate citation shape.
*
* @param array<mixed> $citation Raw citation.
* @return array<string, mixed>
*/
public static function normalize( array $citation ): array {
$normalized = array();
foreach ( $citation as $key => $value ) {
if ( is_string( $key ) ) {
$normalized[ $key ] = $value;
}
}
foreach ( array( 'source', 'source_id', 'item_id', 'fragment_id', 'source_title', 'source_url', 'excerpt' ) as $key ) {
unset( $normalized[ $key ] );
if ( isset( $citation[ $key ] ) && is_scalar( $citation[ $key ] ) ) {
$value = trim( (string) $citation[ $key ] );
if ( '' !== $value ) {
$normalized[ $key ] = $value;
}
}
}
unset( $normalized['score'] );
if ( isset( $citation['score'] ) && is_numeric( $citation['score'] ) ) {
$normalized['score'] = (float) $citation['score'];
}
return $normalized;
}
}