Jake Vanderwerf
2025-10-20 e729f920139f0c65902be2d6b2c32466b08375e8
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
<?php
namespace JVBase\meta;
 
use JVBase\registry\ContentRegistry;
use InvalidArgumentException;
 
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
 
class MetaRegistry
{
    protected string $object; //post type or taxonomy slug
    protected string $object_type; //post, term, user, [comment]
    protected MetaManager $meta_manager;
    protected array $fields;
    protected string $prefix = BASE;
 
    public function __construct(array $fields, string $object, string $object_type)
    {
        if (!in_array($object_type, ['post', 'term', 'user'])) {
            return;
        }
 
        $this->fields = $fields;
 
        $this->object = jvbCheckBase($object);
        $this->object_type = $object_type;
        $this->meta_manager = new MetaManager();
    }
 
    /**
     * Register meta fields
     */
    public function registerMetaFields():void
    {
        $fields = $this->fields;
 
        foreach ($fields as $name => $options) {
            if (in_array($name, [
                'post_title',
                'post_content',
                'post_excerpt',
                'featured_image',
                'display_name',
                'user_email',
            ])) {
                unset($fields[$name]);
            }
        }
        foreach ($fields as $field_name => $field) {
            $this->validateFieldType($field_name, $field);
            $field = array_merge($this->meta_manager->type_manager->getType($field['type']), $field);
            $args = $this->getFieldArgs($field_name, $field);
 
            // Allow modification of field registration args
            $args = apply_filters(
                BASE . 'meta_field_args',
                $args,
                $field_name,
                $field,
                $this->object_type
            );
 
            $temp = register_meta($this->object_type, $this->prefix . $field_name, $args);
 
 
            if (!$temp) {
                $args['auth_callback'] = gettype($args['auth_callback']);
                error_log('Error with registering meta:'.print_r([
                    'object_type' => $this->object_type,
                    'prefix'    => $this->prefix,
                    'field_name' => $field_name,
                    'args'      => $args,
                    ], true));
            }
 
            do_action(BASE . 'meta_field_registered', $field_name, $field, $this);
        }
    }
 
    protected function validateFieldType(string $field_name, array $field):void
    {
        $required = ['name', 'type', 'label'];
        $field['name'] = $field_name;
        foreach ($required as $type) {
            if (!isset($field[$type])) {
                throw new InvalidArgumentException(sprintf('Field %s is required', $type));
            }
        }
    }
 
    protected function getFieldArgs(string $field_name, array $field):array
    {
        $args = [
            'object_subtype' => $this->object,
            'type' => $this->meta_manager->getMetaType($field['type']),
            'label' => __($field['label'], 'jvb') ?? '',
            'description' => __($field['description']?? '', 'jvb') ,
            'single' => true,
            'show_in_rest' => $field['show_in_rest'] ?? true,
            'sanitize_callback' => $this->meta_manager->getSanitizeCallback($field),
            'auth_callback' => [$this, 'validate_permissions'],
            'default' => $field['default'] ?? '',
 
        ];
 
        if ($this->object_type === 'post') {
            $args['revisions_enabled'] = true;
        }
 
 
        // Add schema for complex fields
        if (in_array($field['type'], ['repeater', 'group', 'location']) || $args['type'] === 'array') {
            $args['show_in_rest'] = [
                'schema' => $this->getFieldSchema($field)
            ];
        }
 
        return $args;
    }
 
    /**
     * Get schema for complex field types
     */
    protected function getFieldSchema(array $field):array
    {
        if ($field['type'] === 'repeater') {
            $properties = [];
            foreach ($field['fields'] as $key => $subfield) {
                $properties[$key] = [
                    'type' => $this->meta_manager->getMetaType($subfield['type'])
                ];
            }
 
            return [
                'type' => 'object',
                'items' => [
                    'type' => 'object',
                    'properties' => $properties
                ]
            ];
        } elseif ($field['type'] === 'group') {
            $properties = [];
            foreach ($field['fields'] as $key => $subfield) {
                $properties[$key] = [
                    'type' => $this->meta_manager->getMetaType($subfield['type'])
                ];
 
                // Add description if available
                if (isset($subfield['description'])) {
                    $properties[$key]['description'] = $subfield['description'];
                }
 
                // Add enum for select/radio fields
                if (in_array($subfield['type'], ['select', 'radio']) && isset($subfield['options'])) {
                    $properties[$key]['enum'] = array_keys($subfield['options']);
                }
            }
 
            return [
                'type' => 'object',
                'properties' => $properties,
                'additionalProperties' => false
            ];
        } elseif ($field['type'] === 'location') {
            return [
                'type' => 'object',
                'properties' => [
                    'address' => ['type' => 'string'],
                    'lat' => ['type' => 'number'],
                    'lng' => ['type' => 'number']
                ]
            ];
        }
 
        return [
            'items'     => ['type' => 'string']
        ];
    }
 
 
    protected function logError(string $message, array $context = [])
    {
        error_log(sprintf(
            '[MetaRegistry] %s | Context: %s',
            $message,
            json_encode($context)
        ));
    }
}