### Full Enumshare Configuration Example Source: https://github.com/olivermbs/enumshare/blob/main/README.md This PHP array shows a comprehensive configuration for Enumshare. It specifies which enums to export, the target directory for TypeScript files, the output mode, and settings for automatic discovery of enums within specified paths. ```php // config/enumshare.php return [ 'enums' => [ App\Enums\Status::class, ], 'path' => resource_path('js/Enums'), 'mode' => 'full', // 'full' or 'minimal' 'auto_discovery' => true, 'auto_paths' => ['app/Enums'], ]; ``` -------------------------------- ### Install Enumshare Package with Composer Source: https://github.com/olivermbs/enumshare/blob/main/README.md This command installs the Enumshare package using Composer, the dependency manager for PHP. It adds the package to your project's dependencies, making its features available for use. ```bash composer require olivermbs/enumshare ``` -------------------------------- ### Enumshare Configuration File Setup Source: https://context7.com/olivermbs/enumshare/llms.txt The `config/enumshare.php` file allows customization of the enum export process. Key settings include explicitly listing enums, setting the output path, choosing the export mode ('full' or 'minimal'), defining default and additional locales, enabling auto-discovery, specifying paths for discovery, and setting a language namespace. ```php [ App\Enums\UserStatus::class, App\Enums\OrderStatus::class, App\Enums\PaymentMethod::class, ], // Output path for generated TypeScript files 'path' => resource_path('js/Enums'), // Output mode: 'full' (with utilities) or 'minimal' (values only) 'mode' => 'full', // Default locale for labels (null uses app()->getLocale()) 'locale' => null, // Additional locales for multilingual exports 'locales' => ['en', 'es', 'fr'], // Enable automatic enum discovery in specified paths 'auto_discovery' => true, // Paths to scan for enum files when auto-discovery is enabled 'auto_paths' => [ 'app/Enums', 'app/Models/Enums', 'src/Domain/*/Enums', ], // Language namespace for automatic label resolution 'lang_namespace' => 'enums', ]; ``` -------------------------------- ### Vue 3 Component Integration with TypeScript Enums Source: https://context7.com/olivermbs/enumshare/llms.txt Illustrates how to integrate generated TypeScript enums within Vue 3 components using the Composition API. This example showcases type-safe usage for displaying status badges and managing a select dropdown, utilizing computed properties and event emissions for reactive updates. ```typescript ``` -------------------------------- ### Enum Export Artisan Command Examples Source: https://context7.com/olivermbs/enumshare/llms.txt The `enums:export` Artisan command is the primary interface for generating TypeScript definitions from PHP enums. It offers various flags to control the export process, such as forcing regeneration, listing enums, creating an index file, exporting types, overriding the output path, and specifying locales. ```bash php artisan enums:export php artisan enums:export --force php artisan enums:export --list php artisan enums:export --index php artisan enums:export --types php artisan enums:export --path=resources/ts/enums php artisan enums:export --locale=es ``` -------------------------------- ### Auto-Regenerate TypeScript Enums with Vite and Wayfinder Source: https://context7.com/olivermbs/enumshare/llms.txt Automatically regenerate TypeScript enums during development using Laravel Wayfinder and Vite. This setup ensures that changes in PHP enums, translations, or configuration files trigger a command to update the TypeScript definitions, keeping them in sync. ```bash # Install Wayfinder dependencies composer require laravel/wayfinder npm install @laravel/vite-plugin-wayfinder ``` ```javascript // vite.config.js import { defineConfig } from 'vite'; import laravel from 'laravel-vite-plugin'; import { wayfinder } from '@laravel/vite-plugin-wayfinder'; export default defineConfig({ plugins: [ laravel({ input: ['resources/css/app.css', 'resources/js/app.ts'], refresh: true, }), wayfinder({ // Regenerate enums whenever PHP enums, translations, or config changes command: 'php artisan enums:export --force', patterns: [ 'app/Enums/**/*.php', 'app/Models/Enums/**/*.php', 'lang/**/*.php', 'config/enumshare.php', ], }), ], }); // Now when you modify any enum file during development, TypeScript // definitions are automatically regenerated ``` -------------------------------- ### Run Project Tests Source: https://github.com/olivermbs/enumshare/blob/main/README.md This command executes the test suite for the Enumshare project using Composer. It helps ensure the package's functionality and stability by running automated tests. ```bash composer test ``` -------------------------------- ### PHP Multilingual Label Support for Enums Source: https://context7.com/olivermbs/enumshare/llms.txt Demonstrates setting up and using enums with translated labels for multiple locales in a PHP application. This includes configuration, language files, enum definition with translated labels, and accessing translated labels in TypeScript. ```php // config/enumshare.php return [ 'locale' => 'en', 'locales' => ['en', 'es', 'fr'], // ... ]; // lang/en/status.php return [ 'active' => 'Active', 'pending' => 'Pending', 'inactive' => 'Inactive', ]; // lang/es/status.php return [ 'active' => 'Activo', 'pending' => 'Pendiente', 'inactive' => 'Inactivo', ]; // App/Enums/Status.php namespace App\Enums; use Olivermbs\Enumshare\Attributes\TranslatedLabel; enum Status: string { #[TranslatedLabel('status.active')] case Active = 'active'; #[TranslatedLabel('status.pending')] case Pending = 'pending'; #[TranslatedLabel('status.inactive')] case Inactive = 'inactive'; } ``` ```typescript // Generated TypeScript with multilingual support import { Status } from '@/Enums/Status'; // Labels are objects with locale keys console.log(Status.Active.label); // { en: 'Active', es: 'Activo', fr: 'Actif' } // Get labels for specific locale const spanishLabels = Status.labels('es'); console.log(spanishLabels); // ['Activo', 'Pendiente', 'Inactivo'] // Options with resolved labels const options = Status.options; // Uses default locale const spanishOptions = Status.options.map(opt => ({ value: opt.value, label: resolveLabel(opt.label, 'es') })); ``` -------------------------------- ### Publish Enumshare Configuration Source: https://github.com/olivermbs/enumshare/blob/main/README.md This command publishes the Enumshare configuration file to your Laravel project. This allows you to customize settings such as the enums to export, the output path, the output mode, and auto-discovery preferences. ```bash php artisan vendor:publish --tag="enumshare-config" ``` -------------------------------- ### Enumshare Artisan Command Options Source: https://github.com/olivermbs/enumshare/blob/main/README.md This list details various options available for the 'enums:export' Artisan command. These options allow for controlling the export process, such as forcing overwrites, listing exportable enums, generating index files, specifying output paths, and overriding locales. ```bash php artisan enums:export # Export enums php artisan enums:export --force # Rewrite all, even if unchanged php artisan enums:export --list # List enums that would be exported php artisan enums:export --index # Generate barrel index file php artisan enums:export --types # Export TypeScript helper types php artisan enums:export --path=... # Override export path php artisan enums:export --locale=... # Override locale for labels ``` -------------------------------- ### Test EnumRuntime with Test Data (JavaScript) Source: https://github.com/olivermbs/enumshare/blob/main/tests/browser-test.html This snippet defines test data for a FlightBriefingStatus enum and a simplified `createTestEnum` function to simulate the EnumRuntime. It then tests the enum's properties and methods like `from` and `fromValue`, logging results to the console and updating the DOM. ```javascript // Test data matching FlightBriefingStatus const testEnumData = { "name": "TestEnum", "fqcn": "App\\Enums\\TestEnum", "backingType": "int", "entries": [ { "key": "DRAFT", "value": 0, "label": "Draft", "meta": { "color": "orange" } }, { "key": "SAVED", "value": 1, "label": "Saved", "meta": { "color": "blue" } } ], "options": [ { "value": 0, "label": "Draft" }, { "value": 1, "label": "Saved" } ] }; // Import and test the actual EnumRuntime if available try { // This would normally import from your actual EnumRuntime.ts // For now, we'll use a simplified version function createTestEnum(enumData) { const entriesMap = {}; for (const entry of enumData.entries) { entriesMap[entry.key] = entry; } const baseObject = { name: enumData.name, entries: enumData.entries, options: enumData.options, keys: () => enumData.entries.map(entry => entry.key), values: () => enumData.entries.map(entry => entry.value ?? entry.key), labels: () => enumData.entries.map(entry => entry.label), }; const findEntryByValue = (value) => { const entry = enumData.entries.find(entry => (entry.value !== null ? entry.value : entry.key) === value ); return entry || null; }; baseObject.from = findEntryByValue; baseObject.fromValue = findEntryByValue; return new Proxy(baseObject, { get(target, prop) { if (typeof prop === 'string' && entriesMap[prop]) { return entriesMap[prop]; } return target[prop]; } }); } const testEnum = createTestEnum(testEnumData); console.log('=== Browser Test Results ==='); console.log('Enum:', testEnum); console.log('Has from method:', typeof testEnum.from === 'function'); console.log('Has fromValue method:', typeof testEnum.fromValue === 'function'); console.log('from(1):', testEnum.from(1)); console.log('fromValue(1):', testEnum.fromValue(1)); console.log('Object.getOwnPropertyNames:', Object.getOwnPropertyNames(testEnum)); console.log('hasOwnProperty("fromValue"):', testEnum.hasOwnProperty('fromValue')); // Test the specific use case from Vue const testStatus = 1; console.log('Vue use case test - fromValue(' + testStatus + ')?.label:', testEnum.fromValue(testStatus)?.label); document.getElementById('results').innerHTML = `

Test Results

`; } catch (error) { console.error('Test failed:', error); document.getElementById('results').innerHTML = `

Error: ${error.message}

`; } ``` -------------------------------- ### TypeScript Usage - Minimal Mode Enums Source: https://context7.com/olivermbs/enumshare/llms.txt Illustrates using minimal mode in EnumShare, where generated TypeScript output is compact and includes only values and types. Shows accessing enum values directly and type annotations for functions. ```typescript import { UserStatus } from '@/Enums/UserStatus'; // Minimal mode exports a simple const object console.log(UserStatus.Active); // 'active' console.log(UserStatus.Pending); // 'pending' console.log(UserStatus.Inactive); // 'inactive' // Type annotation function setStatus(status: UserStatus): void { console.log(`Status: ${status}`); } setStatus(UserStatus.Active); // OK - 'active' setStatus('active'); // OK - same as UserStatus.Active setStatus('invalid'); // TypeScript error ``` -------------------------------- ### TypeScript Usage - Full Mode Enums Source: https://context7.com/olivermbs/enumshare/llms.txt Demonstrates accessing generated TypeScript enums with full type safety and utility methods. Includes accessing enum entries with metadata, looking up entries by value or key, type guards, iteration, and retrieving arrays of keys, values, labels, and select options. ```typescript import { UserStatus } from '@/Enums/UserStatus'; // Access enum entries with all metadata const activeStatus = UserStatus.Active; console.log(activeStatus.value); // 'active' console.log(activeStatus.label); // 'Active User' console.log(activeStatus.meta); // { color: 'green', icon: 'check-circle', sortOrder: 1 } console.log(activeStatus.displayName); // 'Active and Verified' // Lookup entries by value const status = UserStatus.from('active'); if (status) { console.log(status.key); // 'Active' console.log(status.label); // 'Active User' } // Lookup entries by key const pendingStatus = UserStatus.fromKey('Pending'); console.log(pendingStatus?.value); // 'pending' // Type guards and validation const userInput: unknown = 'active'; if (UserStatus.isValid(userInput)) { // TypeScript knows userInput is UserStatusValue here const entry = UserStatus.from(userInput); } if (UserStatus.hasKey('Active')) { // TypeScript knows 'Active' is a valid UserStatusKey console.log('Valid key'); } // Iterate over all entries UserStatus.entries.forEach(entry => { console.log(`${entry.key}: ${entry.value} - ${entry.label}`); }); // Get arrays of keys, values, or labels console.log(UserStatus.keys); // ['Active', 'Pending', 'Inactive'] console.log(UserStatus.values); // ['active', 'pending', 'inactive'] console.log(UserStatus.labels()); // ['Active User', 'Pending Verification', 'Inactive'] // Get options for select dropdowns const selectOptions = UserStatus.options; // [ // { value: 'active', label: 'Active User' }, // { value: 'pending', label: 'Pending Verification' }, // { value: 'inactive', label: 'Deactivated Account' } // ] // Get total count console.log(UserStatus.count); // 3 // Type annotations function updateStatus(status: UserStatusValue): void { console.log(`Updating to: ${status}`); } updateStatus('active'); // OK updateStatus('invalid'); // TypeScript error: not assignable to UserStatusValue ``` -------------------------------- ### Configure Enumshare Output Mode Source: https://github.com/olivermbs/enumshare/blob/main/README.md This PHP configuration snippet allows you to set the output mode for generated TypeScript enums. 'full' mode includes all details like labels, metadata, and utility methods, while 'minimal' provides a more concise output focusing on values and types. ```php // config/enumshare.php return [ // ... other configurations 'mode' => 'full', // or 'minimal' // ... ]; ``` -------------------------------- ### Export Enums using Artisan Command Source: https://github.com/olivermbs/enumshare/blob/main/README.md This Artisan command initiates the export process for your PHP Enums to TypeScript. By default, it scans configured paths and generates corresponding TypeScript files, ensuring your frontend has up-to-date enum definitions. ```bash php artisan enums:export ``` -------------------------------- ### React Component Integration with TypeScript Enums Source: https://context7.com/olivermbs/enumshare/llms.txt Demonstrates integrating generated TypeScript enums into React components for type-safe handling of application states or data. It shows how to use enums for rendering status badges and managing select inputs, leveraging utility methods provided by the generated enum. ```typescript import React from 'react'; import { UserStatus } from '@/Enums/UserStatus'; interface StatusBadgeProps { status: UserStatusValue; } const StatusBadge: React.FC = ({ status }) => { const entry = UserStatus.from(status); if (!entry) { return Unknown Status; } return ( {entry.label} ); }; interface StatusSelectProps { value: UserStatusValue; onChange: (value: UserStatusValue) => void; } const StatusSelect: React.FC = ({ value, onChange }) => { return ( ); }; // Usage export default function UserProfile() { const [status, setStatus] = React.useState('active'); return (

Total statuses: {UserStatus.count}

); } ``` -------------------------------- ### Programmatically Export PHP Enums to JavaScript Source: https://context7.com/olivermbs/enumshare/llms.txt Export PHP enums to JavaScript files using the EnumExporter service. This service allows configuring the export path, locale, and inclusion of index and type definitions. It returns statistics about the generated and skipped enums. ```php exporter->export([ 'path' => resource_path('js/Enums'), 'locale' => 'en', 'index' => true, 'types' => true, 'force' => $force, 'list' => false, ]); return [ 'generated' => $result['generated'] ?? 0, 'skipped' => $result['skipped'] ?? 0, 'path' => $result['path'] ?? 'unknown', ]; } public function listAvailableEnums(): array { $result = $this->exporter->export([ 'list' => true, ]); return $result['enums'] ?? []; } } // Usage in controller or command $syncService = app(EnumSyncService::class); $stats = $syncService->syncEnums(force: true); // ['generated' => 5, 'skipped' => 0, 'path' => '/path/to/enums'] $enumList = $syncService->listAvailableEnums(); // ['UserStatus', 'OrderStatus', 'PaymentMethod'] ``` -------------------------------- ### Minimal TypeScript Enum Output Source: https://github.com/olivermbs/enumshare/blob/main/README.md This TypeScript code represents the 'minimal' output mode from Enumshare. It provides a basic export of enum values as constants and a corresponding type definition, suitable for scenarios where only the values are needed without extra metadata or methods. ```typescript /* eslint-disable */ // Auto-generated from App\Enums\Status export const Status = { Active: 'active', Inactive: 'inactive', } as const; export type Status = typeof Status[keyof typeof Status]; ``` -------------------------------- ### Manage and Validate Enum Classes with EnumRegistry Source: https://context7.com/olivermbs/enumshare/llms.txt Utilize the EnumRegistry to manage and validate PHP enum classes. It provides methods to validate a list of enum classes, checking for existence and other potential issues, and to generate a manifest of enum data. It also includes an EnumExtractor for retrieving detailed data from a single enum. ```php validateEnums($enums); // [ // 'App\Enums\NonExistent' => "Enum class 'App\Enums\NonExistent' does not exist." // ] // Generate manifest with extracted enum data try { $manifest = $registry->manifest('en'); // [ // 'UserStatus' => [ // 'name' => 'UserStatus', // 'fqcn' => 'App\Enums\UserStatus', // 'backingType' => 'string', // 'entries' => [...] // ], // 'OrderStatus' => [...] // ] } catch (Olivermbs\Enumshare\Exceptions\InvalidEnumException $e) { // Handle duplicate short names or other validation errors echo $e->getMessage(); } // Extract data from a single enum $extractor = new EnumExtractor(); $enumData = $extractor->extract(App\Enums\UserStatus::class, 'en'); // [ // 'name' => 'UserStatus', // 'fqcn' => 'App\Enums\UserStatus', // 'backingType' => 'string', // 'entries' => [ // [ // 'key' => 'Active', // 'value' => 'active', // 'label' => 'Active User', // 'meta' => ['color' => 'green', 'icon' => 'check-circle'] // ] // ] // ] ``` -------------------------------- ### Configure Vite for Auto-Regeneration with Wayfinder Source: https://github.com/olivermbs/enumshare/blob/main/README.md This JavaScript configuration integrates Laravel Wayfinder with Vite to automatically regenerate TypeScript enums during development. When changes are detected in specified PHP, translation, or configuration files, the 'enums:export' command is triggered, keeping frontend definitions synchronized. ```javascript // vite.config.js import { wayfinder } from '@laravel/vite-plugin-wayfinder'; export default defineConfig({ plugins: [ wayfinder({ command: 'php artisan enums:export --force', patterns: ['app/Enums/**/*.php', 'lang/**/*.php', 'config/enumshare.php'], }), ], }); ``` -------------------------------- ### Use Exported Enum in TypeScript Source: https://github.com/olivermbs/enumshare/blob/main/README.md This TypeScript code demonstrates how to import and utilize an exported Enumshare enum. It showcases accessing the enum's value, label, and metadata, along with using utility methods like 'from', 'isValid', and accessing 'options' for frontend integration. ```typescript import { Status } from '@/Enums/Status'; Status.Active.value // 'active' Status.Active.label // 'Active' Status.Active.meta // { color: 'green' } Status.from('active') // Status.Active entry Status.isValid('active') // true Status.options // [{ value: 'active', label: 'Active' }, ...] ``` -------------------------------- ### Define a PHP Enum with Attributes for Export Source: https://github.com/olivermbs/enumshare/blob/main/README.md This PHP code defines a 'Status' enum with associated labels and metadata using custom attributes. These attributes are utilized by the Enumshare package to enrich the exported TypeScript definitions, enabling richer frontend representations of enum states. ```php 'green'])] case Active = 'active'; #[Label('Inactive')] #[Meta(['color' => 'red'])] case Inactive = 'inactive'; } ``` -------------------------------- ### PHP Enum Definition with Attributes Source: https://context7.com/olivermbs/enumshare/llms.txt PHP enums can be defined using attributes like `#[Label]`, `#[Meta]`, and `#[TranslatedLabel]` to specify display names, metadata, and translated labels. The `#[ExportMethod]` attribute allows exporting custom methods from the enum. ```php 'green', 'icon' => 'check-circle', 'sortOrder' => 1])] case Active = 'active'; #[Label('Pending Verification')] #[Meta(['color' => 'yellow', 'icon' => 'clock', 'sortOrder' => 2])] case Pending = 'pending'; #[TranslatedLabel('status.inactive')] #[Meta(['color' => 'red', 'icon' => 'x-circle', 'sortOrder' => 3])] case Inactive = 'inactive'; #[ExportMethod('displayName')] public function getDisplayName(): string { return match($this) { self::Active => 'Active and Verified', self::Pending => 'Awaiting Verification', self::Inactive => 'Deactivated Account', }; } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.