Jake Vanderwerf
2025-09-30 2cb91676044ecd0abd9c45b4835abb8b0d042312
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
<?php
namespace JVBase\utility;
 
if (!defined('ABSPATH')) {
    exit;
}
/**
 * Centralized registry for all content types, taxonomies, and user roles
 * Provides a single source of truth and caching layer
 */
class Checker
{
    private static ?Checker $instance = null;
    private array $cache = [];
    private array $relationships = [];
 
    // Cache keys for different registries
    const CACHE_CONTENT = 'content_types';
    const CACHE_TAXONOMIES = 'taxonomies';
    const CACHE_USER_ROLES = 'user_roles';
    const CACHE_RELATIONSHIPS = 'relationships';
 
    private function __construct()
    {
        $this->initialize();
    }
 
    public static function getInstance(): self
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
 
    /**
     * Initialize all registries and build relationships
     */
    private function initialize(): void
    {
        // Build initial caches
        $this->buildContentCache();
        $this->buildTaxonomyCache();
        $this->buildUserRoleCache();
        $this->buildRelationships();
 
        // Set up WordPress hooks for cache invalidation
        add_action('init', [$this, 'validateRegistrations'], 1);
        add_action('registered_post_type', [$this, 'invalidateContentCache']);
        add_action('registered_taxonomy', [$this, 'invalidateTaxonomyCache']);
    }
 
    /**
     * Get all content types with optional filtering
     */
    public function getContentTypes(array $filters = []): array
    {
        $content = $this->cache[self::CACHE_CONTENT] ?? [];
 
        if (empty($filters)) {
            return $content;
        }
 
        return $this->applyFilters($content, $filters);
    }
 
    /**
     * Get all taxonomies with optional filtering
     */
    public function getTaxonomies(array $filters = []): array
    {
        $taxonomies = $this->cache[self::CACHE_TAXONOMIES] ?? [];
 
        if (empty($filters)) {
            return $taxonomies;
        }
 
        return $this->applyFilters($taxonomies, $filters);
    }
 
    /**
     * Get user roles with specific capabilities
     */
    public function getUserRoles(array $filters = []): array
    {
        $roles = $this->cache[self::CACHE_USER_ROLES] ?? [];
 
        if (empty($filters)) {
            return $roles;
        }
 
        return $this->applyFilters($roles, $filters);
    }
 
    /**
     * Get taxonomies for a specific content type
     */
    public function getTaxonomiesForContent(string $contentType): array
    {
        $contentType = jvbNoBase($contentType);
        return $this->relationships['content_taxonomies'][$contentType] ?? [];
    }
 
    /**
     * Get content types for a specific taxonomy
     */
    public function getContentForTaxonomy(string $taxonomy): array
    {
        $taxonomy = jvbNoBase($taxonomy);
        return $this->relationships['taxonomy_content'][$taxonomy] ?? [];
    }
 
    /**
     * Get content types a user role can create
     */
    public function getCreatableContent(string $role): array
    {
        $role = jvbNoBase($role);
        return $this->relationships['role_content'][$role] ?? [];
    }
 
    /**
     * Check if a type has a specific feature
     */
    public function hasFeature(string $type, string $feature, string $registry = 'content'): bool
    {
        $type = jvbNoBase($type);
 
        $data = match ($registry) {
            'content' => $this->cache[self::CACHE_CONTENT][$type] ?? [],
            'taxonomy' => $this->cache[self::CACHE_TAXONOMIES][$type] ?? [],
            'user' => $this->cache[self::CACHE_USER_ROLES][$type] ?? [],
            default => []
        };
 
        return isset($data[$feature]) && $data[$feature] === true;
    }
 
    /**
     * Get all types with a specific feature
     */
    public function getTypesWithFeature(string $feature, string $registry = 'content'): array
    {
        $filters = [$feature => true];
 
        return match ($registry) {
            'content' => $this->getContentTypes($filters),
            'taxonomy' => $this->getTaxonomies($filters),
            'user' => $this->getUserRoles($filters),
            default => []
        };
    }
 
    /**
     * Build content type cache
     */
    private function buildContentCache(): void
    {
        $this->cache[self::CACHE_CONTENT] = JVB_CONTENT;
 
        // Add computed properties
        foreach ($this->cache[self::CACHE_CONTENT] as $slug => &$config) {
            $config['_slug'] = $slug;
            $config['_post_type'] = BASE . $slug;
            $config['_supports_dashboard'] = $this->computesDashboardSupport($config);
            $config['_is_user_type'] = $this->computesUserType($config);
        }
    }
 
    /**
     * Build taxonomy cache
     */
    private function buildTaxonomyCache(): void
    {
        $this->cache[self::CACHE_TAXONOMIES] = JVB_TAXONOMY;
 
        foreach ($this->cache[self::CACHE_TAXONOMIES] as $slug => &$config) {
            $config['_slug'] = $slug;
            $config['_taxonomy'] = BASE . $slug;
            $config['_is_hierarchical'] = $config['hierarchical'] ?? true;
        }
    }
 
    /**
     * Build user role cache
     */
    private function buildUserRoleCache(): void
    {
        $this->cache[self::CACHE_USER_ROLES] = JVB_USER;
 
        foreach ($this->cache[self::CACHE_USER_ROLES] as $slug => &$config) {
            $config['_slug'] = $slug;
            $config['_role'] = BASE . $slug;
            $config['_creatable_content'] = $this->extractCreatableContent($config);
        }
    }
 
    /**
     * Build relationships between types
     */
    private function buildRelationships(): void
    {
        // Content -> Taxonomies
        foreach ($this->cache[self::CACHE_CONTENT] as $contentSlug => $content) {
            $this->relationships['content_taxonomies'][$contentSlug] = [];
        }
 
        // Taxonomy -> Content
        foreach ($this->cache[self::CACHE_TAXONOMIES] as $taxSlug => $taxonomy) {
            $this->relationships['taxonomy_content'][$taxSlug] = $taxonomy['for_content'] ?? [];
 
            // Build reverse relationship
            foreach ($taxonomy['for_content'] ?? [] as $contentType) {
                $this->relationships['content_taxonomies'][$contentType][] = $taxSlug;
            }
        }
 
        // User Role -> Content
        foreach ($this->cache[self::CACHE_USER_ROLES] as $roleSlug => $role) {
            $this->relationships['role_content'][$roleSlug] = $role['_creatable_content'];
        }
 
        $this->cache[self::CACHE_RELATIONSHIPS] = $this->relationships;
    }
 
    /**
     * Apply filters to a registry array
     */
    private function applyFilters(array $data, array $filters): array
    {
        return array_filter($data, function ($item) use ($filters) {
            foreach ($filters as $key => $value) {
                if (!isset($item[$key]) || $item[$key] !== $value) {
                    return false;
                }
            }
            return true;
        });
    }
 
    /**
     * Extract creatable content from user role config
     */
    private function extractCreatableContent(array $config): array
    {
        $content = [];
 
        foreach ($config['can_create'] ?? [] as $item) {
            if (is_array($item)) {
                foreach ($item as $type => $contents) {
                    $content = array_merge($content, $contents);
                }
            } else {
                $content[] = $item;
            }
        }
 
        return array_unique($content);
    }
 
    /**
     * Check if content type supports dashboard
     */
    private function computesDashboardSupport(array $config): bool
    {
        return !empty($config['fields']) ||
            !empty($config['sections']) ||
            ($config['show_dashboard'] ?? false);
    }
 
    /**
     * Check if content type is a user profile type
     */
    private function computesUserType(array $config): bool
    {
        foreach ($this->cache[self::CACHE_USER_ROLES] ?? [] as $role) {
            if (($role['profile'] ?? '') === $config['_slug']) {
                return true;
            }
        }
        return false;
    }
 
    /**
     * Validate all registrations are properly set up
     */
    public function validateRegistrations(): void
    {
        $errors = [];
 
        // Validate taxonomy relationships
        foreach ($this->getTaxonomies() as $taxSlug => $taxonomy) {
            foreach ($taxonomy['for_content'] ?? [] as $contentType) {
                if (!isset($this->cache[self::CACHE_CONTENT][$contentType])) {
                    $errors[] = "Taxonomy '{$taxSlug}' references non-existent content type '{$contentType}'";
                }
            }
        }
 
        // Validate user role content permissions
        foreach ($this->getUserRoles() as $roleSlug => $role) {
            foreach ($role['_creatable_content'] as $contentType) {
                if (!isset($this->cache[self::CACHE_CONTENT][$contentType]) &&
                    !isset($this->cache[self::CACHE_TAXONOMIES][$contentType])) {
                    $errors[] = "Role '{$roleSlug}' references non-existent type '{$contentType}'";
                }
            }
        }
 
        if (!empty($errors) && WP_DEBUG) {
            foreach ($errors as $error) {
                error_log("[Checker Validation] {$error}");
            }
        }
    }
 
    /**
     * Invalidate content cache
     */
    public function invalidateContentCache(): void
    {
        unset($this->cache[self::CACHE_CONTENT]);
        $this->buildContentCache();
        $this->buildRelationships();
    }
 
    /**
     * Invalidate taxonomy cache
     */
    public function invalidateTaxonomyCache(): void
    {
        unset($this->cache[self::CACHE_TAXONOMIES]);
        $this->buildTaxonomyCache();
        $this->buildRelationships();
    }
 
    /**
     * Get registry statistics for debugging
     */
    public function getStats(): array
    {
        return [
            'content_types' => count($this->cache[self::CACHE_CONTENT] ?? []),
            'taxonomies' => count($this->cache[self::CACHE_TAXONOMIES] ?? []),
            'user_roles' => count($this->cache[self::CACHE_USER_ROLES] ?? []),
            'relationships' => count($this->relationships),
            'cache_size' => strlen(serialize($this->cache))
        ];
    }
}