diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index c68765b..7e5acfc 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1 @@ -github: :vendor_name +github: rescaled diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 80a788c..18db339 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,14 +1,14 @@ 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/rescaled/simple-feature/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/rescaled/simple-feature/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/rescaled/simple-feature/security/policy about: Learn how to notify us for sensitive bugs - name: Report a bug - url: https://github.com/:vendor_name/:package_name/issues/new + url: https://github.com/rescaled/simple-feature/issues/new about: Report a reproducable bug diff --git a/.github/SECURITY.md b/.github/SECURITY.md deleted file mode 100644 index 12ab7c2..0000000 --- a/.github/SECURITY.md +++ /dev/null @@ -1,3 +0,0 @@ -# Security Policy - -If you discover any security related issues, please email author@domain.com instead of using the issue tracker. diff --git a/CHANGELOG.md b/CHANGELOG.md index 767365d..63e9cc1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,7 @@ # Changelog -All notable changes to `:package_name` will be documented in this file. +All notable changes to `simple-feature` will be documented in this file. -## 1.0.0 - 202X-XX-XX +## 1.0.0 - 2022-01-17 - initial release diff --git a/LICENSE.md b/LICENSE.md index 58c9ad4..34fa8e6 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) :vendor_name +Copyright (c) rescaled GmbH 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 35917e4..06633c9 100644 --- a/README.md +++ b/README.md @@ -1,68 +1,38 @@ -# :package_description +# Simple Feature -[![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/workflow/status/:vendor_slug/:package_slug/run-tests?label=tests)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3Arun-tests+branch%3Amain) -[![GitHub Code Style Action Status](https://img.shields.io/github/workflow/status/:vendor_slug/:package_slug/Check%20&%20fix%20styling?label=code%20style)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3A"Check+%26+fix+styling"+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/rescaled/simple-feature.svg?style=flat-square)](https://packagist.org/packages/rescaled/simple-feature) +[![GitHub Tests Action Status](https://img.shields.io/github/workflow/status/rescaled/simple-feature/run-tests?label=tests)](https://github.com/rescaled/simple-feature/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/workflow/status/rescaled/simple-feature/Check%20&%20fix%20styling?label=code%20style)](https://github.com/rescaled/simple-feature/actions?query=workflow%3A"Check+%26+fix+styling"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/rescaled/simple-feature.svg?style=flat-square)](https://packagist.org/packages/rescaled/simple-feature) -1. Press the "Use 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. - -## Support us - -[](https://spatie.be/github-ad-click/:package_name) - -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). - -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). +Simple Feature allows you to define feature flags via environment variables and check for their state within +your Laravel application. It also provides pre-defined middleware you can utilize for this use case. ## Installation You can install the package via composer: ```bash -composer require :vendor_slug/:package_slug -``` - -You can publish and run the migrations with: - -```bash -php artisan vendor:publish --tag=":package_slug-migrations" -php artisan migrate +composer require rescaled/simple-feature ``` -You can publish the config file with: - -```bash -php artisan vendor:publish --tag=":package_slug-config" -``` - -This is the contents of the published config file: - -```php -return [ -]; -``` +## Usage -Optionally, you can publish the views using +```dotenv +FEATURE_FIRST_TEST=true +FEATURE_SECOND_TEST=true -```bash -php artisan vendor:publish --tag=":package_slug-views" +FEATURE_THIRD_TEST=false +FEATURE_FOURTH_TEST=false ``` -## Usage - ```php -$variable = new VendorName\Skeleton(); -echo $variable->echoPhrase('Hello, VendorName!'); +SimpleFeature::enabled('firstTest') // true +SimpleFeature::disabled('firstTest') // false +SimpleFeature::allEnabled(['firstTest', 'secondTest']) // true +SimpleFeature::allDisabled(['thirdTest', 'fourthTest']) // true +SimpleFeature::allEnabled(['firstTest', 'thirdTest']) // false +SimpleFeature::allDisabled(['firstTest', 'thirdTest']) // false ``` ## Testing @@ -81,11 +51,11 @@ Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details. ## Security Vulnerabilities -Please review [our security policy](../../security/policy) on how to report security vulnerabilities. +Please report security vulnerabilities directly to the maintainer. You can find contact information on their GitHub profile. ## Credits -- [:author_name](https://github.com/:author_username) +- [Tobias Hannaske](https://github.com/thannaske) - [All Contributors](../../contributors) ## License diff --git a/composer.json b/composer.json index 1ffdef8..e2753ef 100644 --- a/composer.json +++ b/composer.json @@ -1,17 +1,17 @@ { - "name": ":vendor_slug/:package_slug", - "description": ":package_description", + "name": "rescaled/simple-feature", + "description": "This package aims to provide a fully-featured, yet simple feature flag configuration through environment variables for Laravel 7+", "keywords": [ - ":vendor_name", + "rescaled", "laravel", - ":package_slug" + "simple-feature" ], - "homepage": "https://github.com/:vendor_slug/:package_slug", + "homepage": "https://github.com/rescaled/simple-feature", "license": "MIT", "authors": [ { - "name": ":author_name", - "email": "author@domain.com", + "name": "Tobias Hannaske", + "email": "th@rescaled.de", "role": "Developer" } ], @@ -29,18 +29,17 @@ "phpstan/extension-installer": "^1.1", "phpstan/phpstan-deprecation-rules": "^1.0", "phpstan/phpstan-phpunit": "^1.0", - "phpunit/phpunit": "^9.5", - "spatie/laravel-ray": "^1.26" + "phpunit/phpunit": "^9.5" }, "autoload": { "psr-4": { - "VendorName\\Skeleton\\": "src", - "VendorName\\Skeleton\\Database\\Factories\\": "database/factories" + "Rescaled\\SimpleFeature\\": "src", + "Rescaled\\SimpleFeature\\Database\\Factories\\": "database/factories" } }, "autoload-dev": { "psr-4": { - "VendorName\\Skeleton\\Tests\\": "tests" + "Rescaled\\SimpleFeature\\Tests\\": "tests" } }, "scripts": { @@ -54,10 +53,10 @@ "extra": { "laravel": { "providers": [ - "VendorName\\Skeleton\\SkeletonServiceProvider" + "Rescaled\\SimpleFeature\\SimpleFeatureServiceProvider" ], "aliases": { - "Skeleton": "VendorName\\Skeleton\\Facades\\Skeleton" + "SimpleFeature": "Rescaled\\SimpleFeature\\Facades\\SimpleFeature" } } }, diff --git a/config/skeleton.php b/config/skeleton.php deleted file mode 100644 index fbb0e4c..0000000 --- a/config/skeleton.php +++ /dev/null @@ -1,5 +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 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|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 = 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); -$usePhpCsFixer = confirm('Enable PhpCsFixer?', 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 PhpCsFixer : " . ($usePhpCsFixer ? 'yes' : 'no')); -writeln("Use Larastan/PhpStan : " . ($usePhpStan ? '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, - '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_' . $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 (! $usePhpCsFixer) { - safeUnlink(__DIR__ . '/.php_cs.dist.php'); - safeUnlink(__DIR__ . '/.github/workflows/php-cs-fixer.yml'); -} - -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 (! $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 3bbe22a..6eb0cd3 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -19,7 +19,7 @@ verbose="true" > - + tests @@ -36,4 +36,9 @@ + + + + + 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/Facades/SimpleFeature.php b/src/Facades/SimpleFeature.php new file mode 100644 index 0000000..fe97c31 --- /dev/null +++ b/src/Facades/SimpleFeature.php @@ -0,0 +1,21 @@ +state($feature) !== null ? $this->state($feature) === true : $default; + } + + /** + * Checks whether a given feature is disabled or not + * @param string $feature + * @param bool $default + * @return bool + */ + public function disabled(string $feature, bool $default = true): bool + { + return $this->state($feature) !== null ? $this->state($feature) === false : $default; + } + + /** + * Checks whether all features are enabled or not + * @param array $features + * @param bool $default + * @return bool + */ + public function allEnabled(array $features, bool $default = false): bool + { + foreach ($features as $feature) { + if ($this->disabled($feature, $default)) { + return false; + } + } + + return true; + } + + /** + * Checks whether all features are disabled or not + * @param array $features + * @param bool $default + * @return bool + */ + public function allDisabled(array $features, bool $default = false): bool + { + foreach ($features as $feature) { + if ($this->enabled($feature, $default)) { + return false; + } + } + + return true; + } + + /** + * Returns the actual state of a feature + * @param string $feature + * @return bool|null + */ + public function state(string $feature): ?bool + { + return env("FEATURE_" . Str::upper(Str::snake($feature))); + } +} diff --git a/src/SimpleFeatureServiceProvider.php b/src/SimpleFeatureServiceProvider.php new file mode 100644 index 0000000..1fe2315 --- /dev/null +++ b/src/SimpleFeatureServiceProvider.php @@ -0,0 +1,35 @@ +name('simple-feature'); + } + + public function registeringPackage() + { + $this->app->singleton(SimpleFeature::class, function ($app) { + return new SimpleFeature(); + }); + + $this->registerMiddleware(); + } + + public function registerMiddleware(): void + { + /** @var Router $router */ + $router = $this->app['router']; + + $router->aliasMiddleware('feature.enabled', RequireEnabledFeature::class); + $router->aliasMiddleware('feature.disabled', RequireDisabledFeature::class); + } +} 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/tests/ExampleTest.php b/tests/ExampleTest.php deleted file mode 100644 index 5d36321..0000000 --- a/tests/ExampleTest.php +++ /dev/null @@ -1,5 +0,0 @@ -toBeTrue(); -}); diff --git a/tests/Pest.php b/tests/Pest.php index 7fe1500..be8b029 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,5 @@ in(__DIR__); diff --git a/tests/SimpleFeatureTest.php b/tests/SimpleFeatureTest.php new file mode 100644 index 0000000..f3bba68 --- /dev/null +++ b/tests/SimpleFeatureTest.php @@ -0,0 +1,44 @@ +toBeTrue(); + expect(SimpleFeature::enabled('exampleDisabled'))->toBeFalse(); +}); + +it('indicates a feature is disabled', function () { + expect(SimpleFeature::disabled('exampleEnabled'))->toBeFalse(); + expect(SimpleFeature::disabled('exampleDisabled'))->toBeTrue(); +}); + +it('falls back to the given default', function () { + expect(SimpleFeature::enabled('doesNotExist', true))->toBeTrue(); + expect(SimpleFeature::enabled('doesNotExist', false))->toBeFalse(); + + expect(SimpleFeature::disabled('doesNotExist', true))->toBeTrue(); + expect(SimpleFeature::disabled('doesNotExist', false))->toBeFalse(); +}); + +it('falls back to the standard default', function () { + expect(SimpleFeature::enabled('doesNotExist'))->toBeFalse(); + expect(SimpleFeature::disabled('doesNotExist'))->toBeTrue(); +}); + +it('ignores the default when the flag is provided', function () { + expect(SimpleFeature::enabled('exampleEnabled', false))->toBeTrue(); + expect(SimpleFeature::enabled('exampleDisabled', true))->toBeFalse(); + + expect(SimpleFeature::disabled('exampleDisabled', false))->toBeTrue(); + expect(SimpleFeature::disabled('exampleEnabled', true))->toBeFalse(); +}); + +it('indicates all features are enabled', function () { + expect(SimpleFeature::allEnabled(['exampleEnabled']))->toBeTrue(); + expect(SimpleFeature::allEnabled(['exampleEnabled', 'exampleDisabled']))->toBeFalse(); +}); + +it('indicates all feature are disabled', function () { + expect(SimpleFeature::allDisabled(['exampleDisabled']))->toBeTrue(); + expect(SimpleFeature::allDisabled(['exampleDisabled', 'exampleEnabled']))->toBeFalse(); +}); diff --git a/tests/TestCase.php b/tests/TestCase.php index d04fb0c..9f022e8 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,36 +1,17 @@ 'VendorName\\Skeleton\\Database\\Factories\\'.class_basename($modelName).'Factory' - ); - } - protected function getPackageProviders($app) { return [ - SkeletonServiceProvider::class, + SimpleFeatureServiceProvider::class, ]; } - - public function getEnvironmentSetUp($app) - { - config()->set('database.default', 'testing'); - - /* - $migration = include __DIR__.'/../database/migrations/create_skeleton_table.php.stub'; - $migration->up(); - */ - } }