From bd3ecf8aa34a95a14e18e5adf2a781d77775218b Mon Sep 17 00:00:00 2001 From: Pascal Baljet Date: Wed, 9 Dec 2020 20:15:54 +0100 Subject: [PATCH] WIP --- .editorconfig | 15 +++ .gitattributes | 11 ++ .github/FUNDING.yml | 1 + .github/workflows/run-tests.yml | 64 ++++++++++ .gitignore | 7 ++ .scrutinizer.yml | 19 +++ CHANGELOG.md | 7 ++ CONTRIBUTING.md | 55 +++++++++ LICENSE.md | 21 ++++ README.md | 207 ++++++++++++++++++++++++++++++++ composer.json | 46 +++++++ phpunit.xml.dist | 29 +++++ src/WhereNot.php | 115 ++++++++++++++++++ tests/Comment.php | 9 ++ tests/Post.php | 47 ++++++++ tests/ReadmeExampleTest.php | 51 ++++++++ tests/TestCase.php | 48 ++++++++ tests/User.php | 13 ++ tests/Video.php | 9 ++ tests/WhereNotTest.php | 173 ++++++++++++++++++++++++++ tests/create_tables.php | 49 ++++++++ 21 files changed, 996 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/WhereNot.php create mode 100644 tests/Comment.php create mode 100644 tests/Post.php create mode 100644 tests/ReadmeExampleTest.php create mode 100644 tests/TestCase.php create mode 100644 tests/User.php create mode 100644 tests/Video.php create mode 100644 tests/WhereNotTest.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..fec3f47 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# Changelog + +All notable changes to `laravel-eloquent-where-not` will be documented in this file + +## 1.0.0 - 2020-12-09 + +- 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..8899277 --- /dev/null +++ b/README.md @@ -0,0 +1,207 @@ +# Laravel Eloquent Where Not + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/protonemedia/laravel-eloquent-where-not.svg?style=flat-square)](https://packagist.org/packages/protonemedia/laravel-eloquent-where-not) +![run-tests](https://github.com/protonemedia/laravel-eloquent-where-not/workflows/run-tests/badge.svg) +[![Quality Score](https://img.shields.io/scrutinizer/g/protonemedia/laravel-eloquent-where-not.svg?style=flat-square)](https://scrutinizer-ci.com/g/protonemedia/laravel-eloquent-where-not) +[![Total Downloads](https://img.shields.io/packagist/dt/protonemedia/laravel-eloquent-where-not.svg?style=flat-square)](https://packagist.org/packages/protonemedia/laravel-eloquent-where-not) +[![Buy us a tree](https://img.shields.io/badge/Treeware-%F0%9F%8C%B3-lightgreen)](https://plant.treeware.earth/protonemedia/laravel-eloquent-where-not) + +## Requirements + +* PHP 7.4+ +* Laravel 7.0 and higher + +This package has been tested with MySQL 5.7+ but others drivers should work as well. + +## Features + +* Intvert your scope, or really any query constraint. +* Zero third-party dependencies. + +## Support + +We proudly support the community by developing Laravel packages and giving them away for free. Keeping track of issues and pull requests takes time, but we're happy to help! If this package saves you time or if you're relying on it professionally, please consider [supporting the maintenance and development](https://github.com/sponsors/pascalbaljet). + +## Blogpost + +[...soon!](https://protone.media/blog/stop-duplicating-your-eloquent-query-scopes-and-constraints-re-use-them-as-select-statements-with-a-new-laravel-package). + +## Installation + +You can install the package via composer: + +```bash +composer require protonemedia/laravel-eloquent-where-not +``` + +Add the `macro` to the query builder, for example, in your `AppServiceProvider`. By default, the name of the macro is `whereNot`, but you can customize it with the first parameter of the `addMacro` method. + +```php +use ProtoneMedia\LaravelEloquentWhereNot\WhereNot; + +public function boot() +{ + WhereNot::addMacro(); + + // or use a custom method name: + WhereNot::addMacro('not'); +} +``` + +## Short API description + +*For a more practical explanation, check out the [usage](#usage) section below.* + +Call the `whereNot` method with a Closure: +```php +Post::whereNot(function ($query) { + $query->onFrontPage(); +})->get(); +``` + +The example above can be shortened by using a string, where the second argument is the name of the scope: +```php +Post::whereNot('onFrontPage')->get(); +``` + +You can use an array to call multiple scopes: +```php +Post::whereNot(['popular', 'published'])->get(); +``` + +Use an associative array to call dynamic scopes: +```php +Post::whereNot(['ofType' => 'announcement'])->get(); +``` + +If your dynamic scopes require multiple arguments, you can use an associative array: +```php +Post::whereNot(['publishedBetween' => [2010, 2020]])->get(); +``` + +You can also mix dynamic and non-dynmaic scopes: +```php +Post::whereNot([ + 'published', + 'ofType' => 'announcement' +])->get(); +``` + +## Usage + +Imagine you have a `Post` Eloquent model with a query scope that constraints the query to all posts to should make the front page. + +```php +class Post extends Model +{ + public function user() + { + return $this->belongsTo(User::class); + } + + public function comments() + { + return $this->hasMany(Comment::class); + } + + public function scopeOnFrontPage($query) + { + $query->where('is_public', 1) + ->where('votes', '>', 100) + ->has('comments', '>=', 20) + ->whereHas('user', fn($user) => $user->isAdmin()) + ->whereYear('published_at', date('Y')); + } +} +``` + +Now you can fetch all posts for your front page by calling the scope method on the query: + +```php +$posts = Post::onFrontPage()->get(); +``` + +But what if you want to fetch *all* posts that *didn't* make the front page? Using the power of this package, you can re-use your scope! + +```php +$posts = Post::whereNot(function($query) { + $query->onFrontPage(); +})->get(); +``` + +With short closures, a feature which was introduced in PHP 7.4, this can be even shorter: + +```php +$posts = Post::whereNot(fn ($query) => $query->onFrontPage())->get(); +``` + +### Shortcuts + +Instead of using a Closure, there are some shortcuts you could use (see also: [Short API description](#short-api-description)): + +Using a string instead of a Closure: + +```php +Post::whereNot(function ($query) { + $query->published(); +}); + +// is the same as: + +Post::whereNot('published'); +``` + +Using an array instead of Closure, to support multiple scopes and dynamic scopes: + +```php +Post::whereNot(function ($query) { + $query->ofType('announcement'); +}); + +// is the same as: + +Post::whereNot(['ofType' => 'announcement']); +``` + +### 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 Cross Eloquent Search`](https://github.com/protonemedia/laravel-cross-eloquent-search): Laravel package to search through multiple Eloquent models. +* [`Laravel Eloquent Scope as Select`](https://github.com/protonemedia/laravel-eloquent-scope-as-select): Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery. +* [`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-where-not) 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..cf0f941 --- /dev/null +++ b/composer.json @@ -0,0 +1,46 @@ +{ + "name": "protonemedia/laravel-eloquent-where-not", + "description": "Laravel package to invert Eloquent scopes.", + "keywords": [ + "protonemedia", + "laravel-eloquent-where-not" + ], + "homepage": "https://github.com/protonemedia/laravel-eloquent-where-not", + "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\\LaravelEloquentWhereNot\\": "src" + } + }, + "autoload-dev": { + "psr-4": { + "ProtoneMedia\\LaravelEloquentWhereNot\\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 +} \ 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/WhereNot.php b/src/WhereNot.php new file mode 100644 index 0000000..554b2df --- /dev/null +++ b/src/WhereNot.php @@ -0,0 +1,115 @@ + $arguments) { + if (is_numeric($scope)) { + [$scope, $arguments] = [$arguments, null]; + } + + // As we allow a constraint to be a single arguments. + $arguments = Arr::wrap($arguments); + + $query->{$scope}(...$arguments); + } + + return $query; + }; + } + + /** + * Adds a macro to the query builder. + * + * @param string $name + * @return void + */ + public static function addMacro(string $name = 'whereNot') + { + Builder::macro($name, function ($withQuery): Builder { + $callable = is_callable($withQuery) + ? $withQuery + : WhereNot::makeCallable($withQuery); + + // We do this to make sure the $query variable is an Eloquent Query Builder. + $builder = WhereNot::builder($this); + + return $builder->whereNotExists(function ($query) use ($callable, $builder) { + // Create a new Eloquent Query Builder with the given Query Builder and + // set the model from the original builder. + $query = new Builder($query); + $query->setModel($builder->getModel()); + + $originalTable = $query->getModel()->getTable(); + + // Instantiate a new model that uses the aliased table. + $aliasedTable = WhereNot::getTableAlias($originalTable); + $aliasedModel = $query->newModelInstance()->setTable($aliasedTable); + + // Apply the where constraint based on the model's key name and apply the $callable. + $query + ->setModel($aliasedModel) + ->select(DB::raw(1)) + ->from($originalTable, $aliasedTable) + ->whereColumn($aliasedModel->getQualifiedKeyName(), 'posts.id') + ->limit(1) + ->tap(fn ($query) => $callable($query)); + }); + }); + } +} diff --git a/tests/Comment.php b/tests/Comment.php new file mode 100644 index 0000000..953b891 --- /dev/null +++ b/tests/Comment.php @@ -0,0 +1,9 @@ +belongsTo(User::class); + } + + public function comments() + { + return $this->hasMany(Comment::class); + } + + public function scopeTitleIs($query, $title) + { + $query->where($query->qualifyColumn('title'), $title); + } + + public function scopeTitleIsFoo($query) + { + $query->titleIs('foo'); + } + + public function scopeHasMoreCommentsThan($query, $value) + { + $query->has('comments', '>', $value); + } + + public function scopeHasSixOrMoreComments($query) + { + $query->hasMoreCommentsThan(5); + } + + public function scopeOnFrontPage($query) + { + $query->where('is_public', 1) + ->where($query->qualifyColumn('votes'), '>', 100) + ->has('comments', '>=', 20) + ->whereHas('user', fn ($user) => $user->isAdmin()) + ->whereYear('published_at', date('Y')); + } +} diff --git a/tests/ReadmeExampleTest.php b/tests/ReadmeExampleTest.php new file mode 100644 index 0000000..317ce93 --- /dev/null +++ b/tests/ReadmeExampleTest.php @@ -0,0 +1,51 @@ + false]); + + $post = $posts[] = Post::create([ + 'title' => $i, + 'votes' => 100, + 'is_public' => false, + 'user_id' => $user->id, + 'published_at' => now()->subYear(), + ]); + + foreach (range(1, 19) as $i) { + $post->comments()->create(['body' => 'ok']); + } + } + + $posts->skip(1)->each->update(['votes' => 101]); + $posts->skip(2)->each->update(['is_public' => true]); + $posts->skip(3)->each->update(['published_at' => now()]); + $posts->skip(4)->each->update(['published_at' => now()]); + $posts->skip(5)->each(function ($post) { + $post->user->update(['is_admin' => true]); + }); + + $posts->skip(6)->each(function ($post) { + $post->comments()->create(['body' => 'ok']); + }); + + $onFrontPage = Post::onFrontPage()->get(); + $this->assertCount(4, $onFrontPage); + $this->assertEquals([7,8,9,10], $onFrontPage->map->title->all()); + + $notOnFrontPage = Post::whereNot('onFrontPage')->get(); + $this->assertCount(6, $notOnFrontPage); + $this->assertEquals([1,2,3,4,5,6], $notOnFrontPage->map->title->all()); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php new file mode 100644 index 0000000..7569c25 --- /dev/null +++ b/tests/TestCase.php @@ -0,0 +1,48 @@ +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/User.php b/tests/User.php new file mode 100644 index 0000000..4ef196f --- /dev/null +++ b/tests/User.php @@ -0,0 +1,13 @@ +where('is_admin', 1); + } +} diff --git a/tests/Video.php b/tests/Video.php new file mode 100644 index 0000000..5364148 --- /dev/null +++ b/tests/Video.php @@ -0,0 +1,9 @@ + 'foo']); + $postB = Post::create(['title' => 'foo']); + $postC = Post::create(['title' => 'bar']); + $postD = Post::create(['title' => 'bar']); + + foreach (range(1, 5) as $i) { + $postA->comments()->create(['body' => 'ok']); + $postC->comments()->create(['body' => 'ok']); + } + + foreach (range(1, 10) as $i) { + $postB->comments()->create(['body' => 'ok']); + $postD->comments()->create(['body' => 'ok']); + } + + return [$postA, $postB, $postC, $postD]; + } + + /** @test */ + public function it_can_invert_a_scope() + { + $postA = Post::create(['title' => 'foo']); + $postB = Post::create(['title' => 'bar']); + + $posts = Post::query() + ->whereNot(fn ($query) => $query->titleIsFoo()) + ->orderBy('id') + ->get(); + + $this->assertCount(1, $posts); + $this->assertTrue($posts->contains($postB)); + } + + /** @test */ + public function it_can_invert_a_scope_by_using_the_name() + { + $postA = Post::create(['title' => 'foo']); + $postB = Post::create(['title' => 'bar']); + + $posts = Post::query() + ->whereNot('titleIsFoo') + ->orderBy('id') + ->get(); + + $this->assertCount(1, $posts); + $this->assertTrue($posts->contains($postB)); + } + + /** @test */ + public function it_can_invert_multiple_scopes_by_using_an_array() + { + [$postA, $postB, $postC, $postD] = $this->prepareFourPosts(); + + $posts = Post::query() + ->whereNot(['titleIsFoo', 'hasSixOrMoreComments']) + ->orderBy('id') + ->get(); + + $this->assertCount(3, $posts); + $this->assertTrue($posts->contains($postA)); + $this->assertTrue($posts->contains($postC)); + $this->assertTrue($posts->contains($postD)); + } + + /** @test */ + public function it_can_invert_multiple_dynamic_scopes_by_using_an_array() + { + [$postA, $postB, $postC, $postD] = $this->prepareFourPosts(); + + $posts = Post::query() + ->whereNot([ + 'titleIsFoo', + 'hasMoreCommentsThan' => 5, + ]) + ->orderBy('id') + ->get(); + + $this->assertCount(3, $posts); + $this->assertTrue($posts->contains($postA)); + $this->assertTrue($posts->contains($postC)); + $this->assertTrue($posts->contains($postD)); + } + + /** @test */ + public function it_can_invert_multiple_dynamic_scopes_by_using_an_array_of_scope_arguments() + { + [$postA, $postB, $postC, $postD] = $this->prepareFourPosts(); + + $posts = Post::query() + ->whereNot([ + 'titleIsFoo', + 'hasMoreCommentsThan' => [5], + ]) + ->orderBy('id') + ->get(); + + $this->assertCount(3, $posts); + $this->assertTrue($posts->contains($postA)); + $this->assertTrue($posts->contains($postC)); + $this->assertTrue($posts->contains($postD)); + } + + /** @test */ + public function it_can_invert_multiple_and_has_relation_scopes() + { + $postA = Post::create(['title' => 'foo']); + $postB = Post::create(['title' => 'bar']); + + foreach (range(1, 10) as $i) { + $postA->comments()->create(['body' => 'ok']); + } + + foreach (range(1, 5) as $i) { + $postB->comments()->create(['body' => 'ok']); + } + + $posts = Post::query() + ->whereNot(function ($query) { + $query->hasSixOrMoreComments(); + }) + ->whereNot(function ($query) { + $query->titleIsFoo(); + }) + ->orderBy('id') + ->get(); + + $this->assertCount(1, $posts); + $this->assertTrue($posts->contains($postB)); + } + + /** @test */ + public function it_can_invert_inline_contraints_as_well() + { + [$postA, $postB, $postC, $postD] = $this->prepareFourPosts(); + + $posts = Post::query() + ->whereNot(function ($query) { + $query->where('title', 'foo')->has('comments', '>=', 6); + }) + ->orderBy('id') + ->get(); + + $this->assertCount(3, $posts); + $this->assertTrue($posts->contains($postA)); + $this->assertTrue($posts->contains($postC)); + $this->assertTrue($posts->contains($postD)); + } + + /** @test */ + public function it_can_mix_scopes_outside_of_the_closure() + { + [$postA, $postB, $postC, $postD] = $this->prepareFourPosts(); + + $posts = Post::query() + ->where('title', 'foo') + ->whereNot(function ($query) { + $query->has('comments', '>=', 6); + }) + ->orderBy('id') + ->get(); + + $this->assertCount(1, $posts); + $this->assertTrue($posts->contains($postA)); + } +} diff --git a/tests/create_tables.php b/tests/create_tables.php new file mode 100644 index 0000000..0545c12 --- /dev/null +++ b/tests/create_tables.php @@ -0,0 +1,49 @@ +bigIncrements('id'); + $table->boolean('is_admin')->default(false); + $table->timestamps(); + }); + + Schema::create('posts', function (Blueprint $table) { + $table->bigIncrements('id'); + $table->unsignedInteger('user_id')->nullable(); + $table->integer('votes')->default(0); + $table->boolean('is_public')->default(false); + $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(); + }); + } + /** + * Reverse the migrations. + * + * @return void + */ + public function down() + { + Schema::dropIfExists('posts'); + } +}