diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..a7c44dd --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +indent_size = 4 +indent_style = space +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..9e9519b --- /dev/null +++ b/.gitattributes @@ -0,0 +1,19 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore all test and documentation with "export-ignore". +/.github export-ignore +/.gitattributes export-ignore +/.gitignore export-ignore +/phpunit.xml.dist export-ignore +/art export-ignore +/docs export-ignore +/tests export-ignore +/.editorconfig export-ignore +/.php_cs.dist.php export-ignore +/psalm.xml export-ignore +/psalm.xml.dist export-ignore +/testbench.yaml export-ignore +/UPGRADING.md export-ignore +/phpstan.neon.dist export-ignore +/phpstan-baseline.neon export-ignore diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 0000000..fe4cfe6 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,66 @@ +name: Bug Report +description: Report an Issue or Bug with the Package +title: "[Bug]: " +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + We're sorry to hear you have a problem. Can you help us solve it by providing the following details. + - type: textarea + id: what-happened + attributes: + label: What happened? + description: What did you expect to happen? + placeholder: I cannot currently do X thing because when I do, it breaks X thing. + validations: + required: true + - type: textarea + id: how-to-reproduce + attributes: + label: How to reproduce the bug + description: How did this occur, please add any config values used and provide a set of reliable steps if possible. + placeholder: When I do X I see Y. + validations: + required: true + - type: input + id: package-version + attributes: + label: Package Version + description: What version of our Package are you running? Please be as specific as possible + placeholder: 2.0.0 + validations: + required: true + - type: input + id: php-version + attributes: + label: PHP Version + description: What version of PHP are you running? Please be as specific as possible + placeholder: 8.2.0 + validations: + required: true + - type: input + id: laravel-version + attributes: + label: Laravel Version + description: What version of Laravel are you running? Please be as specific as possible + placeholder: 9.0.0 + validations: + required: true + - type: dropdown + id: operating-systems + attributes: + label: Which operating systems does with happen with? + description: You may select more than one. + multiple: true + options: + - macOS + - Windows + - Linux + - type: textarea + id: notes + attributes: + label: Notes + description: Use this field to provide any other notes that you feel might be relevant to the issue. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..66eba36 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: false +contact_links: + - name: Ask a question + url: https://github.com/flavorly/larave-helpers/discussions/new?category=q-a + about: Ask the community for help + - name: Request a feature + url: https://github.com/flavorly/larave-helpers/discussions/new?category=ideas + about: Share ideas for new features + - name: Report a security issue + url: https://github.com/flavorly/larave-helpers/security/policy + about: Learn how to notify us for sensitive bugs diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..30c8a49 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +# Please see the documentation for all configuration options: +# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates + +version: 2 +updates: + + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly" + labels: + - "dependencies" \ No newline at end of file diff --git a/.github/workflows/changelog.yml b/.github/workflows/changelog.yml new file mode 100644 index 0000000..752048b --- /dev/null +++ b/.github/workflows/changelog.yml @@ -0,0 +1,31 @@ +name: 📠 Flow Update Changelog + +on: + release: + types: [released] + +permissions: + contents: write + +jobs: + update: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + ref: main + + - name: Update Changelog + uses: stefanzweifel/changelog-updater-action@v1 + with: + latest-version: ${{ github.event.release.name }} + release-notes: ${{ github.event.release.body }} + + - name: Commit updated CHANGELOG + uses: stefanzweifel/git-auto-commit-action@v5 + with: + branch: main + commit_message: Update CHANGELOG + file_pattern: CHANGELOG.md diff --git a/.github/workflows/depbot-merge.yml b/.github/workflows/depbot-merge.yml new file mode 100644 index 0000000..e91a568 --- /dev/null +++ b/.github/workflows/depbot-merge.yml @@ -0,0 +1,32 @@ +name: 🤖 Flow Auto Merge Dependabot PRs +on: pull_request_target + +permissions: + pull-requests: write + contents: write + +jobs: + dependabot: + runs-on: ubuntu-latest + if: ${{ github.actor == 'dependabot[bot]' }} + steps: + + - name: Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@v2.1.0 + with: + github-token: "${{ secrets.GITHUB_TOKEN }}" + + - name: Auto-merge Dependabot PRs for semver-minor updates + if: ${{steps.metadata.outputs.update-type == 'version-update:semver-minor'}} + run: gh pr merge --auto --merge "$PR_URL" + env: + PR_URL: ${{github.event.pull_request.html_url}} + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} + + - name: Auto-merge Dependabot PRs for semver-patch updates + if: ${{steps.metadata.outputs.update-type == 'version-update:semver-patch'}} + run: gh pr merge --auto --merge "$PR_URL" + env: + PR_URL: ${{github.event.pull_request.html_url}} + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} diff --git a/.github/workflows/larastan.yml b/.github/workflows/larastan.yml new file mode 100644 index 0000000..d131a1a --- /dev/null +++ b/.github/workflows/larastan.yml @@ -0,0 +1,25 @@ +name: 🚨Flow PHPStan + +on: + push: + branches: + - main + +jobs: + phpstan: + name: phpstan + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + coverage: none + + - name: Install composer dependencies + uses: ramsey/composer-install@v3 + + - name: Run PHPStan + run: ./vendor/bin/phpstan --error-format=github diff --git a/.github/workflows/pest.yml b/.github/workflows/pest.yml new file mode 100644 index 0000000..d8301e6 --- /dev/null +++ b/.github/workflows/pest.yml @@ -0,0 +1,55 @@ +name: 🚥 Flow Pest + +on: + push: + branches: + - main +jobs: + ci: + runs-on: ubuntu-latest + services: + redis: + image: redis + ports: + - 6379:6379 + strategy: + fail-fast: true + matrix: + php: [8.3] + laravel: [11.*] + include: + - laravel: 11.* + testbench: 9.* + + name: Tests + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Cache Dependencies + uses: actions/cache@v4 + with: + path: ~/.composer/cache/files + key: dependencies-php-composer-${{ hashFiles('composer.lock') }} + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo + tools: composer:v2 + coverage: xdebug + + - name: Setup Problem Matches + run: | + echo "::add-matcher::${{ runner.tool_cache }}/php.json" + echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" + + - name: Install dependencies + run: | + composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update --dev + composer update --${{ matrix.stability }} --prefer-dist --no-interaction + + - name: Tests + run: vendor/bin/pest diff --git a/.github/workflows/pint.yml b/.github/workflows/pint.yml new file mode 100644 index 0000000..569aed9 --- /dev/null +++ b/.github/workflows/pint.yml @@ -0,0 +1,29 @@ +name: 🖌️ Flow Pint + +on: + push: + branches: + - main + paths: + - '**.php' + +permissions: + contents: write + +jobs: + php-code-styling: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + ref: ${{ github.head_ref }} + + - name: Fix PHP code style issues + uses: aglipanci/laravel-pint-action@2.4 + + - name: Commit changes + uses: stefanzweifel/git-auto-commit-action@v5 + with: + commit_message: Fix styling diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..9791210 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,36 @@ +name: 🏆 Flow Release + +on: + push: + branches: + - main + +permissions: + contents: write + issues: write + +jobs: + release: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Bump version and push tag + id: bump_version + uses: mathieudutour/github-tag-action@v6.2 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + default_bump: patch + release_branches: main + create_annotated_tag: true + + - name: Create Release + uses: softprops/action-gh-release@v2 + with: + tag_name: ${{ steps.bump_version.outputs.new_tag }} + name: Release ${{ steps.bump_version.outputs.new_tag }} + draft: false + prerelease: false + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..66ee14f --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +.idea +.php_cs +.php_cs.cache +.phpunit.result.cache +build +coverage +docs +phpunit.xml +testbench.yaml +vendor +node_modules +.php-cs-fixer.cache diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..f597aae --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +All notable changes to `laravel-flows` will be documented in this file. diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..c73c44b --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Flavorly + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..c3ecd51 --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +# Laravel Flows ⚡ + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/flavorly/laravel-flows.svg?style=flat-square)](https://packagist.org/packages/flavorly/laravel-flows) +[![GitHub Tests Action Status](https://img.shields.io/github/workflow/status/flavorly/laravel-flows/run-tests?label=tests)](https://github.com/flavorly/laravel-flows/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/workflow/status/flavorly/laravel-flows/Check%20&%20fix%20styling?label=code%20style)](https://github.com/flavorly/laravel-flows/actions?query=workflow%3A"Check+%26+fix+styling"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/flavorly/laravel-flows.svg?style=flat-square)](https://packagist.org/packages/flavorly/laravel-flows) + +A simple package to manage flows in your Laravel application. +This package aims to provider a "ticketing" system to manage the flow of a certain Model + +So lets say you have orders, but a order can be retried many times, but you want to know exactly +what happened on that "flow" of the order, so you can use this package to manage that +The flow also aims to store some additional context if requires, so you can store the request payload, the response payload, the error message, etc + + +## Installation + +You can install the package via composer: + +```bash +composer require flavorly/laravel-flows +``` + +You can publish the config file with: + +```bash +php artisan vendor:publish --tag="laravel-flows-config" +``` + +## Testing + +```bash +composer test +``` + +## Security Vulnerabilities + +Please review [our security policy](../../security/policy) on how to report security vulnerabilities. + +## Credits + +- [jon](https://github.com/flavorly) +- [All Contributors](../../contributors) + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..5d67d7d --- /dev/null +++ b/composer.json @@ -0,0 +1,75 @@ +{ + "name": "flavorly/laravel-flows", + "description": "A tool of tiny but useful Laravel Helpers that we use across our projects", + "keywords": [ + "flavorly", + "laravel", + "laravel helpers" + ], + "homepage": "https://github.com/flavorly/laravel-flows", + "license": "MIT", + "authors": [ + { + "name": "jon", + "email": "support@indigit.pt", + "role": "Developer" + } + ], + "require": { + "php": "^8.3", + "laravel/framework": "^v11.0.0", + "illuminate/contracts": "^11.8.0", + "spatie/laravel-data": "^4.5", + "spatie/laravel-typescript-transformer": "^2.4", + "spatie/laravel-package-tools": "^1.16", + "league/iso3166": "^4.3" + }, + "require-dev": { + "larastan/larastan": "^v2.9.6", + "laravel/pint": "^1.15", + "nunomaduro/collision": "^v8.1.1", + "orchestra/testbench": "^9.1.0", + "pestphp/pest": "^2.34", + "pestphp/pest-plugin-arch": "^2.7", + "pestphp/pest-plugin-laravel": "^2.4", + "spatie/laravel-ray": "^1.36", + "inertiajs-revamped/laravel": "^0.0.4", + "brick/math": "^0.12.1", + "brick/money": "^0.9.0" + }, + "autoload": { + "psr-4": { + "Flavorly\\LaravelFlows\\": "src" + }, + "files": [ + "src/Helpers/generic.php" + ] + }, + "autoload-dev": { + "psr-4": { + "Flavorly\\LaravelFlows\\Tests\\": "tests" + } + }, + "scripts": { + "format": "vendor/bin/pint", + "analyse": "vendor/bin/phpstan analyse", + "test": "vendor/bin/pest", + "test-coverage": "vendor/bin/pest --coverage" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true, + "phpstan/extension-installer": true + } + }, + "extra": { + "laravel": { + "providers": [ + "LaravelFlowsServiceProvider" + ] + } + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/config/helpers.php b/config/helpers.php new file mode 100644 index 0000000..382cf51 --- /dev/null +++ b/config/helpers.php @@ -0,0 +1,12 @@ + + + + + tests + + + + + ./src + + + + + + + + + + + diff --git a/src/Casts/FlowContextCast.php b/src/Casts/FlowContextCast.php new file mode 100644 index 0000000..1402f85 --- /dev/null +++ b/src/Casts/FlowContextCast.php @@ -0,0 +1,85 @@ + + */ +final class FlowContextCast implements CastsAttributes +{ + /** + * This is important so the user can save as a collection but if instantly called again it will be the actual object + */ + public bool $withoutObjectCaching = true; + + /** + * Cast the given value. + * + * @param array $attributes + * @return Collection|Data + */ + public function get(Model $model, string $key, mixed $value, array $attributes): Collection|Data + { + if (! $model instanceof Flow) { + return $value; + } + + $contextClass = FlowContext::resolve($model->flowable_type); + + if ($value instanceof $contextClass) { + // @phpstan-ignore-next-line + return $value; + } + + $decodedValue = json_decode($value, true); + + if ($contextClass && is_subclass_of($contextClass, Data::class)) { + if (empty($decodedValue)) { + return $contextClass::from([]); + } + + if (method_exists($contextClass, 'fromFlowRaw')) { + return $contextClass::fromFlowRaw($decodedValue); + } + + try { + return $contextClass::from($decodedValue); + } catch (\Throwable $e) { + ray('Error in FlowContextCast', $decodedValue); + } + + } + + /** @var Collection $collect */ + $collect = collect($decodedValue); + + return $collect; + } + + /** + * Prepare the given value for storage. + * + * @param array $attributes + */ + public function set(Model $model, string $key, mixed $value, array $attributes): ?string + { + if (! $model instanceof Flow) { + return $value; + } + + $return = json_encode($value); + if ($return === false) { + return $value; + } + + return $return; + } +} diff --git a/src/Concerns/Flowable.php b/src/Concerns/Flowable.php new file mode 100644 index 0000000..5d31b9a --- /dev/null +++ b/src/Concerns/Flowable.php @@ -0,0 +1,34 @@ + + */ + public function flows(): MorphMany + { + return $this->morphMany(Flow::class, 'flowable'); + } + + /** + * Returns the Latest flow + * + * @return MorphOne + */ + public function flow(): MorphOne + { + return $this + ->morphOne(Flow::class, 'flowable') + ->latestOfMany() + ->where('status', FlowStatusEnum::active->value); + } +} diff --git a/src/Enums/FlowStatusEnum.php b/src/Enums/FlowStatusEnum.php new file mode 100644 index 0000000..463cb21 --- /dev/null +++ b/src/Enums/FlowStatusEnum.php @@ -0,0 +1,13 @@ + + */ + protected Collection $registry; + + public function __construct() + { + $this->registry = collect(); + } + + /** + * @param array $mappings + */ + public function register(array $mappings): void + { + $this->registry = $this->registry->merge($mappings); + } + + public function resolve(string $morphType): ?string + { + $class = collect(Relation::$morphMap)->get($morphType) ?? collect(Relation::$morphMap)->flip()->get($morphType); + + return $this->registry->get($class); + } + + /** + * @return Collection + */ + public function registry(): Collection + { + return $this->registry; + } +} diff --git a/src/LaravelFlowsServiceProvider.php b/src/LaravelFlowsServiceProvider.php new file mode 100644 index 0000000..3a10540 --- /dev/null +++ b/src/LaravelFlowsServiceProvider.php @@ -0,0 +1,28 @@ +name('laravel-flows') + ->hasConfigFile(); + } + + public function bootingPackage(): void + { + // Booting the package + } + + public function registeringPackage(): void + { + $this->app->singleton('flow-context-map', function ($app) { + return new FlowContextMap(); + }); + } +} diff --git a/src/Models/Flow.php b/src/Models/Flow.php new file mode 100644 index 0000000..a1a382c --- /dev/null +++ b/src/Models/Flow.php @@ -0,0 +1,60 @@ + + */ + protected function casts(): array + { + return [ + 'status' => FlowStatusEnum::class, + 'context' => FlowContextCast::class, + ]; + } + + /** + * Returns the related flowable model + * + * @return MorphTo + */ + public function flowable(): MorphTo + { + return $this->morphTo(); + } + + /** + * Discard a flow + */ + public function discard(): Flow + { + $this->updateQuietly(['status' => FlowStatusEnum::discarded]); + + return $this; + } + + /** + * Clone the current flow and discards the current one + */ + public function renew(): Flow + { + $this->discard(); + $flow = $this->replicate(['uuid']); + $flow->status = FlowStatusEnum::active; + $flow->save(); + + return $flow; + } +} diff --git a/tests/ExampleTest.php b/tests/ExampleTest.php new file mode 100644 index 0000000..5d36321 --- /dev/null +++ b/tests/ExampleTest.php @@ -0,0 +1,5 @@ +toBeTrue(); +}); diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..1e4b7ff --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,5 @@ +in(__DIR__); diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..dbccaf2 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,31 @@ + 'Flavorly\\LaravelHelpers\\Database\\Factories\\'.class_basename($modelName).'Factory' + ); + } + + protected function getPackageProviders($app) + { + return [ + LaravelFlowsServiceProvider::class, + ]; + } + + public function getEnvironmentSetUp($app) + { + config()->set('database.default', 'testing'); + } +}