diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index c68765b..c149573 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1 @@ -github: :vendor_name +github: Riley Aven diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 6474295..463de0f 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: false contact_links: - name: Ask a question - url: https://github.com/:vendor_slug/:package_name/discussions/new?category=q-a + url: https://github.com/riley19280/laravel-rules-to-schema/discussions/new?category=q-a about: Ask the community for help - name: Request a feature - url: https://github.com/:vendor_slug/:package_name/discussions/new?category=ideas + url: https://github.com/riley19280/laravel-rules-to-schema/discussions/new?category=ideas about: Share ideas for new features - name: Report a security issue - url: https://github.com/:vendor_slug/:package_name/security/policy + url: https://github.com/riley19280/laravel-rules-to-schema/security/policy about: Learn how to notify us for sensitive bugs diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b3242..f984b6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,3 @@ # Changelog -All notable changes to `:package_name` will be documented in this file. +All notable changes to `laravel-rules-to-schema` will be documented in this file. diff --git a/LICENSE.md b/LICENSE.md index 58c9ad4..6f9e310 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) :vendor_name +Copyright (c) Riley Aven Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 375da96..b2946a2 100644 --- a/README.md +++ b/README.md @@ -1,24 +1,15 @@ -# :package_description - -[![Latest Version on Packagist](https://img.shields.io/packagist/v/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) -[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/:vendor_slug/:package_slug/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3Arun-tests+branch%3Amain) -[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/:vendor_slug/:package_slug/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) -[![Total Downloads](https://img.shields.io/packagist/dt/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) - ---- -This repo can be used to scaffold a Laravel package. Follow these steps to get started: - -1. Press the "Use this template" button at the top of this repo to create a new repo with the contents of this skeleton. -2. Run "php ./configure.php" to run a script that will replace all placeholders throughout all the files. -3. Have fun creating your package. -4. If you need help creating a package, consider picking up our Laravel Package Training video course. ---- - +# This is my package laravel-rules-to-schema + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/riley19280/laravel-rules-to-schema.svg?style=flat-square)](https://packagist.org/packages/riley19280/laravel-rules-to-schema) +[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/riley19280/laravel-rules-to-schema/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/riley19280/laravel-rules-to-schema/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/riley19280/laravel-rules-to-schema/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/riley19280/laravel-rules-to-schema/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/riley19280/laravel-rules-to-schema.svg?style=flat-square)](https://packagist.org/packages/riley19280/laravel-rules-to-schema) + This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. ## Support us -[](https://spatie.be/github-ad-click/:package_name) +[](https://spatie.be/github-ad-click/laravel-rules-to-schema) We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us). @@ -29,20 +20,20 @@ We highly appreciate you sending us a postcard from your hometown, mentioning wh You can install the package via composer: ```bash -composer require :vendor_slug/:package_slug +composer require riley19280/laravel-rules-to-schema ``` You can publish and run the migrations with: ```bash -php artisan vendor:publish --tag=":package_slug-migrations" +php artisan vendor:publish --tag="laravel-rules-to-schema-migrations" php artisan migrate ``` You can publish the config file with: ```bash -php artisan vendor:publish --tag=":package_slug-config" +php artisan vendor:publish --tag="laravel-rules-to-schema-config" ``` This is the contents of the published config file: @@ -55,14 +46,14 @@ return [ Optionally, you can publish the views using ```bash -php artisan vendor:publish --tag=":package_slug-views" +php artisan vendor:publish --tag="laravel-rules-to-schema-views" ``` ## Usage ```php -$variable = new VendorName\Skeleton(); -echo $variable->echoPhrase('Hello, VendorName!'); +$laravelRulesToSchema = new LaravelRulesToSchema(); +echo $laravelRulesToSchema->echoPhrase('Hello, LaravelRulesToSchema!'); ``` ## Testing @@ -85,7 +76,7 @@ Please review [our security policy](../../security/policy) on how to report secu ## Credits -- [:author_name](https://github.com/:author_username) +- [Riley Aven](https://github.com/Riley19280) - [All Contributors](../../contributors) ## License diff --git a/composer.json b/composer.json index 65e9908..d5be9ed 100644 --- a/composer.json +++ b/composer.json @@ -1,24 +1,26 @@ { - "name": ":vendor_slug/:package_slug", - "description": ":package_description", + "name": "riley19280/laravel-rules-to-schema", + "description": "Parse Laravel validation rules into a Json Schema Object", "keywords": [ - ":vendor_name", + "Riley Aven", "laravel", - ":package_slug" + "laravel-rules-to-schema" ], - "homepage": "https://github.com/:vendor_slug/:package_slug", + "homepage": "https://github.com/riley19280/laravel-rules-to-schema", "license": "MIT", "authors": [ { - "name": ":author_name", - "email": "author@domain.com", + "name": "Riley Aven", + "email": "rileyaven@example.com", "role": "Developer" } ], "require": { "php": "^8.2", - "spatie/laravel-package-tools": "^1.16", - "illuminate/contracts": "^10.0||^11.0" + "illuminate/contracts": "^10.0||^11.0", + "riley19280/fluent-json-schema": "^1.2.1", + "spatie/invade": "^2.1", + "spatie/laravel-package-tools": "^1.16" }, "require-dev": { "laravel/pint": "^1.14", @@ -30,24 +32,23 @@ "pestphp/pest-plugin-laravel": "^2.3", "phpstan/extension-installer": "^1.3", "phpstan/phpstan-deprecation-rules": "^1.1", - "phpstan/phpstan-phpunit": "^1.3", - "spatie/laravel-ray": "^1.35" + "phpstan/phpstan-phpunit": "^1.3" }, "autoload": { "psr-4": { - "VendorName\\Skeleton\\": "src/", - "VendorName\\Skeleton\\Database\\Factories\\": "database/factories/" + "LaravelRulesToSchema\\": "src/", + "LaravelRulesToSchema\\Database\\Factories\\": "database/factories/" } }, "autoload-dev": { "psr-4": { - "VendorName\\Skeleton\\Tests\\": "tests/", + "LaravelRulesToSchema\\Tests\\": "tests/", "Workbench\\App\\": "workbench/app/" } }, "scripts": { "post-autoload-dump": "@composer run prepare", - "clear": "@php vendor/bin/testbench package:purge-skeleton --ansi", + "clear": "@php vendor/bin/testbench package:purge-laravel-rules-to-schema --ansi", "prepare": "@php vendor/bin/testbench package:discover --ansi", "build": [ "@composer run prepare", @@ -73,10 +74,10 @@ "extra": { "laravel": { "providers": [ - "VendorName\\Skeleton\\SkeletonServiceProvider" + "LaravelRulesToSchema\\LaravelRulesToSchemaServiceProvider" ], "aliases": { - "Skeleton": "VendorName\\Skeleton\\Facades\\Skeleton" + "LaravelRulesToSchema": "LaravelRulesToSchema\\Facades\\LaravelRulesToSchema" } } }, diff --git a/config/rules-to-schema.php b/config/rules-to-schema.php new file mode 100644 index 0000000..2491f86 --- /dev/null +++ b/config/rules-to-schema.php @@ -0,0 +1,6 @@ + $version) { - if (in_array($name, $names, true)) { - unset($data['require-dev'][$name]); - } - } - - file_put_contents(__DIR__.'/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function remove_composer_script($scriptName) -{ - $data = json_decode(file_get_contents(__DIR__.'/composer.json'), true); - - foreach ($data['scripts'] as $name => $script) { - if ($scriptName === $name) { - unset($data['scripts'][$name]); - break; - } - } - - file_put_contents(__DIR__.'/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function remove_readme_paragraphs(string $file): void -{ - $contents = file_get_contents($file); - - file_put_contents( - $file, - preg_replace('/.*/s', '', $contents) ?: $contents - ); -} - -function safeUnlink(string $filename) -{ - if (file_exists($filename) && is_file($filename)) { - unlink($filename); - } -} - -function determineSeparator(string $path): string -{ - return str_replace('/', DIRECTORY_SEPARATOR, $path); -} - -function replaceForWindows(): array -{ - return preg_split('/\\r\\n|\\r|\\n/', run('dir /S /B * | findstr /v /i .git\ | findstr /v /i vendor | findstr /v /i '.basename(__FILE__).' | findstr /r /i /M /F:/ ":author :vendor :package VendorName skeleton migration_table_name vendor_name vendor_slug author@domain.com"')); -} - -function replaceForAllOtherOSes(): array -{ - return explode(PHP_EOL, run('grep -E -r -l -i ":author|:vendor|:package|VendorName|skeleton|migration_table_name|vendor_name|vendor_slug|author@domain.com" --exclude-dir=vendor ./* ./.github/* | grep -v '.basename(__FILE__))); -} - -function getGitHubApiEndpoint(string $endpoint): ?stdClass -{ - try { - $curl = curl_init("https://api.github.com/{$endpoint}"); - curl_setopt_array($curl, [ - CURLOPT_RETURNTRANSFER => true, - CURLOPT_FOLLOWLOCATION => true, - CURLOPT_HTTPGET => true, - CURLOPT_HTTPHEADER => [ - 'User-Agent: spatie-configure-script/1.0', - ], - ]); - - $response = curl_exec($curl); - $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); - - curl_close($curl); - - if ($statusCode === 200) { - return json_decode($response); - } - } catch (Exception $e) { - // ignore - } - - return null; -} - -function searchCommitsForGitHubUsername(): string -{ - $authorName = strtolower(trim(shell_exec('git config user.name'))); - - $committersRaw = shell_exec("git log --author='@users.noreply.github.com' --pretty='%an:%ae' --reverse"); - $committersLines = explode("\n", $committersRaw ?? ''); - $committers = array_filter(array_map(function ($line) use ($authorName) { - $line = trim($line); - [$name, $email] = explode(':', $line) + [null, null]; - - return [ - 'name' => $name, - 'email' => $email, - 'isMatch' => strtolower($name) === $authorName && ! str_contains($name, '[bot]'), - ]; - }, $committersLines), fn ($item) => $item['isMatch']); - - if (empty($committers)) { - return ''; - } - - $firstCommitter = reset($committers); - - return explode('@', $firstCommitter['email'])[0] ?? ''; -} - -function guessGitHubUsernameUsingCli() -{ - try { - if (preg_match('/ogged in to github\.com as ([a-zA-Z-_]+).+/', shell_exec('gh auth status -h github.com 2>&1'), $matches)) { - return $matches[1]; - } - } catch (Exception $e) { - // ignore - } - - return ''; -} - -function guessGitHubUsername(): string -{ - $username = searchCommitsForGitHubUsername(); - if (! empty($username)) { - return $username; - } - - $username = guessGitHubUsernameUsingCli(); - if (! empty($username)) { - return $username; - } - - // fall back to using the username from the git remote - $remoteUrl = shell_exec('git config remote.origin.url'); - $remoteUrlParts = explode('/', str_replace(':', '/', trim($remoteUrl))); - - return $remoteUrlParts[1] ?? ''; -} - -function guessGitHubVendorInfo($authorName, $username): array -{ - $remoteUrl = shell_exec('git config remote.origin.url'); - $remoteUrlParts = explode('/', str_replace(':', '/', trim($remoteUrl))); - - $response = getGitHubApiEndpoint("orgs/{$remoteUrlParts[1]}"); - - if ($response === null) { - return [$authorName, $username]; - } - - return [$response->name ?? $authorName, $response->login ?? $username]; -} - -$gitName = run('git config user.name'); -$authorName = ask('Author name', $gitName); - -$gitEmail = run('git config user.email'); -$authorEmail = ask('Author email', $gitEmail); -$authorUsername = ask('Author username', guessGitHubUsername()); - -$guessGitHubVendorInfo = guessGitHubVendorInfo($authorName, $authorUsername); - -$vendorName = ask('Vendor name', $guessGitHubVendorInfo[0]); -$vendorUsername = ask('Vendor username', $guessGitHubVendorInfo[1] ?? slugify($vendorName)); -$vendorSlug = slugify($vendorUsername); - -$vendorNamespace = str_replace('-', '', ucwords($vendorName)); -$vendorNamespace = ask('Vendor namespace', $vendorNamespace); - -$currentDirectory = getcwd(); -$folderName = basename($currentDirectory); - -$packageName = ask('Package name', $folderName); -$packageSlug = slugify($packageName); -$packageSlugWithoutPrefix = remove_prefix('laravel-', $packageSlug); - -$className = title_case($packageName); -$className = ask('Class name', $className); -$variableName = lcfirst($className); -$description = ask('Package description', "This is my package {$packageSlug}"); - -$usePhpStan = confirm('Enable PhpStan?', true); -$useLaravelPint = confirm('Enable Laravel Pint?', true); -$useDependabot = confirm('Enable Dependabot?', true); -$useLaravelRay = confirm('Use Ray for debugging?', true); -$useUpdateChangelogWorkflow = confirm('Use automatic changelog updater workflow?', true); - -writeln('------'); -writeln("Author : {$authorName} ({$authorUsername}, {$authorEmail})"); -writeln("Vendor : {$vendorName} ({$vendorSlug})"); -writeln("Package : {$packageSlug} <{$description}>"); -writeln("Namespace : {$vendorNamespace}\\{$className}"); -writeln("Class name : {$className}"); -writeln('---'); -writeln('Packages & Utilities'); -writeln('Use Laravel/Pint : '.($useLaravelPint ? 'yes' : 'no')); -writeln('Use Larastan/PhpStan : '.($usePhpStan ? 'yes' : 'no')); -writeln('Use Dependabot : '.($useDependabot ? 'yes' : 'no')); -writeln('Use Ray App : '.($useLaravelRay ? 'yes' : 'no')); -writeln('Use Auto-Changelog : '.($useUpdateChangelogWorkflow ? 'yes' : 'no')); -writeln('------'); - -writeln('This script will replace the above values in all relevant files in the project directory.'); - -if (! confirm('Modify files?', true)) { - exit(1); -} - -$files = (str_starts_with(strtoupper(PHP_OS), 'WIN') ? replaceForWindows() : replaceForAllOtherOSes()); - -foreach ($files as $file) { - replace_in_file($file, [ - ':author_name' => $authorName, - ':author_username' => $authorUsername, - 'author@domain.com' => $authorEmail, - ':vendor_name' => $vendorName, - ':vendor_slug' => $vendorSlug, - 'VendorName' => $vendorNamespace, - ':package_name' => $packageName, - ':package_slug' => $packageSlug, - ':package_slug_without_prefix' => $packageSlugWithoutPrefix, - 'Skeleton' => $className, - 'skeleton' => $packageSlug, - 'migration_table_name' => title_snake($packageSlug), - 'variable' => $variableName, - ':package_description' => $description, - ]); - - match (true) { - str_contains($file, determineSeparator('src/Skeleton.php')) => rename($file, determineSeparator('./src/'.$className.'.php')), - str_contains($file, determineSeparator('src/SkeletonServiceProvider.php')) => rename($file, determineSeparator('./src/'.$className.'ServiceProvider.php')), - str_contains($file, determineSeparator('src/Facades/Skeleton.php')) => rename($file, determineSeparator('./src/Facades/'.$className.'.php')), - str_contains($file, determineSeparator('src/Commands/SkeletonCommand.php')) => rename($file, determineSeparator('./src/Commands/'.$className.'Command.php')), - str_contains($file, determineSeparator('database/migrations/create_skeleton_table.php.stub')) => rename($file, determineSeparator('./database/migrations/create_'.title_snake($packageSlugWithoutPrefix).'_table.php.stub')), - str_contains($file, determineSeparator('config/skeleton.php')) => rename($file, determineSeparator('./config/'.$packageSlugWithoutPrefix.'.php')), - str_contains($file, 'README.md') => remove_readme_paragraphs($file), - default => [], - }; -} - -if (! $useLaravelPint) { - safeUnlink(__DIR__.'/.github/workflows/fix-php-code-style-issues.yml'); - safeUnlink(__DIR__.'/pint.json'); -} - -if (! $usePhpStan) { - safeUnlink(__DIR__.'/phpstan.neon.dist'); - safeUnlink(__DIR__.'/phpstan-baseline.neon'); - safeUnlink(__DIR__.'/.github/workflows/phpstan.yml'); - - remove_composer_deps([ - 'phpstan/extension-installer', - 'phpstan/phpstan-deprecation-rules', - 'phpstan/phpstan-phpunit', - 'larastan/larastan', - ]); - - remove_composer_script('phpstan'); -} - -if (! $useDependabot) { - safeUnlink(__DIR__.'/.github/dependabot.yml'); - safeUnlink(__DIR__.'/.github/workflows/dependabot-auto-merge.yml'); -} - -if (! $useLaravelRay) { - remove_composer_deps(['spatie/laravel-ray']); -} - -if (! $useUpdateChangelogWorkflow) { - safeUnlink(__DIR__.'/.github/workflows/update-changelog.yml'); -} - -confirm('Execute `composer install` and run tests?') && run('composer install && composer test'); - -confirm('Let this script delete itself?', true) && unlink(__FILE__); diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php deleted file mode 100644 index c51604f..0000000 --- a/database/factories/ModelFactory.php +++ /dev/null @@ -1,19 +0,0 @@ -id(); - - // add fields - - $table->timestamps(); - }); - } -}; diff --git a/phpunit.xml.dist b/phpunit.xml.dist index bfe434d..841bd70 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -16,7 +16,7 @@ backupStaticProperties="false" > - + tests diff --git a/resources/views/.gitkeep b/resources/views/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Commands/SkeletonCommand.php b/src/Commands/SkeletonCommand.php deleted file mode 100644 index 3e5f628..0000000 --- a/src/Commands/SkeletonCommand.php +++ /dev/null @@ -1,19 +0,0 @@ -comment('All done'); - - return self::SUCCESS; - } -} diff --git a/src/Contracts/RuleParser.php b/src/Contracts/RuleParser.php new file mode 100644 index 0000000..715c490 --- /dev/null +++ b/src/Contracts/RuleParser.php @@ -0,0 +1,15 @@ +parse(); + } + +} diff --git a/src/SkeletonServiceProvider.php b/src/LaravelRulesToSchemaServiceProvider.php similarity index 50% rename from src/SkeletonServiceProvider.php rename to src/LaravelRulesToSchemaServiceProvider.php index b196c8a..db24ded 100644 --- a/src/SkeletonServiceProvider.php +++ b/src/LaravelRulesToSchemaServiceProvider.php @@ -1,12 +1,12 @@ name('skeleton') - ->hasConfigFile() - ->hasViews() - ->hasMigration('create_migration_table_name_table') - ->hasCommand(SkeletonCommand::class); + ->name('laravel-rules-to-schema') + ->hasConfigFile(); } } diff --git a/src/Parsers/ConfirmedParser.php b/src/Parsers/ConfirmedParser.php new file mode 100644 index 0000000..149f374 --- /dev/null +++ b/src/Parsers/ConfirmedParser.php @@ -0,0 +1,15 @@ +rules = $this->standardizeRules($this->rules); + } + + public function standardizeRules(array $rawRules): array + { + $nestedRules = []; + + foreach($rawRules as $name => $rules) { + + if (is_string($rules)) { + $rules = $this->splitStringToRuleset($rules); + } + + $rules = $this->normalizeRuleset($rules); + + Arr::set($nestedRules, "$name." . self::ValidationRuleToken, $rules); + } + + return $nestedRules; + } + + public function parse(): FluentSchema + { + $schema = FluentSchema::make() + ->type()->object() + ->return(); + + foreach($this->rules as $property => $rawRules) { + $propertySchema = $this->parseRuleset($property, $rawRules); + + if ($propertySchema instanceof FluentSchema) { + $schema->object()->property($property, $propertySchema); + } elseif (is_array($propertySchema)) { + $schema->object()->properties($propertySchema); + } + } + + return $schema; + } + + public function parseRuleset(string $name, array $nestedRuleset): null|FluentSchema|array + { + $validationRules = $nestedRuleset[self::ValidationRuleToken] ?? []; + + $schema = FluentSchema::make(); + + $this->applyTypeToSchema($schema, $validationRules, $name, $nestedRuleset); + + $this->applyNestedObjectsToSchema($schema, $validationRules, $name, $nestedRuleset); + + $this->applyFormatToSchema($schema, $validationRules); + + $this->applyOtherPropertiesToSchema($schema, $validationRules); + + $this->applyEnumOptionsToSchema($schema, $validationRules); + + $this->applyRequiredToSchema($schema, $validationRules); + + if ($this->checkIfExcluded($validationRules)) { + return null; + } + + if ($this->checkIfConfirmed($validationRules)) { + return [ + $name => $schema, + "{$name}_confirmed" => $schema, + ]; + } + + return $schema; + } + + protected function applyTypeToSchema(FluentSchema $schema, array $rules, string $name, array $ruleset): void + { + foreach($rules as $ruleArgs) { + [$rule, $args] = $ruleArgs; + + $ruleName = is_object($rule) ? get_class($rule) : $rule; + + if (in_array($ruleName, RuleCategory::strings())) { + $schema->type()->string(); + } + if (in_array($ruleName, RuleCategory::integers())) { + $schema->type()->integer(); + } + if (in_array($ruleName, RuleCategory::numbers())) { + $schema->type()->number(); + } + if (in_array($ruleName, RuleCategory::booleans())) { + $schema->type()->boolean(); + } + if (in_array($ruleName, RuleCategory::arrays())) { + // Check if what we are dealing with is not an object type with properties + if (count(array_diff_key($ruleset, array_flip([self::ValidationRuleToken]))) == 0) { + $schema->type()->array(); + } + } + if (in_array($ruleName, RuleCategory::nullables())) { + $schema->type()->null(); + } + + if ($rule instanceof EnumRule) { + $enumType = invade($rule)->type; + + $reflection = new ReflectionClass($enumType); + + if ( + $reflection->implementsInterface(\BackedEnum::class) + && count($reflection->getConstants()) > 0 + ) { + $value = array_values($reflection->getConstants())[0]->value; + + if (is_string($value)) { + $schema->type()->string(); + } + if (is_int($value)) { + $schema->type()->integer(); + } + } + } + + if ($rule instanceof InRule || $rule === 'in') { + if (is_string($rule)) { + $values = array_map(function(mixed $value) { + if (is_numeric($value)) { + if (ctype_digit($value)) { + return intval($value); + } + return floatval($value); + } + return $value; + }, $args); + } else { + $values = invade($rule)->values; + } + + $isString = true; + $isInt = true; + $isNumeric = true; + + foreach($values as $value) { + if (is_string($value)) { + $isString = $isString && true; + $isInt = false; + $isNumeric = false; + } + + if (is_int($value)) { + + $isString = false; + $isInt = $isInt && true; + $isNumeric = false; + } + + if (is_float($value)) { + $isString = false; + $isInt = false; + $isNumeric = $isNumeric && true; + } + } + + if ($isString) { + $schema->type()->string(); + } + if ($isInt) { + $schema->type()->integer(); + } + if ($isNumeric) { + $schema->type()->number(); + } + } + } + } + + protected function applyNestedObjectsToSchema(FluentSchema $schema, array $rules, string $name, array $ruleset): void + { + $nestedObjects = array_filter($ruleset, fn($x) => $x != self::ValidationRuleToken, ARRAY_FILTER_USE_KEY); + + if (count($nestedObjects) > 0) { + $isArray = array_key_exists('*', $nestedObjects); + + if ($isArray) { + $objSchema = $this->parseRuleset("$name.*", $nestedObjects['*']); + + $schema->type()->array() + ->items($objSchema); + } else { + foreach($nestedObjects as $propName => $objValidationRules) { + $schema->type()->object() + ->property($propName, $this->parseRuleset($propName, $objValidationRules)); + } + } + } + } + + protected function checkIfExcluded(array $rules): bool + { + foreach($rules as $ruleArgs) { + [$rule, $args] = $ruleArgs; + + if (is_string($rule) && in_array($rule, RuleCategory::excluded())) { + return true; + } + } + + return false; + } + + protected function checkIfConfirmed(array $rules): bool + { + foreach($rules as $ruleArgs) { + [$rule, $args] = $ruleArgs; + + if ($rule === 'confirmed') { + return true; + } + } + + return false; + } + + protected function applyRequiredToSchema(FluentSchema $schema, array $rules): void + { + $foundRequired = false; + foreach($rules as $ruleArgs) { + [$rule, $args] = $ruleArgs; + + if (!is_string($rule)) { + continue; + } + + if ($rule === 'sometimes') { + return; + } elseif ($rule == 'required') { + $foundRequired = true; + } + } + + if ($foundRequired) { + $schema->object()->required(); + } + } + + protected function applyFormatToSchema(FluentSchema $schema, array $rules): void + { + foreach($rules as $ruleArgs) { + [$rule, $args] = $ruleArgs; + + // Only enabling formatting for supported rules + // see https://laravel.com/docs/11.x/validation#available-validation-rules + + // Dates are not enabled because Laravel doesn't differentiate between dates and date-times + + match ($rule) { +// 'regex', 'not_regex' => $schema->format()->regex(), +// 'json-pointer' => $schema->format()->jsonPointer(), +// 'relative-json-pointer' => $schema->format()->relativeJsonPointer(), +// 'uri-template' => $schema->format()->uriTemplate(), + 'uuid' => $schema->format()->uuid(), +// 'iri-reference' => $schema->format()->iriReference(), +// 'iri' => $schema->format()->iri(), +// 'uri-reference' => $schema->format()->uriReference(), +// 'uri' => $schema->format()->uri(), + 'url' => $schema->format()->uri(), + 'ipv4' => $schema->format()->ipv4(), + 'ipv6' => $schema->format()->ipv6(), +// 'hostname' => $schema->format()->hostname(), +// 'idn-hostname' => $schema->format()->idnHostname(), + 'email' => $schema->format()->email(), +// 'idn-email' => $schema->format()->idnEmail(), +// 'date-time' => $schema->format()->dateTime(), +// 'date', 'date_format', 'date_equals' => $schema->format()->dateTime(), +// 'time' => $schema->format()->time(), +// 'duration' => $schema->format()->duration(), + default => null, + }; + + // TODO: Also validate mimes file extensions somehow? + if ($rule == 'mimetypes' && count($args) > 0) { + // TODO: What to do about the rest of the specified mime types + $schema->content()->mediaType($args[0]); + } + } + } + + protected function applyOtherPropertiesToSchema(FluentSchema $schema, array $rules): void + { + /** @var JsonSchemaType[] $schemaTypes */ + $schemaTypes = $schema->getSchemaDTO()->type; + + foreach($rules as $ruleArgs) { + [$rule, $args] = $ruleArgs; + + foreach($schemaTypes ?? [] as $type) { + if ($type === JsonSchemaType::STRING) { + if ($rule === 'min' && count($args) > 0) { + $schema->string()->minLength($args[0]); + } elseif ($rule === 'max' && count($args) > 0) { + $schema->string()->maxLength($args[0]); + } + } elseif (in_array($type, [JsonSchemaType::INTEGER, JsonSchemaType::NUMBER])) { + if ($rule === 'min' && count($args) > 0) { + $schema->number()->minimum($args[0]); + } elseif ($rule === 'max' && count($args) > 0) { + $schema->number()->maximum($args[0]); + } + } elseif ($type === JsonSchemaType::ARRAY) { + if ($rule === 'min' && count($args) > 0) { + $schema->array()->minItems($args[0]); + } elseif ($rule === 'max' && count($args) > 0) { + $schema->array()->maxItems($args[0]); + } + } + } + + if ($rule === 'regex' && count($args) > 0) { + + $matched = preg_match('/^(.)(.*?)\1[a-zA-Z]*$/', $args[0], $matches); + + if ($matched) { + $schema->string()->pattern($matches[2]); + } + } + } + } + + protected function applyEnumOptionsToSchema(FluentSchema $schema, array $rules): void + { + foreach($rules as $ruleArgs) { + [$rule, $args] = $ruleArgs; + + if ($rule instanceof EnumRule) { + $enumType = invade($rule)->type; + + $reflection = new ReflectionClass($enumType); + + if (count($reflection->getConstants()) > 0) { + $values = array_values(array_map(function(\UnitEnum|\BackedEnum $c) { + return $c instanceof \BackedEnum ? $c->value : $c->name; + }, $reflection->getConstants())); + + $schema->object()->enum($values); + } + } + } + } + + /** + * Utility Functions + */ + + /** + * @param array $rules + * @return array + */ + protected function normalizeRuleset(array $rules): array + { + $normalized = []; + + foreach($rules as $rule) { + if (is_string($rule)) { + $result = $this->parseStringRuleArgs($rule); + $normalized[] = $result; + } else { + $normalized[] = [$rule, null]; + } + } + + return $normalized; + } + + protected function splitStringToRuleset(string $rules): array + { + $instance = new ValidationRuleParser([]); + $class = new ReflectionClass($instance); + $method = $class->getMethod('explodeExplicitRule'); + $method->setAccessible(true); + + return $method->invokeArgs($instance, [$rules, null]); + } + + protected function parseStringRuleArgs(string $rule): array + { + $instance = new ValidationRuleParser([]); + $class = new ReflectionClass($instance); + $method = $class->getMethod('parseParameters'); + $method->setAccessible(true); + + $parameters = []; + + if (str_contains($rule, ':')) { + [$rule, $parameter] = explode(':', $rule, 2); + + $parameters = $method->invokeArgs($instance, [$rule, $parameter]); + } + + return [trim($rule), $parameters]; + } +} diff --git a/src/Skeleton.php b/src/Skeleton.php deleted file mode 100755 index 34c7194..0000000 --- a/src/Skeleton.php +++ /dev/null @@ -1,5 +0,0 @@ - 'string|url|min:6', + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('string types', function() { + $rules = [ + 'string_property' => ['string'], + 'password_property' => ['password'], + 'date_property' => ['date'], + 'alpha_property' => ['alpha'], + 'alpha_dash_property' => ['alpha_dash'], + 'alpha_num_property' => ['alpha_num'], + 'enum_property' => [new Enum(TestStringBackedEnum::class)], + 'ip_property' => ['ip'], + 'ipv4_property' => ['ipv4'], + 'ipv6_property' => ['ipv6'], + 'mac_address_property' => ['mac_address'], + 'json_property' => ['json'], + 'url_property' => ['url'], + 'uuid_property' => ['uuid'], + 'ulid_property' => ['ulid'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('integer types', function() { + $rules = [ + 'integer_property' => ['integer'], + 'int_property' => ['int'], + 'enum_property' => [new Enum(TestIntBackedEnum::class)], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('numeric types', function() { + $rules = [ + 'decimal_property' => ['decimal:2,5'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('boolean types', function() { + $rules = [ + 'boolean_property' => ['boolean'], + 'bool_property' => ['bool'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('nullable types', function() { + $rules = [ + 'nullable_property' => ['nullable', 'string'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('nullable objects and arrays', function() { + $rules = [ + 'nullable_object' => ['nullable'], + 'nullable_object.myProperty' => ['string'], + 'nullable_array' => ['nullable', 'array'], + 'nullable_array.*' => ['string'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('nested object properties', function() { + $rules = [ + 'array.*' => ['string'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('nested objects', function() { + $rules = [ + 'object1.object2.property1' => ['string'], + 'object1.object2.property2' => ['string'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('nested object with array', function() { + $rules = [ + 'object1.object2.*' => ['string'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('nested arrays', function() { + $rules = [ + 'array' => ['array', 'one'], + 'array.*' => ['array', 'two'], + 'array.*.one' => ['array', 'three'], + 'array.*.one.*' => ['string'], + 'array.*.two.*.property1' => ['string'], + 'array.*.two.*.property2' => ['string'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('excluded attributes are not displayed', function() { + $rules = [ + 'prohibited_property' => ['prohibited'], + 'missing_property' => ['missing'], + 'exclude_property' => ['exclude'], + 'other_property' => ['string'], + ]; + + // TODO: These can be prohibited in the schema using not + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('confirmed rule adds additional field', function() { + $rules = [ + 'password' => ['string', 'confirmed'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('can infer type from in rule', function() { + $rules = [ + 'in_rule' => [Rule::in([1, 2, 3])], + 'in_rule_str' => ['in:a,b,c'], + 'in_mixed' => ['in:1,b,c'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('can infer type from exists rule', function() { + $rules = [ + 'exists_property' => [Rule::exists(TestModel::class)], + 'exists_str_property' => ['exists:test_models,name'], + ]; +})->skip('Need to parse migration/schema doc'); + +test('required', function() { + $rules = [ + 'required_property' => ['required'], + 'sometimes_required' => ['sometimes', 'required'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('format', function() { + $rules = [ + 'regex' => ['regex'], + 'not_regex' => ['not_regex'], + 'uuid' => ['uuid'], + 'url' => ['url'], + 'ipv4' => ['ipv4'], + 'ipv6' => ['ipv6'], + 'email' => ['email'], + 'date' => ['date'], + 'date_format' => ['date_format'], + 'date_equals' => ['date_equals'], + 'mimetypes' => ['mimetypes:application/json,image/png'], + 'mimes' => ['mimes:png,jpg'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('rules apply other attributes', function() { + $rules = [ + 'str_min' => ['string', 'min:1'], + 'str_max' => ['string', 'max:10'], + 'int_min' => ['int', 'min:1'], + 'int_max' => ['int', 'max:10'], + 'float_min' => ['decimal', 'min:1'], + 'float_max' => ['decimal', 'max:10'], + 'array_min' => ['array', 'min:1'], + 'array_max' => ['array', 'max:10'], + + 'regex' => ['regex:/[a-z]{4}/i'], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); + +test('enum', function() { + $rules = [ + 'enum' => [new Enum(TestEnum::class)], + 'string_enum' => [new Enum(TestStringBackedEnum::class)], + 'int_enum' => [new Enum(TestIntBackedEnum::class)], + ]; + + expect(LaravelRulesToSchema::parse($rules)->compile()) + ->toMatchSnapshot(); +}); diff --git a/tests/Pest.php b/tests/Pest.php index 7fe1500..89edfad 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,5 @@ in(__DIR__); diff --git a/tests/TestCase.php b/tests/TestCase.php index d04fb0c..0239ca4 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,10 +1,10 @@ 'VendorName\\Skeleton\\Database\\Factories\\'.class_basename($modelName).'Factory' + fn (string $modelName) => 'LaravelRulesToSchema\\LaravelRulesToSchema\\Database\\Factories\\'.class_basename($modelName).'Factory' ); } protected function getPackageProviders($app) { return [ - SkeletonServiceProvider::class, + LaravelRulesToSchemaServiceProvider::class, ]; } @@ -29,7 +29,7 @@ public function getEnvironmentSetUp($app) config()->set('database.default', 'testing'); /* - $migration = include __DIR__.'/../database/migrations/create_skeleton_table.php.stub'; + $migration = include __DIR__.'/../database/migrations/create_laravel-rules-to-schema_table.php.stub'; $migration->up(); */ } diff --git a/workbench/app/Providers/WorkbenchServiceProvider.php b/workbench/app/Providers/WorkbenchServiceProvider.php deleted file mode 100644 index 001d06d..0000000 --- a/workbench/app/Providers/WorkbenchServiceProvider.php +++ /dev/null @@ -1,25 +0,0 @@ -