src/Metadata/functions.php source

1 <?php
2
3 namespace mini;
4
5 use mini\Metadata\Metadata;
6 use mini\Metadata\MetadataStore;
7 use mini\Metadata\AttributeMetadataFactory;
8
9 // Register Metadata services
10 Mini::$mini->addService(Metadata::class, Lifetime::Transient, fn() => new Metadata());
11 Mini::$mini->addService(MetadataStore::class, Lifetime::Singleton, fn() => new MetadataStore());
12 Mini::$mini->addService(AttributeMetadataFactory::class, Lifetime::Singleton, fn() => new AttributeMetadataFactory());
13
14 /**
15 * Get or create a Metadata instance
16 *
17 * With no arguments: Returns a new Metadata for building annotations.
18 * With class name: Returns metadata built from class attributes (auto-cached by MetadataStore).
19 * With custom identifier: Returns cached metadata from the store.
20 *
21 * Examples:
22 * ```php
23 * // New metadata
24 * $m = metadata()->title('Username')->description('User login identifier');
25 *
26 * // From class attributes (auto-built and cached)
27 * $userMeta = metadata(User::class);
28 *
29 * // Access property metadata
30 * $usernameMeta = metadata(User::class)->username;
31 *
32 * // Manually store metadata
33 * Mini::$mini->get(MetadataStore::class)[User::class] = metadata()
34 * ->title('User')
35 * ->properties([
36 * 'username' => metadata()->title('Username')->readOnly(true)
37 * ]);
38 * ```
39 *
40 * @param class-string|string|null $classOrName Class name or custom identifier
41 * @return Metadata Metadata instance (empty if not found and not a class)
42 */
43 function metadata(?string $classOrName = null): Metadata
44 {
45 // No argument: return new metadata
46 if ($classOrName === null) {
47 return Mini::$mini->get(Metadata::class);
48 }
49
50 $store = Mini::$mini->get(MetadataStore::class);
51
52 // Get from store (auto-builds from attributes if class/interface)
53 $metadata = $store->get($classOrName);
54
55 // Return metadata or empty instance if not found
56 // This enables reading from unregistered identifiers without throwing exceptions
57 return $metadata ?? new Metadata();
58 }
59