From 3aa16a8fa9111e0fa1650be5b6ad6b8bfd000e0e Mon Sep 17 00:00:00 2001 From: Maurizio Date: Wed, 12 Jul 2023 20:33:22 +0200 Subject: [PATCH] wip --- .github/ISSUE_TEMPLATE/config.yml | 6 +- CHANGELOG.md | 2 +- LICENSE.md | 2 +- README.md | 138 ++++++--- composer.json | 29 +- config/human-id.php | 20 ++ config/skeleton.php | 6 - configure.php | 266 ------------------ database/factories/ModelFactory.php | 19 -- phpstan-baseline.neon | 6 + phpstan.neon.dist | 1 - phpunit.xml.dist | 2 +- resources/views/.gitkeep | 0 src/Commands/SkeletonCommand.php | 19 -- src/Concerns/HasHuids.php | 114 ++++++++ src/Database/Schema/Blueprints/HumanId.php | 20 ++ src/Facades/Skeleton.php | 16 -- src/HumanIdServiceProvider.php | 24 ++ src/Skeleton.php | 7 - src/SkeletonServiceProvider.php | 25 -- src/Support/String.php | 27 ++ tests/ExampleTest.php | 5 - tests/HumanIdTest.php | 30 ++ tests/Pest.php | 7 +- tests/StringTest.php | 15 + tests/TestCase.php | 38 ++- ...01_01_000000_testbench_create_my_table.php | 8 +- 27 files changed, 398 insertions(+), 454 deletions(-) create mode 100644 config/human-id.php delete mode 100644 config/skeleton.php delete mode 100644 configure.php delete mode 100644 database/factories/ModelFactory.php delete mode 100644 resources/views/.gitkeep delete mode 100644 src/Commands/SkeletonCommand.php create mode 100644 src/Concerns/HasHuids.php create mode 100644 src/Database/Schema/Blueprints/HumanId.php delete mode 100644 src/Facades/Skeleton.php create mode 100644 src/HumanIdServiceProvider.php delete mode 100755 src/Skeleton.php delete mode 100644 src/SkeletonServiceProvider.php create mode 100644 src/Support/String.php delete mode 100644 tests/ExampleTest.php create mode 100644 tests/HumanIdTest.php create mode 100644 tests/StringTest.php rename database/migrations/create_skeleton_table.php.stub => tests/database/migrations/2023_01_01_000000_testbench_create_my_table.php (65%) diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 96701be..81b72d3 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_name/:package_name/discussions/new?category=q-a + url: https://github.com/lemaur/laravel-human-id/discussions/new?category=q-a about: Ask the community for help - name: Request a feature - url: https://github.com/:vendor_name/:package_name/discussions/new?category=ideas + url: https://github.com/lemaur/laravel-human-id/discussions/new?category=ideas about: Share ideas for new features - name: Report a security issue - url: https://github.com/:vendor_name/:package_name/security/policy + url: https://github.com/lemaur/laravel-human-id/security/policy about: Learn how to notify us for sensitive bugs diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b3242..d3b85d6 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-human-id` will be documented in this file. diff --git a/LICENSE.md b/LICENSE.md index 58c9ad4..f131d54 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) :vendor_name +Copyright (c) lemaur 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..b50232c 100644 --- a/README.md +++ b/README.md @@ -1,70 +1,126 @@ -# :package_description +# Laravel Human IDs -[![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: +[![Latest Version on Packagist](https://img.shields.io/packagist/v/lemaur/laravel-human-id.svg?style=flat-square)](https://packagist.org/packages/lemaur/laravel-human-id) +[![Total Downloads](https://img.shields.io/packagist/dt/lemaur/laravel-human-id.svg?style=flat-square)](https://packagist.org/packages/lemaur/laravel-human-id) +[![License](https://img.shields.io/packagist/l/lemaur/laravel-human-id.svg?style=flat-square&color=yellow)](https://github.com/leMaur/laravel-human-id/blob/main/LICENSE.md) +[![Tests](https://img.shields.io/github/actions/workflow/status/lemaur/laravel-human-id/run-tests.yml?label=tests&style=flat-square)](https://github.com/leMaur/laravel-human-id/actions/workflows/run-tests.yml) +[![GitHub Sponsors](https://img.shields.io/github/sponsors/lemaur?style=flat-square&color=ea4aaa)](https://github.com/sponsors/leMaur) +[![Trees](https://img.shields.io/badge/dynamic/json?color=yellowgreen&style=flat-square&label=Trees&query=%24.total&url=https%3A%2F%2Fpublic.offset.earth%2Fusers%2Flemaur%2Ftrees)](https://ecologi.com/lemaur?r=6012e849de97da001ddfd6c9) -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 where your description should go. Limit it to a paragraph or two. Consider adding a small example. +This package has been inspired by the article "Designing APIs for humans: Object IDs" appeared on [Dev](https://dev.to/stripe/designing-apis-for-humans-object-ids-3o5a) (Aug 30, 2022 / by [Paul Asjes](https://dev.to/paulasjes)). -## Support us +I really like the approach Stripe uses to define the object ID, so I figured out how to make something similar for Laravel. +Basically, the package generate a so-called "human id" by prepending a prefix to a ULID with a separator between them. -[](https://spatie.be/github-ad-click/:package_name) +An example should be better than a thousand words... -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). +```md +👇 the structure ----------------- -We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards). +{prefix}{separator}{ulid} -## Installation -You can install the package via composer: +👇 the params -------------------- -```bash -composer require :vendor_slug/:package_slug -``` +prefix: post +separator: _ +ulid: 26 alphanumeric characters -You can publish and run the migrations with: -```bash -php artisan vendor:publish --tag=":package_slug-migrations" -php artisan migrate +👇 the result -------------------- + +post_01h554vp2prg6zfayagh83ccx7 ``` -You can publish the config file with: +
+ +## Support Me + +Hey folks, + +Do you like this package? Do you find it useful, and it fits well in your project? + +I am glad to help you, and I would be so grateful if you considered supporting my work. + +You can even choose 😃: +* You can [sponsor me 😎](https://github.com/sponsors/leMaur) with a monthly subscription. +* You can [buy me a coffee ☕ or a pizza 🍕](https://github.com/sponsors/leMaur?frequency=one-time&sponsor=leMaur) just for this package. +* You can [plant trees 🌴](https://ecologi.com/lemaur?r=6012e849de97da001ddfd6c9). By using this link we will both receive 30 trees for free and the planet (and me) will thank you. +* You can "Star ⭐" this repository (it's free 😉). + +
+ +## Installation + +You can install the package via composer: ```bash -php artisan vendor:publish --tag=":package_slug-config" +composer require lemaur/laravel-human-id ``` -This is the contents of the published config file: +
+ +## Usage + +1. Add the "human ID" field in your migration files. +2. Import the `Lemaur\HumanId\Concerns\HasHuids` trait into your eloquent model. + +Here's a real-life example of how to implement the trait on a model. ```php -return [ -]; +// database\migrations\create_posts_table.php + +use Illuminate\Database\Migrations\Migration; +use Illuminate\Database\Schema\Blueprint; +use Illuminate\Support\Facades\Schema; + +return new class extends Migration +{ + public function up(): void + { + Schema::create('posts', static function (Blueprint $table) { + $table->id(); + + $table->huid(); // <-- declare "huid" field + + // other fields... + }); + } +} ``` -Optionally, you can publish the views using +```php +// app\Models\Post.php -```bash -php artisan vendor:publish --tag=":package_slug-views" +namespace App\Models; + +use \Illuminate\Database\Eloquent\Model; +use \Lemaur\HumanId\Concerns\HasHuids; + +class Post extends Model +{ + use HasHuids; // <-- import trait + + /** @var string */ + private const HUID_PREFIX = 'post'; // <-- declare prefix (max 4 characters length) +} + +// this will generate a huid like --> post_01h554vp2prg6zfayagh83ccx7 ``` -## Usage +
-```php -$variable = new VendorName\Skeleton(); -echo $variable->echoPhrase('Hello, VendorName!'); +## Configuration + +You can use a different name for the field (currently is "huid") and the separator character (currently is "_"). +To do that, you should publish the configuration file and change them from there. + +```bash +php artisan vendor:publish --tag=human-id-config ``` +
+ ## Testing ```bash @@ -85,7 +141,7 @@ Please review [our security policy](../../security/policy) on how to report secu ## Credits -- [:author_name](https://github.com/:author_username) +- [leMaur](https://github.com/lemaur) - [All Contributors](../../contributors) ## License diff --git a/composer.json b/composer.json index c1db049..e0283b7 100644 --- a/composer.json +++ b/composer.json @@ -1,17 +1,17 @@ { - "name": ":vendor_slug/:package_slug", - "description": ":package_description", + "name": "lemaur/laravel-human-id", + "description": "Automatically generate Human IDs for your model.", "keywords": [ - ":vendor_name", + "lemaur", "laravel", - ":package_slug" + "laravel-human-id" ], - "homepage": "https://github.com/:vendor_slug/:package_slug", + "homepage": "https://github.com/lemaur/laravel-human-id", "license": "MIT", "authors": [ { - "name": ":author_name", - "email": "author@domain.com", + "name": "lemaur", + "email": "hello@lemaur.me", "role": "Developer" } ], @@ -30,18 +30,16 @@ "pestphp/pest-plugin-laravel": "^2.0", "phpstan/extension-installer": "^1.1", "phpstan/phpstan-deprecation-rules": "^1.0", - "phpstan/phpstan-phpunit": "^1.0", - "spatie/laravel-ray": "^1.26" + "phpstan/phpstan-phpunit": "^1.0" }, "autoload": { "psr-4": { - "VendorName\\Skeleton\\": "src/", - "VendorName\\Skeleton\\Database\\Factories\\": "database/factories/" + "Lemaur\\HumanId\\": "src/" } }, "autoload-dev": { "psr-4": { - "VendorName\\Skeleton\\Tests\\": "tests/" + "Lemaur\\HumanId\\Tests\\": "tests/" } }, "scripts": { @@ -61,11 +59,8 @@ "extra": { "laravel": { "providers": [ - "VendorName\\Skeleton\\SkeletonServiceProvider" - ], - "aliases": { - "Skeleton": "VendorName\\Skeleton\\Facades\\Skeleton" - } + "Lemaur\\HumanId\\HumanIdServiceProvider" + ] } }, "minimum-stability": "dev", diff --git a/config/human-id.php b/config/human-id.php new file mode 100644 index 0000000..65bb0ac --- /dev/null +++ b/config/human-id.php @@ -0,0 +1,20 @@ + 'huid', + + /* + |-------------------------------------------------------------------------- + | Prefix Separator + |-------------------------------------------------------------------------- + | + */ + 'separator' => '_', +]; diff --git a/config/skeleton.php b/config/skeleton.php deleted file mode 100644 index 7e74186..0000000 --- a/config/skeleton.php +++ /dev/null @@ -1,6 +0,0 @@ - $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__))); -} - -$gitName = run('git config user.name'); -$authorName = ask('Author name', $gitName); - -$gitEmail = run('git config user.email'); -$authorEmail = ask('Author email', $gitEmail); - -$usernameGuess = explode(':', run('git config remote.origin.url'))[1]; -$usernameGuess = dirname($usernameGuess); -$usernameGuess = basename($usernameGuess); -$authorUsername = ask('Author username', $usernameGuess); - -$vendorName = ask('Vendor name', $authorUsername); -$vendorSlug = slugify($vendorName); -$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', - 'nunomaduro/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 @@ - - + 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/Concerns/HasHuids.php b/src/Concerns/HasHuids.php new file mode 100644 index 0000000..3d30183 --- /dev/null +++ b/src/Concerns/HasHuids.php @@ -0,0 +1,114 @@ +usesUniqueIds = true; + } + + /** + * Get the columns that should receive a unique identifier. + * + * @return array + */ + public function uniqueIds(): array + { + return [(string) config('human-id.field', 'huid')]; + } + + /** + * Generate a new ULID for the model. + * + * @return string + * @throws RuntimeException + */ + public function newUniqueId(): string + { + if (! defined('static::HUID_PREFIX')) { + throw new RuntimeException('Unable to find HUID_PREFIX. Please add it as private constant to your model.'); + } + + if (! is_string(static::HUID_PREFIX)) { + throw new RuntimeException('HUID_PREFIX should contain only alpha characters.'); + } + + $len = strlen(static::HUID_PREFIX); + + if ($len < 1 || $len > 4) { + throw new RuntimeException('HUID_PREFIX length should be between 1 and 4 characters.'); + } + + return Str::of(static::HUID_PREFIX) + ->slug('') + ->limit(4, '') + ->append((string) config('human-id.separator', '_')) + ->append(Str::ulid()) + ->lower() + ->toString(); + } + + /** + * Retrieve the model for a bound value. + * + * @param Model|Relation $query + * @param mixed $value + * @param string|null $field + * @return Relation + * + * @throws ModelNotFoundException + */ + public function resolveRouteBindingQuery($query, $value, $field = null): Relation + { + if ($field && ! Str::isHuid($value) && in_array($field, $this->uniqueIds(), true)) { + throw (new ModelNotFoundException)->setModel(get_class($this), $value); + } + + if (! $field && ! Str::isHuid($value) && in_array($this->getRouteKeyName(), $this->uniqueIds(), true)) { + throw (new ModelNotFoundException)->setModel(get_class($this), $value); + } + + return parent::resolveRouteBindingQuery($query, $value, $field); + } + + /** + * Get the auto-incrementing key type. + * + * @return string + */ + public function getKeyType(): string + { + if (in_array($this->getKeyName(), $this->uniqueIds(), true)) { + return 'string'; + } + + return $this->keyType; + } + + /** + * Get the value indicating whether the IDs are incrementing. + * + * @return bool + */ + public function getIncrementing(): bool + { + if (in_array($this->getKeyName(), $this->uniqueIds(), true)) { + return false; + } + + return $this->incrementing; + } +} diff --git a/src/Database/Schema/Blueprints/HumanId.php b/src/Database/Schema/Blueprints/HumanId.php new file mode 100644 index 0000000..e027078 --- /dev/null +++ b/src/Database/Schema/Blueprints/HumanId.php @@ -0,0 +1,20 @@ +char($column, 31); +}); diff --git a/src/Facades/Skeleton.php b/src/Facades/Skeleton.php deleted file mode 100644 index 1fa9076..0000000 --- a/src/Facades/Skeleton.php +++ /dev/null @@ -1,16 +0,0 @@ -name('laravel-human-id') + ->hasConfigFile(); + } + + public function packageBooted(): void + { + collect(array_merge( + (array) glob(__DIR__.'/Database/Schema/Blueprints/*.php'), + (array) glob(__DIR__.'/Support/*.php') + ))->each(static fn ($path) => require $path); + } +} diff --git a/src/Skeleton.php b/src/Skeleton.php deleted file mode 100755 index 66fab60..0000000 --- a/src/Skeleton.php +++ /dev/null @@ -1,7 +0,0 @@ -name('skeleton') - ->hasConfigFile() - ->hasViews() - ->hasMigration('create_skeleton_table') - ->hasCommand(SkeletonCommand::class); - } -} diff --git a/src/Support/String.php b/src/Support/String.php new file mode 100644 index 0000000..cd38c06 --- /dev/null +++ b/src/Support/String.php @@ -0,0 +1,27 @@ +toBeTrue(); -}); diff --git a/tests/HumanIdTest.php b/tests/HumanIdTest.php new file mode 100644 index 0000000..143a92b --- /dev/null +++ b/tests/HumanIdTest.php @@ -0,0 +1,30 @@ +huid) + ->toBeHuid() + ->toStartWith('usr_'); +}); + +it('fails if prefix is not set', function () { + TestModelWithoutPrefix::create(); +})->throws(RuntimeException::class); + +class TestModelWithPrefix extends Model +{ + use HasHuids; + + private const HUID_PREFIX = 'usr'; + + protected $table = 'my_table'; +} + +class TestModelWithoutPrefix extends Model +{ + use HasHuids; + + protected $table = 'my_table'; +} diff --git a/tests/Pest.php b/tests/Pest.php index 7fe1500..3358188 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,10 @@ in(__DIR__); + +expect()->extend('toBeHuid', function () { + return expect(Str::isHuid($this->value))->toBeTrue(); +}); diff --git a/tests/StringTest.php b/tests/StringTest.php new file mode 100644 index 0000000..a25f88c --- /dev/null +++ b/tests/StringTest.php @@ -0,0 +1,15 @@ +toBeFalse(); + expect(Str::isHuid(123))->toBeFalse(); + expect(Str::isHuid(null))->toBeFalse(); + expect(Str::isHuid([]))->toBeFalse(); + + $testHuid = Str::lower('post_'.Ulid::fromString('01GNNA1J00DYW71SWPDHN0F1S5')); + + expect(Str::isHuid($testHuid))->toBeTrue(); +}); diff --git a/tests/TestCase.php b/tests/TestCase.php index d04fb0c..c49bc9b 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,36 +1,34 @@ 'VendorName\\Skeleton\\Database\\Factories\\'.class_basename($modelName).'Factory' - ); - } - - protected function getPackageProviders($app) + protected function getPackageProviders($app): array { return [ - SkeletonServiceProvider::class, + HumanIdServiceProvider::class, ]; } - public function getEnvironmentSetUp($app) + protected function defineEnvironment($app): void { - config()->set('database.default', 'testing'); + tap($app->make('config'), function (Repository $config) { + $config->set('database.default', 'testbench'); + $config->set('database.connections.testbench', [ + 'driver' => 'sqlite', + 'database' => ':memory:', + 'prefix' => '', + ]); + }); + } - /* - $migration = include __DIR__.'/../database/migrations/create_skeleton_table.php.stub'; - $migration->up(); - */ + protected function defineDatabaseMigrations(): void + { + $this->loadMigrationsFrom(__DIR__.'/database/migrations'); } } diff --git a/database/migrations/create_skeleton_table.php.stub b/tests/database/migrations/2023_01_01_000000_testbench_create_my_table.php similarity index 65% rename from database/migrations/create_skeleton_table.php.stub rename to tests/database/migrations/2023_01_01_000000_testbench_create_my_table.php index 2efdce9..3971cbd 100644 --- a/database/migrations/create_skeleton_table.php.stub +++ b/tests/database/migrations/2023_01_01_000000_testbench_create_my_table.php @@ -6,13 +6,11 @@ return new class extends Migration { - public function up() + public function up(): void { - Schema::create('migration_table_name_table', function (Blueprint $table) { + Schema::create('my_table', static function (Blueprint $table) { $table->id(); - - // add fields - + $table->huid(); $table->timestamps(); }); }