Jake Vanderwerf
2026-02-14 27fb820ae9081fb56957cf75e79eccd8a99edd52
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
<?php
namespace JVBase\meta;
 
use InvalidArgumentException;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class Registry
{
    protected string $object;      // post type or taxonomy slug
    protected string $object_type; // post, term, user
    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;
    }
 
    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(MetaTypeManager::getType($field['type']), $field);
            $args = $this->getFieldArgs($field_name, $field);
 
            $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'              => MetaTypeManager::getMetaType($field['type']),
            'label'             => __($field['label'], 'jvb') ?? '',
            'description'       => __($field['description'] ?? '', 'jvb'),
            'single'            => true,
            'show_in_rest'      => $field['show_in_rest'] ?? true,
            'sanitize_callback' => $this->getSanitizeCallback($field),
            'auth_callback'     => [$this, 'validate_permissions'],
            'default'           => $field['default'] ?? '',
        ];
 
        if ($this->object_type === 'post') {
            $args['revisions_enabled'] = true;
        }
 
        if (in_array($field['type'], ['repeater', 'group', 'location']) || $args['type'] === 'array') {
            $args['show_in_rest'] = [
                'schema' => $this->getFieldSchema($field)
            ];
        }
 
        return $args;
    }
 
    /**
     * Build sanitize callback for register_meta
     */
    protected function getSanitizeCallback(array $field): callable
    {
        return fn($value) => Sanitizer::sanitize($value, $field);
    }
 
    protected function getFieldSchema(array $field): array
    {
        if ($field['type'] === 'repeater') {
            $properties = [];
            foreach ($field['fields'] as $key => $subfield) {
                $properties[$key] = [
                    'type' => MetaTypeManager::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' => MetaTypeManager::getMetaType($subfield['type'])
                ];
 
                if (isset($subfield['description'])) {
                    $properties[$key]['description'] = $subfield['description'];
                }
 
                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 = []): void
    {
        error_log(sprintf(
            '[Meta.Registry] %s | Context: %s',
            $message,
            json_encode($context)
        ));
    }
}