├── .phpunit.result.cache ├── .styleci.yml ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── composer.json ├── config └── config.php ├── phpunit.xml └── src ├── Console └── Commands │ └── GenerateCommand.php ├── LaravelEnumJsServiceProvider.php └── Resources ├── ConstantFormatter.php ├── ObjectFormatter.php ├── OutputFormatFactory.php └── OutputFormatter.php /.phpunit.result.cache: -------------------------------------------------------------------------------- 1 | {"version":1,"defects":{"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGenerate":4,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"int\"":4,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"string\"":4,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"native\"":4,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"native backed int\"":4,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"native backed string\"":4,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"array\"":4},"times":{"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGenerate":0.196,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"int\"":0.012,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"string\"":0.01,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"native\"":0.009,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"native backed int\"":0.009,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"native backed string\"":0.009,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedContent with data set \"array\"":0.009,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedObjectFormat with data set \"int\"":0.01,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedObjectFormat with data set \"string\"":0.009,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedObjectFormat with data set \"native\"":0.011,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedObjectFormat with data set \"native backed int\"":0.011,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedObjectFormat with data set \"native backed string\"":0.01,"Modstore\\LaravelEnumJs\\Tests\\Console\\Commands\\GenerateCommandTest::testGeneratedObjectFormat with data set \"array\"":0.011}} -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - single_class_element_per_statement 5 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-enum-js` will be documented in this file 4 | 5 | ## 1.0.0 - 201X-XX-XX 6 | 7 | - initial release 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Mark Whitney 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel Enum Js 2 | 3 | Package to generate javascript versions of your PHP enum files to be used in your js builds etc. 4 | Works with Php8.1+ enums, constants in your PHP files, or you can use a package such as https://github.com/BenSampo/laravel-enum 5 | 6 | ## Installation 7 | 8 | You can install the package via composer: 9 | 10 | ```bash 11 | composer require modstore/laravel-enum-js 12 | ``` 13 | 14 | Publish the config: 15 | 16 | ``` 17 | php artisan vendor:publish --provider="Modstore\LaravelEnumJs\LaravelEnumJsServiceProvider" 18 | ``` 19 | 20 | ## Usage 21 | 22 | Create a storage location, the path the generated files will be saved to. 23 | ``` php 24 | // config/filesystems.php 25 | ... 26 | 'disks' => [ 27 | 'enum-js' => [ 28 | 'driver' => 'local', 29 | 'root' => resource_path() . '/js/enums', 30 | ], 31 | ], 32 | ... 33 | ``` 34 | Check the other configuration options in the config file. 35 | 36 | You can generate the js files by running the following Artisan command: 37 | ``` bash 38 | php artisan enum-js:generate 39 | ``` 40 | 41 | NOTE: When developing, if you create a new file, you will likely need to dump the 42 | autoload files before this command will pick it up, e.g. 43 | ``` bash 44 | composer dump-autoload 45 | php artisan enum-js:generate 46 | ``` 47 | 48 | You can then use the generated files in your javascript like so: 49 | ``` javascript 50 | import * as Status from '../enums/Status' 51 | 52 | if (this.status === Status.Active) { 53 | // Do something. 54 | } 55 | ``` 56 | 57 | ### Testing 58 | 59 | ``` bash 60 | composer test 61 | ``` 62 | 63 | ### Changelog 64 | 65 | Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently. 66 | 67 | ## Contributing 68 | 69 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 70 | 71 | ## Credits 72 | 73 | - [Mark Whitney](https://github.com/modstore) 74 | - [All Contributors](../../contributors) 75 | 76 | ## License 77 | 78 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 79 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "modstore/laravel-enum-js", 3 | "description": "Package to generate javascript versions of your PHP enum files to be used in your js builds etc.", 4 | "keywords": [ 5 | "modstore", 6 | "laravel-enum-js" 7 | ], 8 | "homepage": "https://github.com/modstore/laravel-enum-js", 9 | "license": "MIT", 10 | "type": "library", 11 | "authors": [ 12 | { 13 | "name": "Mark Whitney", 14 | "email": "mark@priceguard.com.au", 15 | "role": "Developer" 16 | } 17 | ], 18 | "require": { 19 | "php": "^8.0|^8.1", 20 | "illuminate/support": ">=6.0" 21 | }, 22 | "require-dev": { 23 | "orchestra/testbench": "^4.0|^6.24|^7.6", 24 | "phpunit/phpunit": "^8.0" 25 | }, 26 | "autoload": { 27 | "psr-4": { 28 | "Modstore\\LaravelEnumJs\\": "src" 29 | } 30 | }, 31 | "autoload-dev": { 32 | "psr-4": { 33 | "Modstore\\LaravelEnumJs\\Tests\\": "tests" 34 | } 35 | }, 36 | "scripts": { 37 | "test": "vendor/bin/phpunit", 38 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage" 39 | 40 | }, 41 | "config": { 42 | "sort-packages": true 43 | }, 44 | "extra": { 45 | "laravel": { 46 | "providers": [ 47 | "Modstore\\LaravelEnumJs\\LaravelEnumJsServiceProvider" 48 | ] 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /config/config.php: -------------------------------------------------------------------------------- 1 | [ 6 | 'App\Enums\*', 7 | ], 8 | 9 | // Name of the disk that's the location you'd like the js files to be output to. 10 | // Be sure to add this disk in your config/filesystems.php 11 | 'output_disk' => 'enum-js', 12 | 13 | // A list of transforms for the js output file path. 14 | 'output_transform' => [ 15 | 'App\\Enums\\' => '', 16 | ], 17 | 18 | // Set a specific extension for the output files (without a dot character). 19 | 'output_file_extension' => 'js', 20 | 21 | // here you may configure the desired output style for the generated js files. 22 | // Available options: 'constant', 'object' 23 | 'output_style' => 'constant', 24 | ]; 25 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 | 14 | tests 15 | 16 | 17 | 18 | 19 | src/ 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /src/Console/Commands/GenerateCommand.php: -------------------------------------------------------------------------------- 1 | allFiles(); 34 | 35 | // Just to ensure this isn't accidentally the wrong directly with non-js files. 36 | $nonJsFiles = collect($files)->filter(function ($filename) { 37 | return preg_match('/\.' . config('laravel-enum-js.output_file_extension', 'js') . '$/', $filename) !== 1; 38 | }); 39 | 40 | if ($nonJsFiles->count() > 0) { 41 | throw new \Exception('Js enums directory contains non-js files, please check your config.'); 42 | } 43 | 44 | Storage::disk(config('laravel-enum-js.output_disk'))->delete($files); 45 | 46 | $pattern = '/' . collect(config('laravel-enum-js.namespaces'))->map(function ($item) { 47 | return str_replace('\\*', '.+', preg_quote($item)); 48 | })->implode('|') . '/'; 49 | 50 | $classLoader = require('vendor/autoload.php'); 51 | $classes = array_unique(array_merge(get_declared_classes(), array_keys($classLoader->getClassMap()))); 52 | 53 | // Create a js file for any class that matches the specified pattern. 54 | foreach ($classes as $class) { 55 | if (preg_match($pattern, $class) !== 1) { 56 | continue; 57 | } 58 | 59 | $this->writeFile($class); 60 | } 61 | 62 | return 0; 63 | } 64 | 65 | /** 66 | * Create a js file from the constants in the provided class. 67 | * 68 | * @param string $class 69 | * @throws \ReflectionException 70 | */ 71 | protected function writeFile(string $class): void 72 | { 73 | $outputPath = $class; 74 | foreach (config('laravel-enum-js.output_transform') as $pattern => $replacement) { 75 | $outputPath = preg_replace('/' . preg_quote($pattern) . '/', $replacement, $outputPath); 76 | } 77 | $outputPath .= '.' . config('laravel-enum-js.output_file_extension', 'js'); 78 | 79 | $reflection = new \ReflectionClass($class); 80 | 81 | $formatter = OutputFormatFactory::create( config('laravel-enum-js.output_style', 'constant'), $reflection); 82 | 83 | Storage::disk(config('laravel-enum-js.output_disk'))->put($outputPath, $formatter->getFileContents()); 84 | 85 | $this->info(sprintf('File written to: %s', $outputPath)); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/LaravelEnumJsServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 16 | $this->publishes([ 17 | __DIR__ . '/../config/config.php' => config_path('laravel-enum-js.php'), 18 | ], 'config'); 19 | 20 | $this->commands([ 21 | GenerateCommand::class, 22 | ]); 23 | } 24 | } 25 | 26 | /** 27 | * Register the application services. 28 | */ 29 | public function register() 30 | { 31 | // Automatically apply the package configuration 32 | $this->mergeConfigFrom(__DIR__ . '/../config/config.php', 'laravel-enum-js'); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/Resources/ConstantFormatter.php: -------------------------------------------------------------------------------- 1 | getEnumValue($case); 17 | 18 | return sprintf("export const %s = %s\n", $case->getName(), json_encode($value)); 19 | } 20 | } -------------------------------------------------------------------------------- /src/Resources/ObjectFormatter.php: -------------------------------------------------------------------------------- 1 | getEnumValue($case); 17 | 18 | return sprintf(" %s: %s,\n", $case->getName(), json_encode($value)); 19 | } 20 | 21 | protected function getStart(): string 22 | { 23 | $exploded=explode('\\', $this->class->getName()); 24 | $objectName = end($exploded); 25 | 26 | return sprintf("export const %s = Object.freeze({\n", $objectName); 27 | } 28 | 29 | protected function getEnd(): string 30 | { 31 | return '})'; 32 | } 33 | } -------------------------------------------------------------------------------- /src/Resources/OutputFormatFactory.php: -------------------------------------------------------------------------------- 1 | new ObjectFormatter($class), 19 | 'constant' => new ConstantFormatter($class), 20 | default => throw new \InvalidArgumentException("Invalid output format type: {$type}"), 21 | }; 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /src/Resources/OutputFormatter.php: -------------------------------------------------------------------------------- 1 | getStart(); 44 | 45 | foreach ($this->class->getReflectionConstants() as $case) { 46 | $output .= $this->printCase($case); 47 | } 48 | 49 | $output .= $this->getEnd(); 50 | 51 | return $output; 52 | } 53 | 54 | protected function getEnumValue($enumCase): mixed 55 | { 56 | $value = $enumCase->getValue(); 57 | if (method_exists($enumCase, 'isEnumCase') && $enumCase->isEnumCase()) { 58 | $value = property_exists($value, 'value') ? $value->value : $value->name; 59 | } 60 | 61 | return $value; 62 | } 63 | } --------------------------------------------------------------------------------