From a9e65133c5a05eb5a4f829791491cf082b3d0f37 Mon Sep 17 00:00:00 2001 From: pascalbaljet Date: Mon, 30 Nov 2020 09:30:10 +0100 Subject: [PATCH] first commit --- .editorconfig | 15 +++++++ .gitattributes | 11 +++++ .github/FUNDING.yml | 1 + .github/workflows/run-tests.yml | 64 +++++++++++++++++++++++++++ .gitignore | 7 +++ .scrutinizer.yml | 19 +++++++++ CHANGELOG.md | 28 ++++++++++++ CONTRIBUTING.md | 55 ++++++++++++++++++++++++ LICENSE.md | 21 +++++++++ README.md | 76 +++++++++++++++++++++++++++++++++ composer.json | 53 +++++++++++++++++++++++ phpunit.xml.dist | 29 +++++++++++++ src/NullableBooleanCaster.php | 17 ++++++++ src/ServiceProvider.php | 49 +++++++++++++++++++++ tests/Comment.php | 9 ++++ tests/Post.php | 18 ++++++++ tests/SearchTest.php | 23 ++++++++++ tests/TestCase.php | 51 ++++++++++++++++++++++ tests/Video.php | 9 ++++ tests/create_tables.php | 48 +++++++++++++++++++++ 20 files changed, 603 insertions(+) create mode 100644 .editorconfig create mode 100644 .gitattributes create mode 100644 .github/FUNDING.yml create mode 100644 .github/workflows/run-tests.yml create mode 100644 .gitignore create mode 100644 .scrutinizer.yml create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 composer.json create mode 100644 phpunit.xml.dist create mode 100644 src/NullableBooleanCaster.php create mode 100644 src/ServiceProvider.php create mode 100644 tests/Comment.php create mode 100644 tests/Post.php create mode 100644 tests/SearchTest.php create mode 100644 tests/TestCase.php create mode 100644 tests/Video.php create mode 100644 tests/create_tables.php diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..cd8eb86 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at http://editorconfig.org + +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 diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..bb6265e --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore all test and documentation with "export-ignore". +/.gitattributes export-ignore +/.gitignore export-ignore +/.travis.yml export-ignore +/phpunit.xml.dist export-ignore +/.scrutinizer.yml export-ignore +/tests export-ignore +/.editorconfig export-ignore diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..ecdd8d3 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1 @@ +github: [pascalbaljet] diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml new file mode 100644 index 0000000..3ca4b27 --- /dev/null +++ b/.github/workflows/run-tests.yml @@ -0,0 +1,64 @@ +name: run-tests + +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: true + matrix: + php: [8.0, 7.4] + laravel: [8.*, 7.*] + dependency-version: [prefer-lowest, prefer-stable] + include: + - laravel: 8.* + testbench: 6.* + - laravel: 7.* + testbench: 5.* + + name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} + + services: + mysql: + image: mysql:5.7 + env: + MYSQL_ALLOW_EMPTY_PASSWORD: no + MYSQL_USER: protone_media_db_test + MYSQL_DATABASE: protone_media_db_test + MYSQL_PASSWORD: secret + MYSQL_ROOT_PASSWORD: secret + ports: + - 3306 + options: --health-cmd="mysqladmin ping" --health-interval=10s --health-timeout=5s --health-retries=3 + + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Cache dependencies + uses: actions/cache@v2 + with: + path: ~/.composer/cache/files + key: dependencies-laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} + + - 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, mysql, mysqli, pdo_mysql + coverage: none + + - name: Install dependencies + run: | + composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update + composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --no-suggest + + - name: Execute tests + run: vendor/bin/phpunit + env: + DB_DATABASE: protone_media_db_test + DB_USERNAME: protone_media_db_test + DB_PASSWORD: secret + DB_PORT: ${{ job.services.mysql.ports[3306] }} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..65ff236 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +build +composer.lock +docs +vendor +coverage +.phpunit.result.cache +.phpunit.result.cache diff --git a/.scrutinizer.yml b/.scrutinizer.yml new file mode 100644 index 0000000..df16b68 --- /dev/null +++ b/.scrutinizer.yml @@ -0,0 +1,19 @@ +filter: + excluded_paths: [tests/*] + +checks: + php: + remove_extra_empty_lines: true + remove_php_closing_tag: true + remove_trailing_whitespace: true + fix_use_statements: + remove_unused: true + preserve_multiple: false + preserve_blanklines: true + order_alphabetically: true + fix_php_opening_tag: true + fix_linefeed: true + fix_line_ending: true + fix_identation_4spaces: true + fix_doc_comments: true + diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..49eebd0 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,28 @@ +# Changelog + +All notable changes to `laravel-eloquent-scope-as-select` will be documented in this file + +## 1.4.0 - 2020-10-28 + +- Allow empty search terms +- Added `new()` method method + +## 1.3.1 - 2020-10-28 + +- Docs + +## 1.3.0 - 2020-09-24 + +- Support for Laravel 8.0 + +## 1.2.0 - 2020-08-28 + +- standalone search terms parser + +## 1.1.0 - 2020-08-10 + +- option to disable the parsing of the search term + +## 1.0.0 - 2020-07-08 + +- initial release diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..b4ae1c4 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,55 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +Please read and understand the contribution guide before creating an issue or pull request. + +## Etiquette + +This project is open source, and as such, the maintainers give their free time to build and maintain the source code +held within. They make the code freely available in the hope that it will be of use to other developers. It would be +extremely unfair for them to suffer abuse or anger for their hard work. + +Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the +world that developers are civilized and selfless people. + +It's the duty of the maintainer to ensure that all submissions to the project are of sufficient +quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. + +## Viability + +When requesting or submitting new features, first consider whether it might be useful to others. Open +source projects are used by many developers, who may have entirely different needs to your own. Think about +whether or not your feature is likely to be used by other users of the project. + +## Procedure + +Before filing an issue: + +- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. +- Check to make sure your feature suggestion isn't already present within the project. +- Check the pull requests tab to ensure that the bug doesn't have a fix in progress. +- Check the pull requests tab to ensure that the feature isn't already in progress. + +Before submitting a pull request: + +- Check the codebase to ensure that your feature doesn't already exist. +- Check the pull requests to ensure that another person hasn't already submitted the feature or fix. + +## Requirements + +If the project maintainer has any additional requirements, you will find them listed here. + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + +**Happy coding**! diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..734d597 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Protone Media B.V. + +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. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..c9ec80b --- /dev/null +++ b/README.md @@ -0,0 +1,76 @@ +# Laravel Eloquent Scope as Select + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/protonemedia/laravel-eloquent-scope-as-select.svg?style=flat-square)](https://packagist.org/packages/protonemedia/laravel-eloquent-scope-as-select) +![run-tests](https://github.com/protonemedia/laravel-eloquent-scope-as-select/workflows/run-tests/badge.svg) +[![Quality Score](https://img.shields.io/scrutinizer/g/protonemedia/laravel-eloquent-scope-as-select.svg?style=flat-square)](https://scrutinizer-ci.com/g/protonemedia/laravel-eloquent-scope-as-select) +[![Total Downloads](https://img.shields.io/packagist/dt/protonemedia/laravel-eloquent-scope-as-select.svg?style=flat-square)](https://packagist.org/packages/protonemedia/laravel-eloquent-scope-as-select) +[![Buy us a tree](https://img.shields.io/badge/Treeware-%F0%9F%8C%B3-lightgreen)](https://plant.treeware.earth/protonemedia/laravel-eloquent-scope-as-select) + +... + +## Requirements + +* PHP 7.4+ +* MySQL 5.7+ +* Laravel 7.0 and higher + +## Features + +* Zero third-party dependencies + +## Blogpost + +If you want to know more about the background of this package, please read [the blogpost](https://protone.media/blog/search-through-multiple-eloquent-models-with-our-latest-laravel-package). + +## Installation + +You can install the package via composer: + +```bash +composer require protonemedia/laravel-eloquent-scope-as-select +``` + +## Usage + +... + +### Testing + +``` bash +composer test +``` + +### Changelog + +Please see [CHANGELOG](CHANGELOG.md) for more information about what has changed recently. + +## Contributing + +Please see [CONTRIBUTING](CONTRIBUTING.md) for details. + +## Other Laravel packages + +* [`Laravel Analytics Event Tracking`](https://github.com/protonemedia/laravel-analytics-event-tracking): Laravel package to easily send events to Google Analytics. +* [`Laravel Blade On Demand`](https://github.com/protonemedia/laravel-blade-on-demand): Laravel package to compile Blade templates in memory. +* [`Laravel FFMpeg`](https://github.com/protonemedia/laravel-ffmpeg): This package provides an integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem. +* [`Laravel Form Components`](https://github.com/protonemedia/laravel-form-components): Blade components to rapidly build forms with Tailwind CSS Custom Forms and Bootstrap 4. Supports validation, model binding, default values, translations, includes default vendor styling and fully customizable! +* [`Laravel Paddle`](https://github.com/protonemedia/laravel-paddle): Paddle.com API integration for Laravel with support for webhooks/events. +* [`Laravel Verify New Email`](https://github.com/protonemedia/laravel-verify-new-email): This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified. +* [`Laravel WebDAV`](https://github.com/protonemedia/laravel-webdav): WebDAV driver for Laravel's Filesystem. + +### Security + +If you discover any security related issues, please email pascal@protone.media instead of using the issue tracker. + +## Credits + +- [Pascal Baljet](https://github.com/protonemedia) +- [All Contributors](../../contributors) + +## License + +The MIT License (MIT). Please see [License File](LICENSE.md) for more information. + +## Treeware + +This package is [Treeware](https://treeware.earth). If you use it in production, then we ask that you [**buy the world a tree**](https://plant.treeware.earth/pascalbaljetmedia/laravel-eloquent-scope-as-select) to thank us for our work. By contributing to the Treeware forest you’ll be creating employment for local families and restoring wildlife habitats. diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..1e7b3e8 --- /dev/null +++ b/composer.json @@ -0,0 +1,53 @@ +{ + "name": "protonemedia/laravel-eloquent-scope-as-select", + "description": "Laravel package to search through multiple Eloquent models. Supports pagination, eager loading relations, single/multiple columns, sorting and scoped queries.", + "keywords": [ + "protonemedia", + "laravel-eloquent-scope-as-select" + ], + "homepage": "https://github.com/protonemedia/laravel-eloquent-scope-as-select", + "license": "MIT", + "type": "library", + "authors": [ + { + "name": "Pascal Baljet", + "email": "pascal@protone.media", + "role": "Developer" + } + ], + "require": { + "php": "^7.4|^8.0", + "illuminate/support": "^7.0|^8.0" + }, + "require-dev": { + "mockery/mockery": "^1.3.3", + "orchestra/testbench": "^5.0|^6.0", + "phpunit/phpunit": "^9.0" + }, + "autoload": { + "psr-4": { + "ProtoneMedia\\LaravelEloquentScopeAsSelect\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "ProtoneMedia\\LaravelEloquentScopeAsSelect\\Tests\\": "tests" + } + }, + "scripts": { + "test": "vendor/bin/phpunit", + "test-coverage": "vendor/bin/phpunit --coverage-html coverage" + }, + "config": { + "sort-packages": true + }, + "minimum-stability": "dev", + "prefer-stable": true, + "extra": { + "laravel": { + "providers": [ + "ProtoneMedia\\LaravelEloquentScopeAsSelect\\ServiceProvider" + ] + } + } +} \ No newline at end of file diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..22fe879 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,29 @@ + + + + + tests + + + + + src/ + + + + + + + + + + diff --git a/src/NullableBooleanCaster.php b/src/NullableBooleanCaster.php new file mode 100644 index 0000000..e38cacf --- /dev/null +++ b/src/NullableBooleanCaster.php @@ -0,0 +1,17 @@ +getModel(); + + $table = $originalModel->getTable(); + + $as = "{$name}_{$table}"; + + $asTable = "{$table} as {$as}"; + + $subSelect = $originalModel::query(); + + $model = $originalModel->newModelInstance() ?: (clone $subSelect->getModel()); + $model->setTable($as); + + $subSelect->setModel($model); + $subSelect->getQuery()->from($asTable); + + $subSelect + ->select(DB::raw(1)) + ->whereColumn($model->getQualifiedKeyName(), $originalModel->getQualifiedKeyName()) + ->tap(function ($query) use ($callable) { + $callable($query); + }); + + $query->withCasts([ + $name => NullableBooleanCaster::class, + ])->addSelect([$name => $subSelect]); + + return $this; + }); + } +} diff --git a/tests/Comment.php b/tests/Comment.php new file mode 100644 index 0000000..c0ae7f6 --- /dev/null +++ b/tests/Comment.php @@ -0,0 +1,9 @@ +hasMany(Comment::class); + } + + public function scopeTitleIsFoo($query) + { + $query->where($query->qualifyColumn('title'), 'foo'); + } +} diff --git a/tests/SearchTest.php b/tests/SearchTest.php new file mode 100644 index 0000000..5a34423 --- /dev/null +++ b/tests/SearchTest.php @@ -0,0 +1,23 @@ + 'foo']); + $postB = Post::create(['title' => 'bar']); + + $posts = Post::query() + ->addScopeAsSelect('title_is_foo', function ($query) { + $query->titleIsFoo(); + }) + ->orderBy('id') + ->get(); + + $this->assertTrue($posts->get(0)->title_is_foo); + $this->assertFalse($posts->get(1)->title_is_foo); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..fd4be2a --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,51 @@ +app['config']->set('app.key', 'base64:yWa/ByhLC/GUvfToOuaPD7zDwB64qkc/QkaQOrT5IpE='); + + $this->app['config']->set('database.connections.mysql', [ + 'driver' => 'mysql', + 'url' => env('DATABASE_URL'), + 'host' => env('DB_HOST', '127.0.0.1'), + 'port' => env('DB_PORT', '3306'), + 'database' => env('DB_DATABASE', 'scope_as_select_test'), + 'username' => env('DB_USERNAME', 'homestead'), + 'password' => env('DB_PASSWORD', 'secret'), + 'unix_socket' => env('DB_SOCKET', ''), + 'charset' => 'utf8mb4', + 'collation' => 'utf8mb4_unicode_ci', + 'prefix' => '', + 'prefix_indexes' => true, + 'strict' => true, + 'engine' => null, + 'options' => extension_loaded('pdo_mysql') ? array_filter([ + PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), + ]) : [], + ]); + + $this->artisan('migrate:fresh'); + + include_once __DIR__ . '/create_tables.php'; + + (new \CreateTables)->up(); + } +} diff --git a/tests/Video.php b/tests/Video.php new file mode 100644 index 0000000..aaa62d1 --- /dev/null +++ b/tests/Video.php @@ -0,0 +1,9 @@ +bigIncrements('id'); + $table->string('title'); + $table->date('published_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('comments', function (Blueprint $table) { + $table->bigIncrements('id'); + $table->unsignedInteger('post_id'); + $table->string('body'); + $table->date('published_at')->nullable(); + $table->timestamps(); + }); + + Schema::create('videos', function (Blueprint $table) { + $table->bigIncrements('id'); + $table->string('title'); + $table->string('subtitle')->nullable(); + $table->date('published_at')->nullable(); + $table->timestamps(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('posts'); + } +}