diff --git a/.github/workflows/monorepo-split.yml b/.github/workflows/monorepo-split.yml index 0f38e847..85860e47 100644 --- a/.github/workflows/monorepo-split.yml +++ b/.github/workflows/monorepo-split.yml @@ -16,6 +16,8 @@ jobs: - announcements - core - laravel-translations + - redirects + - laravel-redirects steps: - uses: actions/checkout@v3 - id: previous-tag diff --git a/.github/workflows/setup-in-laravel.yml b/.github/workflows/setup-in-laravel.yml index 34bdf068..26c715c0 100644 --- a/.github/workflows/setup-in-laravel.yml +++ b/.github/workflows/setup-in-laravel.yml @@ -59,5 +59,6 @@ jobs: run: | cd theater composer config minimum-stability dev + composer config repositories.cms vcs git@github.com:backstagephp/cms.git composer require backstage/cms:dev-${{ steps.extract_branch.outputs.branch }} php artisan backstage:install diff --git a/packages/laravel-redirects/.editorconfig b/packages/laravel-redirects/.editorconfig new file mode 100644 index 00000000..dd9a2b51 --- /dev/null +++ b/packages/laravel-redirects/.editorconfig @@ -0,0 +1,15 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true + +[*.md] +trim_trailing_whitespace = false + +[*.{yml,yaml}] +indent_size = 2 diff --git a/packages/laravel-redirects/.gitattributes b/packages/laravel-redirects/.gitattributes new file mode 100644 index 00000000..c09f81e5 --- /dev/null +++ b/packages/laravel-redirects/.gitattributes @@ -0,0 +1,20 @@ +# 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 +/workbench 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/packages/laravel-redirects/.github/FUNDING.yml b/packages/laravel-redirects/.github/FUNDING.yml new file mode 100644 index 00000000..757a8a4c --- /dev/null +++ b/packages/laravel-redirects/.github/FUNDING.yml @@ -0,0 +1 @@ +github: backstagephp diff --git a/packages/laravel-redirects/.github/ISSUE_TEMPLATE/bug.yml b/packages/laravel-redirects/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 00000000..fe4cfe6d --- /dev/null +++ b/packages/laravel-redirects/.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/packages/laravel-redirects/.github/ISSUE_TEMPLATE/config.yml b/packages/laravel-redirects/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..742b0a9e --- /dev/null +++ b/packages/laravel-redirects/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: false +contact_links: + - name: Ask a question + url: https://github.com/backstagephp/laravel-redirects/discussions/new?category=q-a + about: Ask the community for help + - name: Request a feature + url: https://github.com/backstagephp/laravel-redirects/discussions/new?category=ideas + about: Share ideas for new features + - name: Report a security issue + url: https://github.com/backstagephp/laravel-redirects/security/policy + about: Learn how to notify us for sensitive bugs diff --git a/packages/laravel-redirects/.github/dependabot.yml b/packages/laravel-redirects/.github/dependabot.yml new file mode 100644 index 00000000..39b15807 --- /dev/null +++ b/packages/laravel-redirects/.github/dependabot.yml @@ -0,0 +1,19 @@ +# 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" + + - package-ecosystem: "composer" + directory: "/" + schedule: + interval: "weekly" + labels: + - "dependencies" diff --git a/packages/laravel-redirects/.github/workflows/dependabot-auto-merge.yml b/packages/laravel-redirects/.github/workflows/dependabot-auto-merge.yml new file mode 100644 index 00000000..cc8c94cf --- /dev/null +++ b/packages/laravel-redirects/.github/workflows/dependabot-auto-merge.yml @@ -0,0 +1,33 @@ +name: dependabot-auto-merge +on: pull_request_target + +permissions: + pull-requests: write + contents: write + +jobs: + dependabot: + runs-on: ubuntu-latest + timeout-minutes: 5 + if: ${{ github.actor == 'dependabot[bot]' }} + steps: + + - name: Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@v2.4.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/packages/laravel-redirects/.github/workflows/fix-php-code-style-issues.yml b/packages/laravel-redirects/.github/workflows/fix-php-code-style-issues.yml new file mode 100644 index 00000000..1eed95a3 --- /dev/null +++ b/packages/laravel-redirects/.github/workflows/fix-php-code-style-issues.yml @@ -0,0 +1,28 @@ +name: Fix PHP code style issues + +on: + push: + paths: + - '**.php' + +permissions: + contents: write + +jobs: + php-code-styling: + runs-on: ubuntu-latest + timeout-minutes: 5 + + 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.6 + + - name: Commit changes + uses: stefanzweifel/git-auto-commit-action@v5 + with: + commit_message: Fix styling diff --git a/packages/laravel-redirects/.github/workflows/phpstan.yml b/packages/laravel-redirects/.github/workflows/phpstan.yml new file mode 100644 index 00000000..d5db2f14 --- /dev/null +++ b/packages/laravel-redirects/.github/workflows/phpstan.yml @@ -0,0 +1,28 @@ +name: PHPStan + +on: + push: + paths: + - '**.php' + - 'phpstan.neon.dist' + - '.github/workflows/phpstan.yml' + +jobs: + phpstan: + name: phpstan + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + coverage: none + + - name: Install composer dependencies + uses: ramsey/composer-install@v3 + + - name: Run PHPStan + run: ./vendor/bin/phpstan --error-format=github diff --git a/packages/laravel-redirects/.github/workflows/run-tests.yml b/packages/laravel-redirects/.github/workflows/run-tests.yml new file mode 100644 index 00000000..c1fc1958 --- /dev/null +++ b/packages/laravel-redirects/.github/workflows/run-tests.yml @@ -0,0 +1,58 @@ +name: run-tests + +on: + push: + paths: + - '**.php' + - '.github/workflows/run-tests.yml' + - 'phpunit.xml.dist' + - 'composer.json' + - 'composer.lock' + +jobs: + test: + runs-on: ${{ matrix.os }} + timeout-minutes: 5 + strategy: + fail-fast: true + matrix: + os: [ubuntu-latest, windows-latest] + php: [8.3, 8.2] + laravel: [11.*, 10.*] + stability: [prefer-lowest, prefer-stable] + include: + - laravel: 11.* + testbench: 9.* + carbon: ^2.63 + - laravel: 10.* + testbench: 8.* + carbon: ^2.63 + + name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} - ${{ matrix.os }} + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - 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 + coverage: none + + - name: Setup problem matchers + 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 }}" "nesbot/carbon:${{ matrix.os == 'windows-latest' && '^^^' || '' }}${{ matrix.carbon }}" --no-interaction --no-update + composer update --${{ matrix.stability }} --prefer-dist --no-interaction + + - name: List Installed Dependencies + run: composer show -D + + - name: Execute tests + run: vendor/bin/pest --ci diff --git a/packages/laravel-redirects/.github/workflows/update-changelog.yml b/packages/laravel-redirects/.github/workflows/update-changelog.yml new file mode 100644 index 00000000..39de30d6 --- /dev/null +++ b/packages/laravel-redirects/.github/workflows/update-changelog.yml @@ -0,0 +1,32 @@ +name: "Update Changelog" + +on: + release: + types: [released] + +permissions: + contents: write + +jobs: + update: + runs-on: ubuntu-latest + timeout-minutes: 5 + + 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/packages/laravel-redirects/.gitignore b/packages/laravel-redirects/.gitignore new file mode 100644 index 00000000..b60507fb --- /dev/null +++ b/packages/laravel-redirects/.gitignore @@ -0,0 +1,32 @@ +# Composer Related +composer.lock +/vendor + +# Frontend Assets +/node_modules + +# Logs +npm-debug.log +yarn-error.log + +# Caches +.phpunit.cache +.phpunit.result.cache +/build + +# IDE Helper +_ide_helper.php +_ide_helper_models.php +.phpstorm.meta.php + +# Editors +/.idea +/.fleet +/.vscode + +# Misc +phpunit.xml +phpstan.neon +testbench.yaml +/docs +/coverage diff --git a/packages/laravel-redirects/CHANGELOG.md b/packages/laravel-redirects/CHANGELOG.md new file mode 100644 index 00000000..8a04e551 --- /dev/null +++ b/packages/laravel-redirects/CHANGELOG.md @@ -0,0 +1,3 @@ +# Changelog + +All notable changes to `laravel-redirects` will be documented in this file. diff --git a/packages/laravel-redirects/LICENSE.md b/packages/laravel-redirects/LICENSE.md new file mode 100644 index 00000000..2d69e769 --- /dev/null +++ b/packages/laravel-redirects/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Backstage + +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/packages/laravel-redirects/README.md b/packages/laravel-redirects/README.md new file mode 100644 index 00000000..aa31ed7c --- /dev/null +++ b/packages/laravel-redirects/README.md @@ -0,0 +1,77 @@ +# Laravel Redirects + +## Add redirects to your Laravel app using a database, so you can dynamically manage it without writing code. + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/backstage/laravel-redirects.svg?style=flat-square)](https://packagist.org/packages/backstage/laravel-redirects) +[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/backstagephp/laravel-redirects/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/backstagephp/laravel-redirects/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/backstagephp/laravel-redirects/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/backstagephp/laravel-redirects/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/backstage/laravel-redirects.svg?style=flat-square)](https://packagist.org/packages/backstage/laravel-redirects) + +This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. + +## Installation + +You can install the package via composer: + +```bash +composer require backstage/laravel-redirects +``` + +You can publish and run the migrations with: + +```bash +php artisan vendor:publish --tag="laravel-redirects-migrations" +php artisan migrate +``` + +You can publish the config file with: + +```bash +php artisan vendor:publish --tag="laravel-redirects-config" +``` + +This is the contents of the published config file: + +```php +return [ +]; +``` + +Optionally, you can publish the views using + +```bash +php artisan vendor:publish --tag="laravel-redirects-views" +``` + +## Usage + +```php +... +``` + +## Testing + +```bash +composer test +``` + +## Changelog + +Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. + +## Contributing + +Please see [CONTRIBUTING](CONTRIBUTING.md) for details. + +## Security Vulnerabilities + +Please review [our security policy](../../security/policy) on how to report security vulnerabilities. + +## Credits + +- [Mark van Eijk](https://github.com/markvaneijk) +- [All Contributors](../../contributors) + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. diff --git a/packages/laravel-redirects/composer.json b/packages/laravel-redirects/composer.json new file mode 100644 index 00000000..c586e19a --- /dev/null +++ b/packages/laravel-redirects/composer.json @@ -0,0 +1,84 @@ +{ + "name": "backstage/laravel-redirects", + "description": "Add redirects to your Laravel app using a database, so you can dynamically manage it without writing code.", + "keywords": [ + "backstage", + "vormkracht10", + "laravel", + "php", + "redirects" + ], + "homepage": "https://github.com/backstagephp/laravel-redirects", + "license": "MIT", + "authors": [ + { + "name": "Mark van Eijk", + "email": "mark@backstagephp.com", + "role": "Developer" + } + ], + "require": { + "php": "^8.2", + "backstage/laravel-trailing-slash": "^0.1.0", + "illuminate/contracts": "^10.0 || ^11.0 || ^12.0", + "spatie/laravel-package-tools": "^1.16" + }, + "require-dev": { + "laravel/pint": "^1.14", + "nunomaduro/collision": "^8.1.1 || ^7.10.0", + "larastan/larastan": "^2.9", + "orchestra/testbench": "^9.0.0 || ^8.22.0", + "pestphp/pest": "^2.34", + "pestphp/pest-plugin-arch": "^2.7", + "pestphp/pest-plugin-laravel": "^2.3", + "phpstan/extension-installer": "^1.3", + "phpstan/phpstan-deprecation-rules": "^1.1", + "phpstan/phpstan-phpunit": "^1.3" + }, + "autoload": { + "psr-4": { + "Backstage\\Redirects\\Laravel\\": "src/", + "Backstage\\Redirects\\Laravel\\Database\\Factories\\": "database/factories/" + } + }, + "autoload-dev": { + "psr-4": { + "Backstage\\Redirects\\Laravel\\Tests\\": "tests/", + "Workbench\\App\\": "workbench/app/" + } + }, + "scripts": { + "post-autoload-dump": "@composer run prepare", + "clear": "@php vendor/bin/testbench package:purge-laravel-redirects --ansi", + "prepare": "@php vendor/bin/testbench package:discover --ansi", + "build": [ + "@composer run prepare", + "@php vendor/bin/testbench workbench:build --ansi" + ], + "start": [ + "Composer\\Config::disableProcessTimeout", + "@composer run build", + "@php vendor/bin/testbench serve" + ], + "analyse": "vendor/bin/phpstan analyse", + "test": "vendor/bin/pest", + "test-coverage": "vendor/bin/pest --coverage", + "format": "vendor/bin/pint" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true, + "phpstan/extension-installer": true + } + }, + "extra": { + "laravel": { + "providers": [ + "Backstage\\Redirects\\Laravel\\RedirectServiceProvider" + ] + } + }, + "minimum-stability": "dev", + "prefer-stable": true +} diff --git a/packages/laravel-redirects/config/redirects.php b/packages/laravel-redirects/config/redirects.php new file mode 100644 index 00000000..d1b6e4be --- /dev/null +++ b/packages/laravel-redirects/config/redirects.php @@ -0,0 +1,59 @@ + [ + // 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + // 303 => 'See Other', + // 304 => 'Not Modified', + // 305 => 'Use Proxy', + // 306 => 'Unused', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', + ], + + /* + * Define the model you want to use for Redirects. + */ + 'model' => Backstage\Redirects\Laravel\Models\Redirect::class, + + /* + * The default status code to select when redirecting. + */ + 'default_status_code' => env('REDIRECT_DEFAULT_STATUS_CODE', 301), + + /* + * If the case is sensitive, the following routes will be treated as different: + * + * /example + * /Example + */ + 'case_sensitive' => env('REDIRECT_CASE_SENSITIVE', false), + + /* + * If the trailing slash is sensitive, the following routes will be treated as different: + * + * /example + * /example/ + */ + 'trailing_slash_sensitive' => env('REDIRECT_TRAILING_SLASH_SENSITIVE', false), + + /* + * Always add a trailing slash for redirect endpoint to maintain consistency in used URLs for SEO. + */ + 'trailing_slash' => env('REDIRECT_WITH_TRAILING_SLASH', false), + + /** + * The middleware to use for redirecting. + * If you ad \Backstage\Redirects\Laravel\Http\Middleware\BackstageRedirects, the request will be looped endlessly. + */ + 'middleware' => [ + Backstage\Redirects\Laravel\Http\Middleware\HttpRedirects::class, + Backstage\Redirects\Laravel\Http\Middleware\WildRedirects::class, + Backstage\Redirects\Laravel\Http\Middleware\StrictRedirects::class, + ], +]; diff --git a/packages/laravel-redirects/database/factories/ModelFactory.php b/packages/laravel-redirects/database/factories/ModelFactory.php new file mode 100644 index 00000000..54577120 --- /dev/null +++ b/packages/laravel-redirects/database/factories/ModelFactory.php @@ -0,0 +1,19 @@ +ulid()->primary(); + $table->string('source'); + $table->string('destination')->nullable(); + $table->unsignedInteger('code', 3)->default(301)->autoIncrement(false); + $table->unsignedBigInteger('hits')->default(0); + $table->timestamps(); + }); + } +}; diff --git a/packages/laravel-redirects/phpstan-baseline.neon b/packages/laravel-redirects/phpstan-baseline.neon new file mode 100644 index 00000000..e69de29b diff --git a/packages/laravel-redirects/phpstan.neon.dist b/packages/laravel-redirects/phpstan.neon.dist new file mode 100644 index 00000000..ab1b4c30 --- /dev/null +++ b/packages/laravel-redirects/phpstan.neon.dist @@ -0,0 +1,12 @@ +includes: + - phpstan-baseline.neon + +parameters: + level: 5 + paths: + - src + - config + - database + tmpDir: build/phpstan + checkOctaneCompatibility: true + checkModelProperties: true diff --git a/packages/laravel-redirects/phpunit.xml.dist b/packages/laravel-redirects/phpunit.xml.dist new file mode 100644 index 00000000..80dc22aa --- /dev/null +++ b/packages/laravel-redirects/phpunit.xml.dist @@ -0,0 +1,31 @@ + + + + + tests + + + + + + + + ./src + + + diff --git a/packages/laravel-redirects/src/Events/UrlHasChanged.php b/packages/laravel-redirects/src/Events/UrlHasChanged.php new file mode 100644 index 00000000..edb3f05f --- /dev/null +++ b/packages/laravel-redirects/src/Events/UrlHasChanged.php @@ -0,0 +1,18 @@ +isMethod('GET') && ! $request->isMethod('HEAD')) { + return $next($request); + } + + return $this->handleNonPost($request, $next); + } + + /** + * Handle non-POST requests. + */ + abstract protected function handleNonPost(Request $request, Closure $next); +} diff --git a/packages/laravel-redirects/src/Http/Middleware/HttpRedirects.php b/packages/laravel-redirects/src/Http/Middleware/HttpRedirects.php new file mode 100644 index 00000000..e6ec2bea --- /dev/null +++ b/packages/laravel-redirects/src/Http/Middleware/HttpRedirects.php @@ -0,0 +1,37 @@ +firstWhere(function (Redirect $redirect) use ($request) { + return str($request->fullUrl()) + ->replace(['http://', 'https://'], '') + ->replace(['www.'], '') + ->contains( + str($redirect->source) + ->replace(['http://', 'https://'], '') + ->replace(['www.'], '') + ); + }); + + if (! $checker) { + return $next($request); + } + + return $checker->redirect($request); + } +} diff --git a/packages/laravel-redirects/src/Http/Middleware/StrictRedirects.php b/packages/laravel-redirects/src/Http/Middleware/StrictRedirects.php new file mode 100644 index 00000000..850becfd --- /dev/null +++ b/packages/laravel-redirects/src/Http/Middleware/StrictRedirects.php @@ -0,0 +1,37 @@ +firstWhere(function (Redirect $redirect) use ($request) { + return str($request->url()) + ->replace(['http://', 'https://'], '') + ->replace(['www.'], '') + ->exactly( + str($redirect->source) + ->replace(['http://', 'https://'], '') + ->replace(['www.'], '') + ); + }); + + if (! $checker) { + return $next($request); + } + + return $checker->redirect($request); + } +} diff --git a/packages/laravel-redirects/src/Http/Middleware/WildRedirects.php b/packages/laravel-redirects/src/Http/Middleware/WildRedirects.php new file mode 100644 index 00000000..7886a5df --- /dev/null +++ b/packages/laravel-redirects/src/Http/Middleware/WildRedirects.php @@ -0,0 +1,30 @@ +firstWhere(function (Redirect $redirect) use ($request) { + return str($request->fullUrl())->contains($redirect->source); + }); + + if (! $checker) { + return $next($request); + } + + return $checker->redirect($request); + } +} diff --git a/packages/laravel-redirects/src/Listeners/RedirectOldUrlToNewUrl.php b/packages/laravel-redirects/src/Listeners/RedirectOldUrlToNewUrl.php new file mode 100644 index 00000000..b1c0bfa9 --- /dev/null +++ b/packages/laravel-redirects/src/Listeners/RedirectOldUrlToNewUrl.php @@ -0,0 +1,18 @@ + $event->oldUrl, + 'destination' => $event->newUrl, + 'code' => $event->code, + ]); + } +} diff --git a/packages/laravel-redirects/src/Models/Redirect.php b/packages/laravel-redirects/src/Models/Redirect.php new file mode 100644 index 00000000..92c2b5c4 --- /dev/null +++ b/packages/laravel-redirects/src/Models/Redirect.php @@ -0,0 +1,38 @@ +increment('hits'); + + $destination = $this->destination; + + if ($request->query()) { + $destination .= (str($destination)->contains('?') ? '&' : '?') . Arr::query($request->query()); + } + + return redirect($destination, $this->code) + ->with('input', $request->input()); + } +} diff --git a/packages/laravel-redirects/src/RedirectServiceProvider.php b/packages/laravel-redirects/src/RedirectServiceProvider.php new file mode 100644 index 00000000..d1df361b --- /dev/null +++ b/packages/laravel-redirects/src/RedirectServiceProvider.php @@ -0,0 +1,35 @@ +name('laravel-redirects') + ->hasConfigFile() + ->hasMigration('create_redirects_table'); + } + + public function packageBooted() + { + /** @var \Illuminate\Routing\Router $router */ + $kernel = $this->app->make(Router::class); + + foreach (config('redirects.middleware') as $middleware) { + $kernel->pushMiddlewareToGroup('web', $middleware); + } + + $this->app['events']->listen( + UrlHasChanged::class, + RedirectOldUrlToNewUrl::class + ); + } +} diff --git a/packages/laravel-redirects/tests/ArchTest.php b/packages/laravel-redirects/tests/ArchTest.php new file mode 100644 index 00000000..87fb64cd --- /dev/null +++ b/packages/laravel-redirects/tests/ArchTest.php @@ -0,0 +1,5 @@ +expect(['dd', 'dump', 'ray']) + ->each->not->toBeUsed(); diff --git a/packages/laravel-redirects/tests/ExampleTest.php b/packages/laravel-redirects/tests/ExampleTest.php new file mode 100644 index 00000000..5d363218 --- /dev/null +++ b/packages/laravel-redirects/tests/ExampleTest.php @@ -0,0 +1,5 @@ +toBeTrue(); +}); diff --git a/packages/laravel-redirects/tests/Pest.php b/packages/laravel-redirects/tests/Pest.php new file mode 100644 index 00000000..af5c89ef --- /dev/null +++ b/packages/laravel-redirects/tests/Pest.php @@ -0,0 +1,5 @@ +in(__DIR__); diff --git a/packages/laravel-redirects/tests/TestCase.php b/packages/laravel-redirects/tests/TestCase.php new file mode 100644 index 00000000..a003ef22 --- /dev/null +++ b/packages/laravel-redirects/tests/TestCase.php @@ -0,0 +1,36 @@ + 'Backstage\\Redirects\\Laravel\\Database\\Factories\\' . class_basename($modelName) . 'Factory' + ); + } + + protected function getPackageProviders($app) + { + return [ + RedirectServiceProvider::class, + ]; + } + + public function getEnvironmentSetUp($app) + { + config()->set('database.default', 'testing'); + + /* + $migration = include __DIR__.'/../database/migrations/create_laravel-redirects_table.php.stub'; + $migration->up(); + */ + } +} diff --git a/packages/laravel-redirects/workbench/app/Providers/WorkbenchServiceProvider.php b/packages/laravel-redirects/workbench/app/Providers/WorkbenchServiceProvider.php new file mode 100644 index 00000000..001d06d7 --- /dev/null +++ b/packages/laravel-redirects/workbench/app/Providers/WorkbenchServiceProvider.php @@ -0,0 +1,25 @@ + + +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/packages/redirects/README.md b/packages/redirects/README.md new file mode 100644 index 00000000..1be6267d --- /dev/null +++ b/packages/redirects/README.md @@ -0,0 +1,77 @@ +# Manage Redirects in your Laravel application through Filament. + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/backstage/filament-redirects.svg?style=flat-square)](https://packagist.org/packages/backstage/filament-redirects) +[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/backstagephp/filament-redirects/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/backstagephp/filament-redirects/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/backstagephp/filament-redirects/fix-php-code-styling.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/backstagephp/filament-redirects/actions?query=workflow%3A"Fix+PHP+code+styling"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/backstage/filament-redirects.svg?style=flat-square)](https://packagist.org/packages/backstage/filament-redirects) + + + +This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. + +## Installation + +You can install the package via composer: + +```bash +composer require backstage/redirects +``` + +You can publish and run the migrations with: + +```bash +php artisan vendor:publish --tag="filament-redirects-migrations" +php artisan migrate +``` + +You can publish the config file with: + +```bash +php artisan vendor:publish --tag="filament-redirects-config" +``` + +Optionally, you can publish the views using + +```bash +php artisan vendor:publish --tag="filament-redirects-views" +``` + +This is the contents of the published config file: + +```php +return [ +]; +``` + +## Usage + +```php +... +``` + +## Testing + +```bash +composer test +``` + +## Changelog + +Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. + +## Contributing + +Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details. + +## Security Vulnerabilities + +Please review [our security policy](../../security/policy) on how to report security vulnerabilities. + +## Credits + +- [Mark van Eijk](https://github.com/markvaneijk) +- [All Contributors](../../contributors) + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. diff --git a/packages/redirects/bin/build.js b/packages/redirects/bin/build.js new file mode 100644 index 00000000..8f7e9478 --- /dev/null +++ b/packages/redirects/bin/build.js @@ -0,0 +1,50 @@ +import esbuild from 'esbuild' + +const isDev = process.argv.includes('--dev') + +async function compile(options) { + const context = await esbuild.context(options) + + if (isDev) { + await context.watch() + } else { + await context.rebuild() + await context.dispose() + } +} + +const defaultOptions = { + define: { + 'process.env.NODE_ENV': isDev ? `'development'` : `'production'`, + }, + bundle: true, + mainFields: ['module', 'main'], + platform: 'neutral', + sourcemap: isDev ? 'inline' : false, + sourcesContent: isDev, + treeShaking: true, + target: ['es2020'], + minify: !isDev, + plugins: [{ + name: 'watchPlugin', + setup: function (build) { + build.onStart(() => { + console.log(`Build started at ${new Date(Date.now()).toLocaleTimeString()}: ${build.initialOptions.outfile}`) + }) + + build.onEnd((result) => { + if (result.errors.length > 0) { + console.log(`Build failed at ${new Date(Date.now()).toLocaleTimeString()}: ${build.initialOptions.outfile}`, result.errors) + } else { + console.log(`Build finished at ${new Date(Date.now()).toLocaleTimeString()}: ${build.initialOptions.outfile}`) + } + }) + } + }], +} + +compile({ + ...defaultOptions, + entryPoints: ['./resources/js/index.js'], + outfile: './resources/dist/filament-redirects.js', +}) diff --git a/packages/redirects/composer.json b/packages/redirects/composer.json new file mode 100644 index 00000000..9bdbb563 --- /dev/null +++ b/packages/redirects/composer.json @@ -0,0 +1,80 @@ +{ + "name": "backstage/redirects", + "description": "Manage Redirects in your Laravel application using Filament.", + "keywords": [ + "backstagephp", + "laravel", + "filament-redirects" + ], + "homepage": "https://github.com/backstagephp/filament-redirects", + "support": { + "issues": "https://github.com/backstagephp/filament-redirects/issues", + "source": "https://github.com/backstagephp/filament-redirects" + }, + "license": "MIT", + "authors": [ + { + "name": "Mark van Eijk", + "email": "mark@backstagephp.com", + "role": "Developer" + } + ], + "require": { + "php": "^8.1", + "filament/filament": "^3.0", + "spatie/laravel-package-tools": "^1.15.0", + "backstage/laravel-redirects": "dev-main" + }, + "require-dev": { + "laravel/pint": "^1.0", + "nunomaduro/collision": "^7.9", + "larastan/larastan": "^2.0.1", + "orchestra/testbench": "^8.0", + "pestphp/pest": "^2.1", + "pestphp/pest-plugin-arch": "^2.0", + "pestphp/pest-plugin-laravel": "^2.0", + "phpstan/extension-installer": "^1.1", + "phpstan/phpstan-deprecation-rules": "^1.0", + "phpstan/phpstan-phpunit": "^1.0" + }, + "autoload": { + "psr-4": { + "Backstage\\Redirects\\Filament\\": "src/", + "Backstage\\Redirects\\Filament\\Database\\Factories\\": "database/factories/" + } + }, + "autoload-dev": { + "psr-4": { + "Backstage\\Redirects\\Filament\\Tests\\": "tests/" + } + }, + "scripts": { + "post-autoload-dump": "@php ./vendor/bin/testbench package:discover --ansi", + "analyse": "vendor/bin/phpstan analyse", + "test": "vendor/bin/pest", + "test-coverage": "vendor/bin/pest --coverage", + "format": "vendor/bin/pint" + }, + "config": { + "sort-packages": true, + "allow-plugins": { + "pestphp/pest-plugin": true, + "phpstan/extension-installer": true + } + }, + "extra": { + "laravel": { + "providers": [ + "Backstage\\Redirects\\Filament\\RedirectServiceProvider" + ] + } + }, + "minimum-stability": "dev", + "prefer-stable": true, + "repositories": { + "laravel-redirects": { + "type": "vcs", + "url": "git@github.com:backstagephp/laravel-redirects.git" + } + } +} diff --git a/packages/redirects/config/backstage/redirects.php b/packages/redirects/config/backstage/redirects.php new file mode 100644 index 00000000..271dd5e0 --- /dev/null +++ b/packages/redirects/config/backstage/redirects.php @@ -0,0 +1,15 @@ + [ + 'parent' => null, + 'group' => null, + 'sort' => 10, + ], + + 'resources' => [ + RedirectResource::class, + ], +]; diff --git a/packages/redirects/package.json b/packages/redirects/package.json new file mode 100644 index 00000000..12f3836f --- /dev/null +++ b/packages/redirects/package.json @@ -0,0 +1,26 @@ +{ + "private": true, + "type": "module", + "scripts": { + "dev:styles": "npx tailwindcss -i resources/css/index.css -o resources/dist/filament-redirects.css --postcss --watch", + "dev:scripts": "node bin/build.js --dev", + "build:styles": "npx tailwindcss -i resources/css/index.css -o resources/dist/filament-redirects.css --postcss --minify && npm run purge", + "build:scripts": "node bin/build.js", + "purge": "filament-purge -i resources/dist/filament-redirects.css -o resources/dist/filament-redirects.css -v 3.x", + "dev": "npm-run-all --parallel dev:*", + "build": "npm-run-all build:*" + }, + "devDependencies": { + "@awcodes/filament-plugin-purge": "^1.1.1", + "@tailwindcss/forms": "^0.5.4", + "@tailwindcss/typography": "^0.5.9", + "autoprefixer": "^10.4.14", + "esbuild": "^0.19.2", + "npm-run-all": "^4.1.5", + "postcss": "^8.4.26", + "postcss-import": "^15.1.0", + "prettier": "^2.7.1", + "prettier-plugin-tailwindcss": "^0.1.13", + "tailwindcss": "^3.3.3" + } +} diff --git a/packages/redirects/phpstan-baseline.neon b/packages/redirects/phpstan-baseline.neon new file mode 100644 index 00000000..e69de29b diff --git a/packages/redirects/phpstan.neon.dist b/packages/redirects/phpstan.neon.dist new file mode 100644 index 00000000..a91953bd --- /dev/null +++ b/packages/redirects/phpstan.neon.dist @@ -0,0 +1,14 @@ +includes: + - phpstan-baseline.neon + +parameters: + level: 4 + paths: + - src + - config + - database + tmpDir: build/phpstan + checkOctaneCompatibility: true + checkModelProperties: true + checkMissingIterableValueType: false + diff --git a/packages/redirects/phpunit.xml.dist b/packages/redirects/phpunit.xml.dist new file mode 100644 index 00000000..ae36eaa3 --- /dev/null +++ b/packages/redirects/phpunit.xml.dist @@ -0,0 +1,38 @@ + + + + + tests + + + + + + + + + + + + + + + ./src + + + diff --git a/packages/redirects/pint.json b/packages/redirects/pint.json new file mode 100644 index 00000000..c6ddb494 --- /dev/null +++ b/packages/redirects/pint.json @@ -0,0 +1,14 @@ +{ + "preset": "laravel", + "rules": { + "blank_line_before_statement": true, + "concat_space": { + "spacing": "one" + }, + "method_argument_space": true, + "single_trait_insert_per_statement": true, + "types_spaces": { + "space": "single" + } + } +} diff --git a/packages/redirects/postcss.config.cjs b/packages/redirects/postcss.config.cjs new file mode 100644 index 00000000..28553945 --- /dev/null +++ b/packages/redirects/postcss.config.cjs @@ -0,0 +1,8 @@ +module.exports = { + plugins: { + "postcss-import": {}, + "tailwindcss/nesting": {}, + tailwindcss: {}, + autoprefixer: {}, + }, +} diff --git a/packages/redirects/resources/css/index.css b/packages/redirects/resources/css/index.css new file mode 100644 index 00000000..b3949d56 --- /dev/null +++ b/packages/redirects/resources/css/index.css @@ -0,0 +1 @@ +@import '../../vendor/filament/filament/resources/css/theme.css'; diff --git a/packages/redirects/resources/dist/.gitkeep b/packages/redirects/resources/dist/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/packages/redirects/resources/js/index.js b/packages/redirects/resources/js/index.js new file mode 100644 index 00000000..e69de29b diff --git a/packages/redirects/resources/lang/en/redirects.php b/packages/redirects/resources/lang/en/redirects.php new file mode 100644 index 00000000..3ac44ad1 --- /dev/null +++ b/packages/redirects/resources/lang/en/redirects.php @@ -0,0 +1,5 @@ +requiredMapping() + ->label(__('Source')) + ->guess(['source']), + ImportColumn::make('destination') + ->requiredMapping() + ->label(__('Destination')) + ->guess(['destination']), + ImportColumn::make('code') + ->requiredMapping() + ->rules(['max:3']) + ->guess(['code', 'status', 'status_code']), + ]; + } + + public function resolveRecord(): ?Redirect + { + if (isset($this->data['source'])) { + return Redirect::firstOrNew([ + 'source' => $this->data['source'], + 'site_id' => Filament::getTenant()->ulid, + ]); + } + } + + public static function getCompletedNotificationBody(Import $import): string + { + $body = __('Your redirects import has completed and :numbers :row imported.', [ + 'numbers' => number_format($import->successful_rows), + 'row' => str('row')->plural($import->successful_rows), + ]); + + if ($failedRowsCount = $import->getFailedRowsCount()) { + $body .= __(':numbers :row failed to import.', [ + 'numbers' => number_format($failedRowsCount), + 'row' => str('row')->plural($failedRowsCount), + ]); + } + + return $body; + } +} diff --git a/packages/redirects/src/RedirectServiceProvider.php b/packages/redirects/src/RedirectServiceProvider.php new file mode 100644 index 00000000..5ad11e28 --- /dev/null +++ b/packages/redirects/src/RedirectServiceProvider.php @@ -0,0 +1,111 @@ +name(static::$name) + ->hasCommands($this->getCommands()) + ->hasInstallCommand(function (InstallCommand $command) { + $command + ->publishConfigFile() + ->askToRunMigrations() + ->askToStarRepoOnGitHub('backstagephp/redirects'); + }); + + $configFileName = $package->shortName(); + + $this->mergeConfigFrom(__DIR__ . '/../config/backstage/redirects.php', 'backstage.redirects'); + + $package->hasConfigFile('backstage/redirects'); + + if (file_exists($package->basePath('/../resources/lang'))) { + $package->hasTranslations(); + } + + if (file_exists($package->basePath('/../resources/views'))) { + $package->hasViews(static::$viewNamespace); + } + } + + public function packageRegistered(): void {} + + public function packageBooted(): void + { + // Asset Registration + FilamentAsset::register( + $this->getAssets(), + $this->getAssetPackageName() + ); + + FilamentAsset::registerScriptData( + $this->getScriptData(), + $this->getAssetPackageName() + ); + + // Icon Registration + FilamentIcon::register($this->getIcons()); + } + + protected function getAssetPackageName(): ?string + { + return 'backstagephp/redirects'; + } + + /** + * @return array + */ + protected function getAssets(): array + { + return [ + // AlpineComponent::make('filament-redirects', __DIR__ . '/../resources/dist/components/filament-redirects.js'), + // Css::make('filament-redirects-styles', __DIR__ . '/../resources/dist/filament-redirects.css'), + // Js::make('filament-redirects-scripts', __DIR__ . '/../resources/dist/filament-redirects.js'), + ]; + } + + /** + * @return array + */ + protected function getCommands(): array + { + return []; + } + + /** + * @return array + */ + protected function getIcons(): array + { + return []; + } + + /** + * @return array + */ + protected function getRoutes(): array + { + return []; + } + + /** + * @return array + */ + protected function getScriptData(): array + { + return []; + } +} diff --git a/packages/redirects/src/RedirectsPlugin.php b/packages/redirects/src/RedirectsPlugin.php new file mode 100644 index 00000000..1160e23e --- /dev/null +++ b/packages/redirects/src/RedirectsPlugin.php @@ -0,0 +1,37 @@ +resources(config('backstage.redirects.resources', [])); + } + + public function boot(Panel $panel): void + { + // + } + + public static function make(): static + { + return app(static::class); + } + + public static function get(): static + { + /** @var static $plugin */ + $plugin = filament(app(static::class)->getId()); + + return $plugin; + } +} diff --git a/packages/redirects/src/Resources/RedirectResource.php b/packages/redirects/src/Resources/RedirectResource.php new file mode 100644 index 00000000..66e12f96 --- /dev/null +++ b/packages/redirects/src/Resources/RedirectResource.php @@ -0,0 +1,152 @@ +schema([ + Tabs::make('Tabs') + ->columnSpanFull() + ->tabs([ + Tab::make('Redirect') + ->schema([ + Select::make('code') + ->label(__('Type')) + ->columnSpanFull() + ->options(collect(config('redirects.status_codes'))->map(fn (string $type, int $code) => $code . ' ' . $type)) + ->searchable() + ->required() + ->default(config('redirects.default_status_code')) + ->prefixIcon('heroicon-o-map-pin') + ->placeholder('HTTP status message'), + TextInput::make('source') + ->label(__('Source')) + ->url() + ->columnSpanFull() + ->required() + ->prefixIcon('heroicon-o-arrow-uturn-right') + ->placeholder(__('Type path, URL or pattern...')) + ->helperText(__('The path to match, you can use regular expressions.')), + TextInput::make('destination') + ->label(__('Destination')) + ->url() + ->columnSpanFull() + ->required() + ->prefixIcon('heroicon-o-arrow-uturn-left') + ->placeholder('Type path or URL...'), + ]), + ]), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->columns([ + TextColumn::make('code') + ->badge() + ->width(0) + ->searchable() + ->sortable() + ->color(fn (string $state): string => match ($state) { + '301' => 'info', + '302' => 'gray', + '307' => 'warning', + '308' => 'info', + }), + TextColumn::make('source') + ->width('50%') + ->searchable() + ->sortable(), + TextColumn::make('hits') + ->searchable() + ->sortable() + ->alignRight() + ->formatStateUsing(fn (string $state): string => $state . ' ×') + ->width(50), + TextColumn::make('destination') + ->width('50%') + ->searchable() + ->sortable(), + ]) + ->filters([ + // + ]) + ->actions([ + Tables\Actions\EditAction::make(), + ]) + ->bulkActions([ + Tables\Actions\BulkActionGroup::make([ + Tables\Actions\DeleteBulkAction::make(), + ]), + ]); + } + + public static function getRelations(): array + { + return [ + // + ]; + } + + public static function getPages(): array + { + return [ + 'index' => Pages\ListRedirects::route('/'), + 'create' => Pages\CreateRedirect::route('/create'), + 'edit' => Pages\EditRedirect::route('/{record}/edit'), + ]; + } +} diff --git a/packages/redirects/src/Resources/RedirectResource/Pages/CreateRedirect.php b/packages/redirects/src/Resources/RedirectResource/Pages/CreateRedirect.php new file mode 100644 index 00000000..e64b57c4 --- /dev/null +++ b/packages/redirects/src/Resources/RedirectResource/Pages/CreateRedirect.php @@ -0,0 +1,11 @@ +label(__('Import by pasting text')) + ->icon('heroicon-o-clipboard-document-list') + ->modal() + ->modalWidth('100%') + ->form([ + Grid::make([ + 'default' => 12, + ])->schema([ + Select::make('code') + ->label(__('Type')) + ->columnSpanFull() + ->options(collect(config('redirects.status_codes'))->map(fn (string $type, int $code) => $code . ' ' . $type)) + ->default(config('redirects.default_status_code')) + ->prefixIcon('heroicon-o-map-pin') + ->placeholder('HTTP status message') + ->required(), + Textarea::make('sources') + ->label(__('Sources')) + ->placeholder(__('Paste your source URLs here')) + ->columnSpan(6) + ->required() + ->rows(30), + Textarea::make('destinations') + ->label(__('Destinations')) + ->placeholder(__('Paste your destination URLs here')) + ->columnSpan(6) + ->required() + ->rows(30), + ]), + ]) + ->action(function ($data) { + $sourceLines = preg_split('/\r\n|\r|\n/', $data['sources']); + $destinationLines = preg_split('/\r\n|\r|\n/', $data['destinations']); + + $redirects = []; + + foreach ($sourceLines as $index => $source) { + $destination = $destinationLines[$index] ?? null; + + if ($destination !== null) { + $redirects[] = [ + 'code' => $data['code'], + 'source' => trim($source), + 'destination' => trim($destination), + ]; + } + } + + foreach ($redirects as $redirect) { + Redirect::updateOrCreate([ + 'source' => $redirect['source'], + 'site_id' => Filament::getTenant()->ulid, + ], [ + 'destination' => $redirect['destination'], + 'code' => $redirect['code'], + ]); + } + }), + Actions\ImportAction::make('import-file') + ->label(__('Import by file')) + ->icon('heroicon-o-arrow-up-on-square-stack') + ->importer(RedirectImporter::class), + ])->label(__('Import')) + ->color('gray') + ->icon('heroicon-o-arrow-up-tray') + ->size(ActionSize::Small) + ->button(), + Actions\CreateAction::make(), + ]; + } +} diff --git a/packages/redirects/src/Testing/TestsRedirects.php b/packages/redirects/src/Testing/TestsRedirects.php new file mode 100644 index 00000000..c9e1e0ab --- /dev/null +++ b/packages/redirects/src/Testing/TestsRedirects.php @@ -0,0 +1,13 @@ +expect(['dd', 'dump', 'ray']) + ->each->not->toBeUsed(); diff --git a/packages/redirects/tests/ExampleTest.php b/packages/redirects/tests/ExampleTest.php new file mode 100644 index 00000000..5d363218 --- /dev/null +++ b/packages/redirects/tests/ExampleTest.php @@ -0,0 +1,5 @@ +toBeTrue(); +}); diff --git a/packages/redirects/tests/Pest.php b/packages/redirects/tests/Pest.php new file mode 100644 index 00000000..42ad93bc --- /dev/null +++ b/packages/redirects/tests/Pest.php @@ -0,0 +1,5 @@ +in(__DIR__); diff --git a/packages/redirects/tests/TestCase.php b/packages/redirects/tests/TestCase.php new file mode 100644 index 00000000..06262e5e --- /dev/null +++ b/packages/redirects/tests/TestCase.php @@ -0,0 +1,49 @@ +set('database.default', 'testing'); + } +}