diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index c68765b..579a6fe 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1 @@ -github: :vendor_name +github: soyhuce diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 80a788c..d1cbe0e 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,14 +1,14 @@ blank_issues_enabled: false contact_links: - name: Ask a question - url: https://github.com/:vendor_name/:package_name/discussions/new?category=q-a + url: https://github.com/Soyhuce/laravel-eloquent-extended/discussions/new?category=q-a about: Ask the community for help - name: Request a feature - url: https://github.com/:vendor_name/:package_name/discussions/new?category=ideas + url: https://github.com/Soyhuce/laravel-eloquent-extended/discussions/new?category=ideas about: Share ideas for new features - name: Report a security issue - url: https://github.com/:vendor_name/:package_name/security/policy + url: https://github.com/Soyhuce/laravel-eloquent-extended/security/policy about: Learn how to notify us for sensitive bugs - name: Report a bug - url: https://github.com/:vendor_name/:package_name/issues/new + url: https://github.com/Soyhuce/laravel-eloquent-extended/issues/new about: Report a reproducable bug diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 12ab7c2..2689ee1 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -1,3 +1,3 @@ # Security Policy -If you discover any security related issues, please email author@domain.com instead of using the issue tracker. +If you discover any security related issues, please email bastien.philippe@soyhuce.fr instead of using the issue tracker. diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index 7143f8a..06c9502 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -1,8 +1,6 @@ in([ - 'config', - 'database', 'src', 'tests', ]); diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b3242..78294ce 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,3 @@ # Changelog -All notable changes to `:package_name` will be documented in this file. +All notable changes to `laravel-eloquent-extended` will be documented in this file. diff --git a/LICENSE.md b/LICENSE.md index 58c9ad4..c3aba28 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) :vendor_name +Copyright (c) Soyhuce Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index cad6213..8051f33 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,11 @@ -# :package_description - -[![Latest Version on Packagist](https://img.shields.io/packagist/v/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) -[![GitHub Tests Action Status](https://img.shields.io/github/workflow/status/:vendor_slug/:package_slug/run-tests?label=tests)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3Arun-tests+branch%3Amain) -[![GitHub Code Style Action Status](https://img.shields.io/github/workflow/status/:vendor_slug/:package_slug/Check%20&%20fix%20styling?label=code%20style)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3A"Check+%26+fix+styling"+branch%3Amain) -[![GitHub PHPStan Action Status](https://img.shields.io/github/workflow/status/:vendor_slug/:package_slug/PHPStan?label=phpstan)](https://github.com/:vendor_slug/:package_slug/actions?query=workflow%3APHPStan+branch%3Amain) -[![Total Downloads](https://img.shields.io/packagist/dt/:vendor_slug/:package_slug.svg?style=flat-square)](https://packagist.org/packages/:vendor_slug/:package_slug) - ---- -This repo can be used to scaffold a Laravel package. Follow these steps to get started: - -1. Press the "Use template" button at the top of this repo to create a new repo with the contents of this skeleton. -2. Run "php ./configure.php" to run a script that will replace all placeholders throughout all the files. -3. Have fun creating your package. ---- - +# Some useful extensions for Eloquent + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/soyhuce/laravel-eloquent-extended.svg?style=flat-square)](https://packagist.org/packages/soyhuce/laravel-eloquent-extended) +[![GitHub Tests Action Status](https://img.shields.io/github/workflow/status/soyhuce/laravel-eloquent-extended/run-tests?label=tests)](https://github.com/soyhuce/laravel-eloquent-extended/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/workflow/status/soyhuce/laravel-eloquent-extended/Check%20&%20fix%20styling?label=code%20style)](https://github.com/soyhuce/laravel-eloquent-extended/actions?query=workflow%3A"Check+%26+fix+styling"+branch%3Amain) +[![GitHub PHPStan Action Status](https://img.shields.io/github/workflow/status/soyhuce/laravel-eloquent-extended/PHPStan?label=phpstan)](https://github.com/soyhuce/laravel-eloquent-extended/actions?query=workflow%3APHPStan+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/soyhuce/laravel-eloquent-extended.svg?style=flat-square)](https://packagist.org/packages/soyhuce/laravel-eloquent-extended) + This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. ## Installation @@ -21,41 +13,59 @@ This is where your description should go. Limit it to a paragraph or two. Consid You can install the package via composer: ```bash -composer require :vendor_slug/:package_slug +composer require soyhuce/laravel-eloquent-extended ``` -You can publish and run the migrations with: -```bash -php artisan vendor:publish --tag=":package_slug-migrations" -php artisan migrate -``` +## Usage -You can publish the config file with: +## Builder -```bash -php artisan vendor:publish --tag=":package_slug-config" -``` +### Misc -This is the contents of the published config file: +- Builder::scope(Illuminate\Database\Eloquent\Scope $score): Builder +- Builder::scoped(\Closure $callable): Builder -```php -return [ -]; -``` +### Ordering -Optionally, you can publish the views using +- Builder::preventInvalidDirection(string $direction): void +- Builder::orderByNullsLast(string $column, string $direction = 'asc'): Builder +- Builder::orderByRawNullsLast(string $sql): Builder +- Builder::orderByAggregate( string $relationName, string $column, string $direction = 'asc', ?string $function = null, + ?Closure $constraints = null) +- Builder::orderByExists(string $relation, ?Closure $constraints = null, string $direction = 'asc') +- Builder::orderByExistsDesc(string $relation, ?Closure $constraints = null) +- Builder::orderByCount(string $relation, ?Closure $constraints = null, string $direction = 'asc') +- Builder::orderByCountDesc(string $relation, ?Closure $constraints = null) +- Builder::orderBySum(string $relation, string $column, ?Closure $constraints = null, string $direction = 'asc') +- Builder::orderBySumDesc(string $relation, string $column, ?Closure $constraints = null) +- Builder::orderByMin(string $relation, string $column, ?Closure $constraints = null, string $direction = 'asc') +- Builder::orderByMinDesc(string $relation, string $column, ?Closure $constraints = null) +- Builder::orderByMax(string $relation, string $column, ?Closure $constraints = null, string $direction = 'asc') +- Builder::orderByMaxDesc(string $relation, string $column, ?Closure $constraints = null) -```bash -php artisan vendor:publish --tag=":package_slug-views" -``` +### Result -## Usage +- Builder::random(): Model + +### Select + +- Builder::withAggregateFunction( $relations, \Soyhuce\EloquentExtended\Aggregates\Contracts\AggregateFunction + $aggregateFunction): Builder +- Builder::withAnyExists(array $relations, string $alias = 'related_exists') : Builder +- Builder::withImplode($relations, string $column, string $glue, ?string $orderBy = null, string $direction = 'asc') : + Builder + +## Eloquent Collection + +- Collection::loadAttributes(Closure(Builder): Builder|void $loadWith): Collection + +## Model traits + +### LoadsAttributes + +- Model::loadAttributes(Closure(Builder): Builder|void $loadWith): Model -```php -$variable = new VendorName\Skeleton(); -echo $variable->echoPhrase('Hello, VendorName!'); -``` ## Testing @@ -77,7 +87,7 @@ Please review [our security policy](../../security/policy) on how to report secu ## Credits -- [:author_name](https://github.com/:author_username) +- [Bastien Philippe](https://github.com/bastien-phi) - [All Contributors](../../contributors) ## License diff --git a/composer.json b/composer.json index 1c1c2fe..cd4f18e 100644 --- a/composer.json +++ b/composer.json @@ -1,24 +1,24 @@ { - "name": ":vendor_slug/:package_slug", - "description": ":package_description", + "name": "soyhuce/laravel-eloquent-extended", + "description": "Some useful extensions for Eloquent", "keywords": [ - ":vendor_name", + "Soyhuce", "laravel", - ":package_slug" + "eloquent" ], - "homepage": "https://github.com/:vendor_slug/:package_slug", + "homepage": "https://github.com/soyhuce/laravel-eloquent-extended", "license": "MIT", "authors": [ { - "name": ":author_name", - "email": "author@domain.com", + "name": "Bastien Philippe", + "email": "bastien.philippe@soyhuce.fr", "role": "Developer" } ], "require": { "php": "^8.1", - "spatie/laravel-package-tools": "^1.9.2", - "illuminate/contracts": "^9.0" + "illuminate/contracts": "^9.7", + "illuminate/database": "^9.7" }, "require-dev": { "friendsofphp/php-cs-fixer": "^3.7", @@ -30,17 +30,17 @@ "phpstan/extension-installer": "^1.1", "phpstan/phpstan-deprecation-rules": "^1.0", "phpstan/phpstan-phpunit": "^1.0", - "phpunit/phpunit": "^9.5" + "phpunit/phpunit": "^9.5", + "soyhuce/next-ide-helper": "^0.9.1" }, "autoload": { "psr-4": { - "VendorName\\Skeleton\\": "src", - "VendorName\\Skeleton\\Database\\Factories\\": "database/factories" + "Soyhuce\\EloquentExtended\\": "src" } }, "autoload-dev": { "psr-4": { - "VendorName\\Skeleton\\Tests\\": "tests" + "Soyhuce\\EloquentExtended\\Tests\\": "tests" } }, "scripts": { @@ -55,16 +55,18 @@ ] }, "config": { - "sort-packages": true + "sort-packages": true, + "preferred-install": "dist", + "allow-plugins": { + "pestphp/pest-plugin": true, + "phpstan/extension-installer": true + } }, "extra": { "laravel": { "providers": [ - "VendorName\\Skeleton\\SkeletonServiceProvider" - ], - "aliases": { - "Skeleton": "VendorName\\Skeleton\\Facades\\Skeleton" - } + "Soyhuce\\EloquentExtended\\EloquentExtendedServiceProvider" + ] } }, "minimum-stability": "dev", diff --git a/config/skeleton.php b/config/eloquent-extended.php similarity index 52% rename from config/skeleton.php rename to config/eloquent-extended.php index 5fdad42..31db79f 100644 --- a/config/skeleton.php +++ b/config/eloquent-extended.php @@ -1,4 +1,4 @@ $version) { - if (in_array($name, $names, true)) { - unset($data['require-dev'][$name]); - } - } - - file_put_contents(__DIR__.'/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function remove_composer_script($scriptName) { - $data = json_decode(file_get_contents(__DIR__.'/composer.json'), true); - - foreach($data['scripts'] as $name => $script) { - if ($scriptName === $name) { - unset($data['scripts'][$name]); - break; - } - } - - file_put_contents(__DIR__.'/composer.json', json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); -} - -function remove_readme_paragraphs(string $file): void { - $contents = file_get_contents($file); - - file_put_contents( - $file, - preg_replace('/.*/s', '', $contents) ?: $contents - ); -} - -function safeUnlink(string $filename) { - if (file_exists($filename) && is_file($filename)) { - unlink($filename); - } -} - -function determineSeparator(string $path): string { - return str_replace('/', DIRECTORY_SEPARATOR, $path); -} - -function replaceForWindows(): array { - return preg_split('/\\r\\n|\\r|\\n/', run('dir /S /B * | findstr /v /i .git\ | findstr /v /i vendor | findstr /v /i '.basename(__FILE__).' | findstr /r /i /M /F:/ ":author :vendor :package VendorName skeleton migration_table_name vendor_name vendor_slug author@domain.com"')); -} - -function replaceForAllOtherOSes(): array { - return explode(PHP_EOL, run('grep -E -r -l -i ":author|:vendor|:package|VendorName|skeleton|migration_table_name|vendor_name|vendor_slug|author@domain.com" --exclude-dir=vendor ./* ./.github/* | grep -v ' . basename(__FILE__))); -} - -$gitName = run('git config user.name'); -$authorName = ask('Author name', $gitName); - -$gitEmail = run('git config user.email'); -$authorEmail = ask('Author email', $gitEmail); - -$usernameGuess = explode(':', run('git config remote.origin.url'))[1]; -$usernameGuess = dirname($usernameGuess); -$usernameGuess = basename($usernameGuess); -$authorUsername = ask('Author username', $usernameGuess); - -$vendorName = ask('Vendor name', $authorUsername); -$vendorSlug = slugify($vendorName); -$vendorNamespace = ucwords($vendorName); -$vendorNamespace = ask('Vendor namespace', $vendorNamespace); - -$currentDirectory = getcwd(); -$folderName = basename($currentDirectory); - -$packageName = ask('Package name', $folderName); -$packageSlug = slugify($packageName); -$packageSlugWithoutPrefix = remove_prefix('laravel-', $packageSlug); - -$className = title_case($packageName); -$className = ask('Class name', $className); -$variableName = lcfirst($className); -$description = ask('Package description', "This is my package {$packageSlug}"); - -$usePhpStan = confirm('Enable PhpStan?', true); -$usePhpCsFixer = confirm('Enable PhpCsFixer?', true); -$useUpdateChangelogWorkflow = confirm('Use automatic changelog updater workflow?', true); - -writeln('------'); -writeln("Author : {$authorName} ({$authorUsername}, {$authorEmail})"); -writeln("Vendor : {$vendorName} ({$vendorSlug})"); -writeln("Package : {$packageSlug} <{$description}>"); -writeln("Namespace : {$vendorNamespace}\\{$className}"); -writeln("Class name : {$className}"); -writeln("---"); -writeln("Packages & Utilities"); -writeln("Use PhpCsFixer : " . ($usePhpCsFixer ? 'yes' : 'no')); -writeln("Use Larastan/PhpStan : " . ($usePhpStan ? 'yes' : 'no')); -writeln("Use Auto-Changelog : " . ($useUpdateChangelogWorkflow ? 'yes' : 'no')); -writeln('------'); - -writeln('This script will replace the above values in all relevant files in the project directory.'); - -if (! confirm('Modify files?', true)) { - exit(1); -} - -$files = (str_starts_with(strtoupper(PHP_OS), 'WIN') ? replaceForWindows() : replaceForAllOtherOSes()); - -foreach ($files as $file) { - replace_in_file($file, [ - ':author_name' => $authorName, - ':author_username' => $authorUsername, - 'author@domain.com' => $authorEmail, - ':vendor_name' => $vendorName, - ':vendor_slug' => $vendorSlug, - 'VendorName' => $vendorNamespace, - ':package_name' => $packageName, - ':package_slug' => $packageSlug, - ':package_slug_without_prefix' => $packageSlugWithoutPrefix, - 'Skeleton' => $className, - 'skeleton' => $packageSlug, - 'migration_table_name' => title_snake($packageSlug), - 'variable' => $variableName, - ':package_description' => $description, - ]); - - match (true) { - str_contains($file, determineSeparator('src/Skeleton.php')) => rename($file, determineSeparator('./src/' . $className . '.php')), - str_contains($file, determineSeparator('src/SkeletonServiceProvider.php')) => rename($file, determineSeparator('./src/' . $className . 'ServiceProvider.php')), - str_contains($file, determineSeparator('src/Facades/Skeleton.php')) => rename($file, determineSeparator('./src/Facades/' . $className . '.php')), - str_contains($file, determineSeparator('src/Commands/SkeletonCommand.php')) => rename($file, determineSeparator('./src/Commands/' . $className . 'Command.php')), - str_contains($file, determineSeparator('database/migrations/create_skeleton_table.php.stub')) => rename($file, determineSeparator('./database/migrations/create_' . title_snake($packageSlugWithoutPrefix) . '_table.php.stub')), - str_contains($file, determineSeparator('config/skeleton.php')) => rename($file, determineSeparator('./config/' . $packageSlugWithoutPrefix . '.php')), - str_contains($file, 'README.md') => remove_readme_paragraphs($file), - default => [], - }; -} - -if (! $usePhpCsFixer) { - safeUnlink(__DIR__ . '/.php_cs.dist.php'); - safeUnlink(__DIR__ . '/.github/workflows/php-cs-fixer.yml'); -} - -if (! $usePhpStan) { - safeUnlink(__DIR__ . '/phpstan.neon.dist'); - safeUnlink(__DIR__ . '/phpstan-baseline.neon'); - safeUnlink(__DIR__ . '/.github/workflows/phpstan.yml'); - - remove_composer_deps([ - 'phpstan/extension-installer', - 'phpstan/phpstan-deprecation-rules', - 'phpstan/phpstan-phpunit', - 'nunomaduro/larastan', - ]); - - remove_composer_script('phpstan'); -} - -if (! $useUpdateChangelogWorkflow) { - safeUnlink(__DIR__ . '/.github/workflows/update-changelog.yml'); -} - -confirm('Execute `composer install` and run tests?') && run('composer install && composer test'); - -confirm('Let this script delete itself?', true) && unlink(__FILE__); diff --git a/database/factories/ModelFactory.php b/database/factories/ModelFactory.php index a818ab6..09ed03a 100644 --- a/database/factories/ModelFactory.php +++ b/database/factories/ModelFactory.php @@ -1,6 +1,6 @@ id(); // add fields diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index e69de29..4ed1e44 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -0,0 +1,137 @@ +parameters: + ignoreErrors: + - + message: "#^PHPDoc tag @mixin contains generic class Illuminate\\\\Database\\\\Eloquent\\\\Collection but does not specify its types\\: TKey, TModel$#" + count: 1 + path: src/Mixins/CollectionMixin.php + + - + message: "#^PHPDoc tag @mixin contains generic class Illuminate\\\\Database\\\\Eloquent\\\\Builder but does not specify its types\\: TModelClass$#" + count: 1 + path: src/Mixins/Misc.php + + - + message: "#^Parameter \\#1 \\$builder of method Illuminate\\\\Database\\\\Eloquent\\\\Scope\\:\\:apply\\(\\) expects Illuminate\\\\Database\\\\Eloquent\\\\Builder, \\$this\\(Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Misc\\) given\\.$#" + count: 1 + path: src/Mixins/Misc.php + + - + message: "#^Call to protected method callScope\\(\\) of class Illuminate\\\\Database\\\\Eloquent\\\\Builder\\\\.$#" + count: 1 + path: src/Mixins/Ordering.php + + - + message: "#^Call to protected method getRelationWithoutConstraints\\(\\) of class Illuminate\\\\Database\\\\Eloquent\\\\Builder\\\\.$#" + count: 1 + path: src/Mixins/Ordering.php + + - + message: "#^Method Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Ordering\\:\\:orderByAggregate\\(\\) invoked with 5 parameters, 0 required\\.$#" + count: 5 + path: src/Mixins/Ordering.php + + - + message: "#^Method Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Ordering\\:\\:orderByCount\\(\\) invoked with 3 parameters, 0 required\\.$#" + count: 1 + path: src/Mixins/Ordering.php + + - + message: "#^Method Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Ordering\\:\\:orderByExists\\(\\) invoked with 3 parameters, 0 required\\.$#" + count: 1 + path: src/Mixins/Ordering.php + + - + message: "#^Method Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Ordering\\:\\:orderByMax\\(\\) invoked with 4 parameters, 0 required\\.$#" + count: 1 + path: src/Mixins/Ordering.php + + - + message: "#^Method Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Ordering\\:\\:orderByMin\\(\\) invoked with 4 parameters, 0 required\\.$#" + count: 1 + path: src/Mixins/Ordering.php + + - + message: "#^Method Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Ordering\\:\\:orderBySum\\(\\) invoked with 4 parameters, 0 required\\.$#" + count: 1 + path: src/Mixins/Ordering.php + + - + message: "#^Method Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Ordering\\:\\:preventInvalidDirection\\(\\) invoked with 1 parameter, 0 required\\.$#" + count: 2 + path: src/Mixins/Ordering.php + + - + message: "#^PHPDoc tag @mixin contains generic class Illuminate\\\\Database\\\\Eloquent\\\\Builder but does not specify its types\\: TModelClass$#" + count: 1 + path: src/Mixins/Ordering.php + + - + message: "#^Parameter \\#2 \\$parentQuery of method Illuminate\\\\Database\\\\Eloquent\\\\Relations\\\\Relation\\\\:\\:getRelationExistenceQuery\\(\\) expects Illuminate\\\\Database\\\\Eloquent\\\\Builder, \\$this\\(Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Ordering\\) given\\.$#" + count: 1 + path: src/Mixins/Ordering.php + + - + message: "#^Property Illuminate\\\\Database\\\\Query\\\\Builder\\:\\:\\$orders \\(array\\) does not accept null\\.$#" + count: 1 + path: src/Mixins/Ordering.php + + - + message: "#^PHPDoc tag @mixin contains generic class Illuminate\\\\Database\\\\Eloquent\\\\Builder but does not specify its types\\: TModelClass$#" + count: 1 + path: src/Mixins/Result.php + + - + message: "#^Access to protected property Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Select\\\\:\\:\\$query\\.$#" + count: 3 + path: src/Mixins/Select.php + + - + message: "#^Anonymous function should return Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Select but returns Closure\\.$#" + count: 2 + path: src/Mixins/Select.php + + - + message: "#^Call to protected method callScope\\(\\) of class Illuminate\\\\Database\\\\Eloquent\\\\Builder\\\\.$#" + count: 1 + path: src/Mixins/Select.php + + - + message: "#^Call to protected method getRelationWithoutConstraints\\(\\) of class Illuminate\\\\Database\\\\Eloquent\\\\Builder\\\\.$#" + count: 1 + path: src/Mixins/Select.php + + - + message: "#^Call to protected method parseWithRelations\\(\\) of class Illuminate\\\\Database\\\\Eloquent\\\\Builder\\\\.$#" + count: 1 + path: src/Mixins/Select.php + + - + message: "#^Method Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Select\\\\:\\:withAggregateFunction\\(\\) invoked with 2 parameters, 0 required\\.$#" + count: 2 + path: src/Mixins/Select.php + + - + message: "#^Parameter \\#1 \\$query of method Soyhuce\\\\EloquentExtended\\\\Aggregates\\\\Contracts\\\\AggregateFunction\\\\:\\:apply\\(\\) expects Illuminate\\\\Database\\\\Eloquent\\\\Builder\\, \\$this\\(Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Select\\\\) given\\.$#" + count: 1 + path: src/Mixins/Select.php + + - + message: "#^Parameter \\#1 \\$query of method Soyhuce\\\\EloquentExtended\\\\Aggregates\\\\Contracts\\\\MultiRelationAggregate\\\\:\\:enclose\\(\\) expects Illuminate\\\\Database\\\\Eloquent\\\\Builder\\, \\$this\\(Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Select\\\\) given\\.$#" + count: 1 + path: src/Mixins/Select.php + + - + message: "#^Parameter \\#1 \\$value of static method Illuminate\\\\Support\\\\Str\\:\\:snake\\(\\) expects string, string\\|null given\\.$#" + count: 1 + path: src/Mixins/Select.php + + - + message: "#^Parameter \\#2 \\$parentQuery of method Illuminate\\\\Database\\\\Eloquent\\\\Relations\\\\Relation\\\\:\\:getRelationExistenceQuery\\(\\) expects Illuminate\\\\Database\\\\Eloquent\\\\Builder, \\$this\\(Soyhuce\\\\EloquentExtended\\\\Mixins\\\\Select\\\\) given\\.$#" + count: 1 + path: src/Mixins/Select.php + + - + message: "#^Property Illuminate\\\\Database\\\\Query\\\\Builder\\:\\:\\$orders \\(array\\) does not accept null\\.$#" + count: 1 + path: src/Mixins/Select.php + diff --git a/phpstan.neon.dist b/phpstan.neon.dist index e273d91..b381967 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -5,8 +5,6 @@ parameters: level: 8 paths: - src - - config - - database checkOctaneCompatibility: true checkModelProperties: true checkMissingIterableValueType: true diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 0ba9dba..c25ceb7 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -19,7 +19,7 @@ verbose="true" > - + tests diff --git a/src/Aggregates/AnyExists.php b/src/Aggregates/AnyExists.php new file mode 100644 index 0000000..272881e --- /dev/null +++ b/src/Aggregates/AnyExists.php @@ -0,0 +1,73 @@ + + */ +class AnyExists implements MultiRelationAggregate +{ + /** @var \Illuminate\Support\Collection */ + protected Collection $existenceQueries; + + public function __construct( + protected string $alias = 'related_exists', + ) { + $this->existenceQueries = new Collection(); + } + + public function column(): string + { + return '*'; + } + + public function expression(string $column): string + { + return $column; + } + + /** + * @phpcsSuppress SlevomatCodingStandard.Functions.UnusedParameter + */ + public function defaultAlias(string $relation, string $column): string + { + return $this->alias; + } + + /** + * @phpcsSuppress SlevomatCodingStandard.Functions.UnusedParameter + * @param \Illuminate\Database\Eloquent\Builder $query + */ + public function apply(Builder $query, QueryBuilder $aggregateQuery, string $alias): void + { + $this->existenceQueries->add($aggregateQuery); + } + + /** + * @param \Illuminate\Database\Eloquent\Builder $query + */ + public function enclose(Builder $query): void + { + $query + ->getQuery() + ->selectRaw( + sprintf( + '%s as %s', + $this->existenceQueries + ->map(fn (QueryBuilder $query) => sprintf('exists(%s)', $query->toSql())) + ->implode(' or '), + $query->getQuery()->grammar->wrap($this->alias) + ), + $this->existenceQueries + ->flatMap(fn (QueryBuilder $query) => $query->getBindings()) + ->all() + ); + $query->withCasts([$this->alias => 'bool']); + } +} diff --git a/src/Aggregates/Contracts/AggregateFunction.php b/src/Aggregates/Contracts/AggregateFunction.php new file mode 100644 index 0000000..3d7af76 --- /dev/null +++ b/src/Aggregates/Contracts/AggregateFunction.php @@ -0,0 +1,35 @@ + $query + */ + public function apply(Builder $query, QueryBuilder $aggregateQuery, string $alias): void; +} diff --git a/src/Aggregates/Contracts/MultiRelationAggregate.php b/src/Aggregates/Contracts/MultiRelationAggregate.php new file mode 100644 index 0000000..1df2b59 --- /dev/null +++ b/src/Aggregates/Contracts/MultiRelationAggregate.php @@ -0,0 +1,20 @@ + + */ +interface MultiRelationAggregate extends AggregateFunction +{ + /** + * Enclose the aggregate on the query. + * This method is executed once for all relations. + * + * @param \Illuminate\Database\Eloquent\Builder $query + */ + public function enclose(Builder $query): void; +} diff --git a/src/Aggregates/Contracts/QualifiesRelatedColumn.php b/src/Aggregates/Contracts/QualifiesRelatedColumn.php new file mode 100644 index 0000000..5b1aeeb --- /dev/null +++ b/src/Aggregates/Contracts/QualifiesRelatedColumn.php @@ -0,0 +1,10 @@ + + */ +class Implode implements AggregateFunction, QualifiesRelatedColumn +{ + private Closure $columnQualifier; + + public function __construct( + protected string $column, + protected string $glue, + protected ?string $orderBy = null, + protected ?string $direction = 'asc', + ) { + } + + public function column(): string + { + return $this->column; + } + + public function setColumnQualifier(Closure $columnQualifier): void + { + $this->columnQualifier = $columnQualifier; + } + + public function expression(string $column): string + { + if ($this->orderBy === null) { + return "string_agg({$column}, ?)"; + } + + $orderBy = ($this->columnQualifier)($this->orderBy); + + return "string_agg({$column}, ? order by {$orderBy} {$this->direction})"; + } + + public function defaultAlias(string $relation, string $column): string + { + return $relation . ' implode ' . $column; + } + + /** + * @param \Illuminate\Database\Eloquent\Builder $query + */ + public function apply(Builder $query, QueryBuilder $aggregateQuery, string $alias): void + { + $aggregateQuery->addBinding($this->glue, 'select'); + + $query->getQuery()->selectSub($aggregateQuery, $alias); + } +} diff --git a/src/Commands/SkeletonCommand.php b/src/Commands/SkeletonCommand.php deleted file mode 100644 index 6ab99d6..0000000 --- a/src/Commands/SkeletonCommand.php +++ /dev/null @@ -1,19 +0,0 @@ -comment('All done'); - - return self::SUCCESS; - } -} diff --git a/src/Concerns/LoadsAttributes.php b/src/Concerns/LoadsAttributes.php new file mode 100644 index 0000000..3cacfa6 --- /dev/null +++ b/src/Concerns/LoadsAttributes.php @@ -0,0 +1,18 @@ +newCollection([$this])->loadAttributes($closure); + + return $this; + } +} diff --git a/src/EloquentExtendedServiceProvider.php b/src/EloquentExtendedServiceProvider.php new file mode 100644 index 0000000..54f0338 --- /dev/null +++ b/src/EloquentExtendedServiceProvider.php @@ -0,0 +1,25 @@ +isEmpty()) { + return $this; + } + + $query = $this->first()->newModelQuery() + ->whereKey($this->modelKeys()) + ->select($this->first()->getKeyName()); + $query = $closure($query) ?? $query; + $models = $query->get()->keyBy($this->first()->getKeyName()); + + $attributes = Arr::except( + array_keys($models->first()->getAttributes()), + $models->first()->getKeyName() + ); + + $this->each(function ($model) use ($models, $attributes): void { + $fetchedModel = $models->get($model->getKey()); + $extraAttributes = Arr::only($fetchedModel->getAttributes(), $attributes); + + $model->forceFill($extraAttributes) + ->syncOriginalAttributes($attributes) + ->mergeCasts($fetchedModel->getCasts()); + }); + + return $this; + }; + } +} diff --git a/src/Mixins/Misc.php b/src/Mixins/Misc.php new file mode 100644 index 0000000..0cfb2dc --- /dev/null +++ b/src/Mixins/Misc.php @@ -0,0 +1,30 @@ +apply($this, $this->getModel()); + + return $this; + }; + } + + public function scoped(): Closure + { + return function (Closure $callback): self { + $result = $callback($this); + + return $result ?? $this; + }; + } +} diff --git a/src/Mixins/Ordering.php b/src/Mixins/Ordering.php new file mode 100644 index 0000000..27f4ec9 --- /dev/null +++ b/src/Mixins/Ordering.php @@ -0,0 +1,185 @@ +preventInvalidDirection($direction); + + $column = $this->getGrammar()->wrap($column); + + $this->orderByRaw("{$column} {$direction} nulls last"); + + return $this; + }; + } + + public function orderByRawNullsLast(): Closure + { + return function (string $sql): self { + $this->orderByRaw("{$sql} nulls last"); + + return $this; + }; + } + + public function orderByAggregate(): Closure + { + return function ( + string $relationName, + string $column, + string $direction = 'asc', + ?string $function = null, + ?Closure $constraints = null, + ) { + $this->preventInvalidDirection($direction); + + if ($constraints === null) { + $constraints = static function (): void { + }; + } + + $relation = $this->getRelationWithoutConstraints($relationName); + + if ($function) { + $hashedColumn = $this->getQuery()->from === $relation->getQuery()->getQuery()->from + ? "{$relation->getRelationCountHash(false)}.{$column}" + : $column; + + $wrappedColumn = $this->getQuery()->getGrammar()->wrap( + $column === '*' ? $column : $relation->getRelated()->qualifyColumn($hashedColumn) + ); + + $expression = $function === 'exists' ? $wrappedColumn : sprintf('%s(%s)', $function, $wrappedColumn); + } else { + $expression = $column; + } + + // Here, we will grab the relationship sub-query and prepare to add it to the main query + // as a sub-select. First, we'll get the "has" query and use that to get the relation + // sub-query. We'll format this relationship name and append this column if needed. + $query = $relation->getRelationExistenceQuery( + $relation->getRelated()->newQuery(), + $this, + new Expression($expression) + )->setBindings([], 'select'); + + $query->callScope($constraints); + + $query = $query->mergeConstraintsFrom($relation->getQuery())->toBase(); + + // If the query contains certain elements like orderings / more than one column selected + // then we will remove those elements from the query so that it will execute properly + // when given to the database. Otherwise, we may receive SQL errors or poor syntax. + $query->orders = null; + $query->setBindings([], 'order'); + + if (count($query->columns) > 1) { + $query->columns = [$query->columns[0]]; + $query->bindings['select'] = []; + } + + if ($function === 'exists') { + $this->orderByRaw( + sprintf('exists(%s) %s', $query->toSql(), $direction), + $query->getBindings() + ); + } else { + $this->orderBy($function ? $query : $query->limit(1), $direction); + } + + return $this; + }; + } + + public function orderByExists(): Closure + { + return function (string $relation, ?Closure $constraints = null, string $direction = 'asc') { + return $this->orderByAggregate($relation, '*', $direction, 'exists', $constraints); + }; + } + + public function orderByExistsDesc(): Closure + { + return function (string $relation, ?Closure $constraints = null) { + return $this->orderByExists($relation, $constraints, 'desc'); + }; + } + + public function orderByCount(): Closure + { + return function (string $relation, ?Closure $constraints = null, string $direction = 'asc') { + return $this->orderByAggregate($relation, '*', $direction, 'count', $constraints); + }; + } + + public function orderByCountDesc(): Closure + { + return function (string $relation, ?Closure $constraints = null) { + return $this->orderByCount($relation, $constraints, 'desc'); + }; + } + + public function orderBySum(): Closure + { + return function (string $relation, string $column, ?Closure $constraints = null, string $direction = 'asc') { + return $this->orderByAggregate($relation, $column, $direction, 'sum', $constraints); + }; + } + + public function orderBySumDesc(): Closure + { + return function (string $relation, string $column, ?Closure $constraints = null) { + return $this->orderBySum($relation, $column, $constraints, 'desc'); + }; + } + + public function orderByMin(): Closure + { + return function (string $relation, string $column, ?Closure $constraints = null, string $direction = 'asc') { + return $this->orderByAggregate($relation, $column, $direction, 'min', $constraints); + }; + } + + public function orderByMinDesc(): Closure + { + return function (string $relation, string $column, ?Closure $constraints = null) { + return $this->orderByMin($relation, $column, $constraints, 'desc'); + }; + } + + public function orderByMax(): Closure + { + return function (string $relation, string $column, ?Closure $constraints = null, string $direction = 'asc') { + return $this->orderByAggregate($relation, $column, $direction, 'max', $constraints); + }; + } + + public function orderByMaxDesc(): Closure + { + return function (string $relation, string $column, ?Closure $constraints = null) { + return $this->orderByMax($relation, $column, $constraints, 'desc'); + }; + } +} diff --git a/src/Mixins/Result.php b/src/Mixins/Result.php new file mode 100644 index 0000000..265387c --- /dev/null +++ b/src/Mixins/Result.php @@ -0,0 +1,25 @@ +toBase()->getCountForPagination(); + + if ($total === 0) { + return null; + } + + return $this->offset(mt_rand(0, $total - 1))->first(); + }; + } +} diff --git a/src/Mixins/Select.php b/src/Mixins/Select.php new file mode 100644 index 0000000..a3217a4 --- /dev/null +++ b/src/Mixins/Select.php @@ -0,0 +1,141 @@ + + */ +class Select +{ + public function withAggregateFunction(): Closure + { + /** + * @param array|array|string $relations + * @param \Soyhuce\EloquentExtended\Aggregates\Contracts\AggregateFunction + */ + return function ($relations, AggregateFunction $aggregateFunction): self { + if (empty($relations)) { + return $this; + } + + if ($this->query->columns === null) { + $this->query->select([$this->query->from . '.*']); + } + + $column = $aggregateFunction->column(); + + /** @var array $relations */ + $relations = $this->parseWithRelations(is_array($relations) ? $relations : [$relations]); + + foreach ($relations as $name => $constraints) { + // First we will determine if the name has been aliased using an "as" clause on the name + // and if it has we will extract the actual relationship name and the desired name of + // the resulting column. This allows multiple aggregates on the same relationships. + $segments = explode(' ', $name); + + unset($alias); + + if (count($segments) === 3 && Str::lower($segments[1]) === 'as') { + [$name, $alias] = [$segments[0], $segments[2]]; + } + + $relation = $this->getRelationWithoutConstraints($name); + + $columnQualifier = function (string $column) use ($relation): string { + $hashedColumn = $this->getQuery()->from === $relation->getQuery()->getQuery()->from + ? "{$relation->getRelationCountHash(false)}.{$column}" + : $column; + + return $this->getQuery()->getGrammar()->wrap( + $column === '*' ? $column : $relation->getRelated()->qualifyColumn($hashedColumn) + ); + }; + + $wrappedColumn = $columnQualifier($column); + + if ($aggregateFunction instanceof QualifiesRelatedColumn) { + $aggregateFunction->setColumnQualifier($columnQualifier); + } + + $expression = $aggregateFunction->expression($wrappedColumn); + + // Here, we will grab the relationship sub-query and prepare to add it to the main query + // as a sub-select. First, we'll get the "has" query and use that to get the relation + // sub-query. We'll format this relationship name and append this column if needed. + $query = $relation->getRelationExistenceQuery( + $relation->getRelated()->newQuery(), + $this, + new Expression($expression) + )->setBindings([], 'select'); + + $query->callScope($constraints); + + $query = $query->mergeConstraintsFrom($relation->getQuery())->toBase(); + + // If the query contains certain elements like orderings / more than one column selected + // then we will remove those elements from the query so that it will execute properly + // when given to the database. Otherwise, we may receive SQL errors or poor syntax. + $query->orders = null; + $query->setBindings([], 'order'); + + if (count($query->columns) > 1) { + $query->columns = [$query->columns[0]]; + $query->bindings['select'] = []; + } + + // Finally, we will make the proper column alias to the query and run this sub-select on + // the query builder. Then, we will return the builder instance back to the developer + // for further constraint chaining that needs to take place on the query as needed. + $alias ??= Str::snake( + preg_replace('/[^[:alnum:][:space:]_]/u', '', $aggregateFunction->defaultAlias($name, $column)) + ); + + $aggregateFunction->apply($this, $query, $alias); + } + + if ($aggregateFunction instanceof MultiRelationAggregate) { + $aggregateFunction->enclose($this); + } + + return $this; + }; + } + + public function withAnyExists(): Closure + { + /** + * @param array|array $relations + */ + return function (array $relations, string $alias = 'related_exists'): self { + return $this->withAggregateFunction($relations, new AnyExists($alias)); + }; + } + + public function withImplode(): Closure + { + /** + * @param array|array|string $relations + */ + return function ( + $relations, + string $column, + string $glue, + ?string $orderBy = null, + string $direction = 'asc', + ): self { + return $this->withAggregateFunction($relations, new Implode($column, $glue, $orderBy, $direction)); + }; + } +} diff --git a/src/NextIdeHelper/Extension.php b/src/NextIdeHelper/Extension.php new file mode 100644 index 0000000..6d5d107 --- /dev/null +++ b/src/NextIdeHelper/Extension.php @@ -0,0 +1,43 @@ +fqcn; + $builderClass = $model->queryBuilder->fqcn; + + Collection::make([ + "{$builderClass} scope(\\Illuminate\\Database\\Eloquent\\Scope \$scope)", + "{$builderClass} scoped(\\Closure \$callable)", + "{$builderClass} preventInvalidDirection(string \$direction)", + "{$builderClass} withAggregateFunction(array \$relations, \\Soyhuce\\EloquentExtended\\Aggregates\\Contracts\\AggregateFunction \$aggregateFunction)", + "{$builderClass} withAnyExists(array \$relations, string \$alias = 'related_exists')", + "{$builderClass} withImplode(array|string \$relations, string \$column, string \$glue, ?string \$orderBy = null, string \$direction = 'asc')", + "{$builderClass} orderByNullsLast(string \$column, string \$direction = 'asc')", + "{$builderClass} orderByRawNullsLast(string \$sql)", + "{$builderClass} orderByAggregate(string \$relationName, string \$column, string \$direction = 'asc', ?string \$function = null, ?\\Closure \$constraints = null)", + "{$builderClass} orderByExists(string \$relation, ?\\Closure \$constraints = null, string \$direction = 'asc')", + "{$builderClass} orderByExistsDesc(string \$relation, ?\\Closure \$constraints = null)", + "{$builderClass} orderByCount(string \$relation, ?\\Closure \$constraints = null, string \$direction = 'asc')", + "{$builderClass} orderByCountDesc(string \$relation, ?\\Closure \$constraints = null)", + "{$builderClass} orderBySum(string \$relation, string \$column, ?\\Closure \$constraints = null, string \$direction = 'asc')", + "{$builderClass} orderBySumDesc(string \$relation, string \$column, ?\\Closure \$constraints = null)", + "{$builderClass} orderByMin(string \$relation, string \$column, ?\\Closure \$constraints = null, string \$direction = 'asc')", + "{$builderClass} orderByMinDesc(string \$relation, string \$column, ?\\Closure \$constraints = null)", + "{$builderClass} orderByMax(string \$relation, string \$column, ?\\Closure \$constraints = null, string \$direction = 'asc')", + "{$builderClass} orderByMaxDesc(string \$relation, string \$column, ?\\Closure \$constraints = null)", + "{$modelClass}|null random()", + ]) + ->map(fn (string $method) => " * @method {$method}") + ->each(function (string $method) use ($model): void { + $model->queryBuilder->addExtra($method); + }); + } +} diff --git a/src/Skeleton.php b/src/Skeleton.php deleted file mode 100755 index eb72cf3..0000000 --- a/src/Skeleton.php +++ /dev/null @@ -1,7 +0,0 @@ -name('skeleton') - ->hasConfigFile() - ->hasViews() - ->hasMigration('create_skeleton_table') - ->hasCommand(SkeletonCommand::class); - } -} diff --git a/tests/CollectionMixinTest.php b/tests/CollectionMixinTest.php new file mode 100644 index 0000000..f05c79c --- /dev/null +++ b/tests/CollectionMixinTest.php @@ -0,0 +1,31 @@ +hasPosts()->createOne(); + $reader = User::factory()->createOne(); + + Collection::make([$author, $reader])->loadAttributes( + fn (Builder $query) => $query->withAnyExists(['posts', 'publishedPosts']) + ); + + $this->assertTrue($author->related_exists); + $this->assertFalse($reader->related_exists); + } +} diff --git a/tests/ExampleTest.php b/tests/ExampleTest.php deleted file mode 100644 index e38d639..0000000 --- a/tests/ExampleTest.php +++ /dev/null @@ -1,5 +0,0 @@ -toBeTrue(); -}); diff --git a/tests/Fixtures/Post.php b/tests/Fixtures/Post.php new file mode 100644 index 0000000..8e83ec5 --- /dev/null +++ b/tests/Fixtures/Post.php @@ -0,0 +1,17 @@ +belongsTo(User::class); + } +} diff --git a/tests/Fixtures/PostFactory.php b/tests/Fixtures/PostFactory.php new file mode 100644 index 0000000..6ac309b --- /dev/null +++ b/tests/Fixtures/PostFactory.php @@ -0,0 +1,27 @@ + + */ + public function definition(): array + { + return [ + 'user_id' => User::factory(), + 'title' => $this->faker->words(asText: true), + 'published' => $this->faker->boolean, + ]; + } + + public function published(bool $published = true): self + { + return $this->state(['published' => $published]); + } +} diff --git a/tests/Fixtures/User.php b/tests/Fixtures/User.php new file mode 100644 index 0000000..5034e02 --- /dev/null +++ b/tests/Fixtures/User.php @@ -0,0 +1,24 @@ +hasMany(Post::class); + } + + public function publishedPosts(): HasMany + { + return $this->hasMany(Post::class)->where('published', true); + } +} diff --git a/tests/Fixtures/UserFactory.php b/tests/Fixtures/UserFactory.php new file mode 100644 index 0000000..e90d9f3 --- /dev/null +++ b/tests/Fixtures/UserFactory.php @@ -0,0 +1,20 @@ + + */ + public function definition(): array + { + return [ + 'name' => $this->faker->name, + ]; + } +} diff --git a/tests/LoadsAttributesTest.php b/tests/LoadsAttributesTest.php new file mode 100644 index 0000000..14ece20 --- /dev/null +++ b/tests/LoadsAttributesTest.php @@ -0,0 +1,28 @@ +hasPosts()->createOne(); + + $author->loadAttributes( + fn (Builder $query) => $query->withAnyExists(['posts', 'publishedPosts']) + ); + + $this->assertTrue($author->related_exists); + } +} diff --git a/tests/MiscTest.php b/tests/MiscTest.php new file mode 100644 index 0000000..077ec96 --- /dev/null +++ b/tests/MiscTest.php @@ -0,0 +1,61 @@ +createOne(['role' => 'admin']); + $user = User::factory()->createOne(['role' => 'user']); + + $scope = new class() implements Scope { + public function apply(Builder $builder, Model $model) + { + return $builder->orderByDesc('role'); + } + }; + + $this->assertEquals( + [$user->id, $admin->id], + User::query()->scope($scope)->pluck('id')->all() + ); + } + + /** + * @test + * @covers ::scoped + */ + public function queryCanBeConfiguredViaClosure(): void + { + $admin = User::factory()->createOne(['role' => 'admin']); + $user = User::factory()->createOne(['role' => 'user']); + + $this->assertEquals( + [$user->id, $admin->id], + User::query()->scoped(fn (Builder $query) => $query->orderByDesc('role'))->pluck('id')->all() + ); + + $this->assertEquals( + [$admin->id, $user->id], + User::query() + ->scoped(function (Builder $query): void { + $query->orderBy('role'); + }) + ->pluck('id') + ->all() + ); + } +} diff --git a/tests/OrderingTest.php b/tests/OrderingTest.php new file mode 100644 index 0000000..74d5629 --- /dev/null +++ b/tests/OrderingTest.php @@ -0,0 +1,287 @@ +preventInvalidDirection('asc'); + User::query()->preventInvalidDirection('desc'); + + $this->assertTrue(true); + } + + /** + * @test + * @covers ::preventInvalidDirection + */ + public function otherDirectionIsInvalid(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Order direction must be "asc" or "desc".'); + + User::query()->preventInvalidDirection('foo'); + } + + /** + * @test + * @covers ::orderByNullsLast + */ + public function orderByNullLast(): void + { + $sqliteVersion = User::query()->getConnection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION); + + if (version_compare($sqliteVersion, '3.31', '<')) { + $this->markTestSkipped('Sqlite < 3.31 does not support nulls last'); + } + + $admin = User::factory()->createOne(['role' => 'admin']); + $user = User::factory()->createOne(['role' => 'user']); + $none = User::factory()->createOne(['role' => null]); + + $this->assertEquals( + [$admin->id, $user->id, $none->id], + User::query()->orderByNullsLast('role')->pluck('id')->all() + ); + + $this->assertEquals( + [$user->id, $admin->id, $none->id], + User::query()->orderByNullsLast('role', 'desc')->pluck('id')->all() + ); + } + + /** + * @test + * @covers ::orderByRawNullsLast + */ + public function orderByRawNullsLast(): void + { + $sqliteVersion = User::query()->getConnection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION); + + if (version_compare($sqliteVersion, '3.31', '<')) { + $this->markTestSkipped('Sqlite < 3.31 does not support nulls last'); + } + + $admin = User::factory()->createOne(['role' => 'admin']); + $user = User::factory()->createOne(['role' => 'user']); + $none = User::factory()->createOne(['role' => null]); + + $this->assertEquals( + [$admin->id, $user->id, $none->id], + User::query()->orderByRawNullsLast('UPPER("role")')->pluck('id')->all() + ); + + $this->assertEquals( + [$user->id, $admin->id, $none->id], + User::query()->orderByRawNullsLast('UPPER("role") desc')->pluck('id')->all() + ); + } + + /** + * @test + * @covers ::orderByExists + */ + public function orderByExists(): void + { + $first = User::factory()->has(Post::factory()->published())->createOne(); + $second = User::factory()->createOne(); + $third = User::factory()->has(Post::factory(2)->published(false))->createOne(); + + $this->assertEquals( + [$second->id, $first->id, $third->id], + User::query()->orderByExists('posts')->orderBy('id')->pluck('id')->all() + ); + + $this->assertEquals( + [$first->id, $third->id, $second->id], + User::query()->orderByExistsDesc('posts')->orderBy('id')->pluck('id')->all() + ); + + $this->assertEquals( + [$second->id, $third->id, $first->id], + User::query() + ->orderByExists('posts', fn ($query) => $query->where('published', true)) + ->orderBy('id') + ->pluck('id') + ->all() + ); + + $this->assertEquals( + [$first->id, $second->id, $third->id], + User::query() + ->orderByExistsDesc('posts', fn ($query) => $query->where('published', true)) + ->orderBy('id') + ->pluck('id') + ->all() + ); + } + + /** + * @test + * @covers ::orderByExists + */ + public function orderByCount(): void + { + $first = User::factory()->has(Post::factory()->published())->createOne(); + $second = User::factory()->createOne(); + $third = User::factory()->has(Post::factory(2)->published(false))->createOne(); + + $this->assertEquals( + [$second->id, $first->id, $third->id], + User::query()->orderByCount('posts')->orderBy('id')->pluck('id')->all() + ); + + $this->assertEquals( + [$third->id, $first->id, $second->id], + User::query()->orderByCountDesc('posts')->orderBy('id')->pluck('id')->all() + ); + + $this->assertEquals( + [$second->id, $third->id, $first->id], + User::query() + ->orderByCount('posts', fn ($query) => $query->where('published', true)) + ->orderBy('id') + ->pluck('id') + ->all() + ); + + $this->assertEquals( + [$first->id, $second->id, $third->id], + User::query() + ->orderByCountDesc('posts', fn ($query) => $query->where('published', true)) + ->orderBy('id') + ->pluck('id') + ->all() + ); + } + + /** + * @test + * @covers ::orderByExists + */ + public function orderBySum(): void + { + $first = User::factory()->has(Post::factory()->published())->createOne(); + $second = User::factory()->createOne(); + $third = User::factory()->has(Post::factory(2)->published(false))->createOne(); + + $this->assertEquals( + [$second->id, $first->id, $third->id], + User::query()->withSum('posts', 'id')->orderBySum('posts', 'id')->orderBy('id')->pluck('id')->all() + ); + + $this->assertEquals( + [$third->id, $first->id, $second->id], + User::query()->orderBySumDesc('posts', 'id')->orderBy('id')->pluck('id')->all() + ); + + $this->assertEquals( + [$second->id, $third->id, $first->id], + User::query() + ->orderBySum('posts', 'id', fn ($query) => $query->where('published', true)) + ->orderBy('id') + ->pluck('id') + ->all() + ); + + $this->assertEquals( + [$first->id, $second->id, $third->id], + User::query() + ->orderBySumDesc('posts', 'id', fn ($query) => $query->where('published', true)) + ->orderBy('id') + ->pluck('id') + ->all() + ); + } + + /** + * @test + * @covers ::orderByExists + */ + public function orderByMin(): void + { + $first = User::factory()->has(Post::factory()->published(false))->createOne(); + $second = User::factory()->createOne(); + $third = User::factory()->has(Post::factory(2)->published())->createOne(); + Post::factory()->for($first)->published(false)->createOne(); + Post::factory()->published()->for($second)->createOne(); + + $this->assertEquals( + [$first->id, $third->id, $second->id], + User::query()->orderByMin('posts', 'id')->pluck('id')->all() + ); + + $this->assertEquals( + [$second->id, $third->id, $first->id], + User::query()->orderByMinDesc('posts', 'id')->pluck('id')->all() + ); + + $this->assertEquals( + [$first->id, $third->id, $second->id], + User::query() + ->orderByMin('posts', 'id', fn ($query) => $query->where('published', true)) + ->pluck('id') + ->all() + ); + + $this->assertEquals( + [$second->id, $third->id, $first->id], + User::query() + ->orderByMinDesc('posts', 'id', fn ($query) => $query->where('published', true)) + ->pluck('id') + ->all() + ); + } + + /** + * @test + * @covers ::orderByExists + */ + public function orderByMax(): void + { + $first = User::factory()->has(Post::factory()->published(false))->createOne(); + $second = User::factory()->createOne(); + $third = User::factory()->has(Post::factory(2)->published())->createOne(); + Post::factory()->for($first)->published(false)->createOne(); + Post::factory()->published()->for($second)->createOne(); + + $this->assertEquals( + [$third->id, $first->id, $second->id], + User::query()->orderByMax('posts', 'id')->pluck('id')->all() + ); + + $this->assertEquals( + [$second->id, $first->id, $third->id], + User::query()->orderByMaxDesc('posts', 'id')->pluck('id')->all() + ); + + $this->assertEquals( + [$first->id, $third->id, $second->id], + User::query() + ->orderByMax('posts', 'id', fn ($query) => $query->where('published', true)) + ->pluck('id') + ->all() + ); + + $this->assertEquals( + [$second->id, $third->id, $first->id], + User::query() + ->orderByMaxDesc('posts', 'id', fn ($query) => $query->where('published', true)) + ->pluck('id') + ->all() + ); + } +} diff --git a/tests/Pest.php b/tests/Pest.php index 916cc0f..4ddeeab 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,5 @@ in(__DIR__); diff --git a/tests/ResultTest.php b/tests/ResultTest.php new file mode 100644 index 0000000..a8e4af8 --- /dev/null +++ b/tests/ResultTest.php @@ -0,0 +1,42 @@ +create(); + + for ($i = 0; $i < 10; $i++) { + $first = User::query()->random(); + $second = User::query()->random(); + + if (!$first->is($second)) { + $this->assertTrue(true); + + return; + } + } + + $this->assertTrue(false, 'Failed to get 2 randoms users'); + } + + /** + * @test + * @covers ::random + */ + public function resultCanBeNull(): void + { + $this->assertNull(User::query()->random()); + } +} diff --git a/tests/SelectTest.php b/tests/SelectTest.php new file mode 100644 index 0000000..5047155 --- /dev/null +++ b/tests/SelectTest.php @@ -0,0 +1,56 @@ +hasPosts()->createOne(); + $reader = User::factory()->createOne(); + + $users = User::query()->withAnyExists(['posts', 'publishedPosts'])->get(); + + $this->assertTrue($users->find($author->id)->related_exists); + $this->assertFalse($users->find($reader->id)->related_exists); + } + + /** + * @test + * @covers ::withImplode + */ + public function withImplode(): void + { + $query = User::query()->withImplode('posts', 'title', ' - '); + + $this->assertEquals( + 'select "users".*, (select string_agg("posts"."title", ?) from "posts" where "users"."id" = "posts"."user_id") as "posts_implode_title" from "users"', + $query->toSql() + ); + $this->assertEquals([' - '], $query->getBindings()); + } + + /** + * @test + * @covers ::withImplode + */ + public function withImplodeWithOrder(): void + { + $query = User::query()->withImplode('posts', 'title', ' - ', 'id', 'desc'); + + $this->assertEquals( + 'select "users".*, (select string_agg("posts"."title", ? order by "posts"."id" desc) from "posts" where "users"."id" = "posts"."user_id") as "posts_implode_title" from "users"', + $query->toSql() + ); + $this->assertEquals([' - '], $query->getBindings()); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php index af769de..7493091 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,10 +1,10 @@ 'VendorName\\Skeleton\\Database\\Factories\\' . class_basename($modelName) . 'Factory' - ); + $this->loadMigrationsFrom(__DIR__ . '/migrations'); + Factory::guessFactoryNamesUsing(fn (string $modelName) => $modelName . 'Factory'); } protected function getPackageProviders($app) { return [ - SkeletonServiceProvider::class, + EloquentExtendedServiceProvider::class, ]; } - - public function getEnvironmentSetUp($app): void - { - config()->set('database.default', 'testing'); - - /* - $migration = include __DIR__.'/../database/migrations/create_skeleton_table.php.stub'; - $migration->up(); - */ - } } diff --git a/tests/migrations/2021_04_26_120300_create_users_table.php b/tests/migrations/2021_04_26_120300_create_users_table.php new file mode 100644 index 0000000..4bb76eb --- /dev/null +++ b/tests/migrations/2021_04_26_120300_create_users_table.php @@ -0,0 +1,24 @@ +id(); + + $table->string('name'); + $table->string('role')->nullable(); + + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('users'); + } +} diff --git a/tests/migrations/2021_04_26_120400_create_posts_table.php b/tests/migrations/2021_04_26_120400_create_posts_table.php new file mode 100644 index 0000000..86b03db --- /dev/null +++ b/tests/migrations/2021_04_26_120400_create_posts_table.php @@ -0,0 +1,26 @@ +id(); + + $table->foreignId('user_id')->references('id')->on('users')->cascadeOnDelete(); + + $table->string('title'); + $table->boolean('published'); + + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('users'); + } +}