From a1e0828f9ac6e494290d16172b6a58f1f27d20fc Mon Sep 17 00:00:00 2001 From: Sairahcaz Date: Sat, 8 Apr 2023 22:22:05 +0200 Subject: [PATCH] Date Scopes V1 --- .github/ISSUE_TEMPLATE/config.yml | 8 +- .../workflows/fix-php-code-style-issues.yml | 24 -- .github/workflows/run-tests.yml | 5 +- CHANGELOG.md | 2 +- LICENSE.md | 2 +- README.md | 223 ++++++++++++--- composer.json | 30 +- config/date-scopes.php | 20 ++ config/skeleton.php | 6 - configure.php | 266 ------------------ database/factories/ModelFactory.php | 19 -- .../migrations/create_skeleton_table.php.stub | 24 -- phpstan.neon.dist | 1 - phpunit.xml.dist | 2 +- resources/views/.gitkeep | 0 src/Commands/SkeletonCommand.php | 19 -- src/DateException.php | 13 + src/DateRange.php | 27 ++ src/DateScopes.php | 164 +++++++++++ src/Facades/Skeleton.php | 16 -- ...p => LaravelDateScopesServiceProvider.php} | 12 +- src/Skeleton.php | 7 - tests/ExampleTest.php | 6 + tests/Pest.php | 2 +- tests/TestCase.php | 10 +- 25 files changed, 456 insertions(+), 452 deletions(-) delete mode 100644 .github/workflows/fix-php-code-style-issues.yml create mode 100644 config/date-scopes.php delete mode 100644 config/skeleton.php delete mode 100644 configure.php delete mode 100644 database/factories/ModelFactory.php delete mode 100644 database/migrations/create_skeleton_table.php.stub delete mode 100644 resources/views/.gitkeep delete mode 100644 src/Commands/SkeletonCommand.php create mode 100644 src/DateException.php create mode 100644 src/DateRange.php create mode 100755 src/DateScopes.php delete mode 100644 src/Facades/Skeleton.php rename src/{SkeletonServiceProvider.php => LaravelDateScopesServiceProvider.php} (51%) delete mode 100755 src/Skeleton.php diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index ea26ad4..080406f 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/laracraft-tech/laravel-date-scopes/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/laracraft-tech/laravel-date-scopes/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/laracraft-tech/laravel-date-scopes/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/laracraft-tech/laravel-date-scopes/issues/new about: Report a reproducible bug diff --git a/.github/workflows/fix-php-code-style-issues.yml b/.github/workflows/fix-php-code-style-issues.yml deleted file mode 100644 index f769382..0000000 --- a/.github/workflows/fix-php-code-style-issues.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: Fix PHP code style issues - -on: - push: - paths: - - '**.php' - -jobs: - php-code-styling: - runs-on: ubuntu-latest - - steps: - - name: Checkout code - uses: actions/checkout@v3 - with: - ref: ${{ github.head_ref }} - - - name: Fix PHP code style issues - uses: aglipanci/laravel-pint-action@2.2.0 - - - name: Commit changes - uses: stefanzweifel/git-auto-commit-action@v4 - with: - commit_message: Fix styling diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 08cc9ab..e569c77 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -14,9 +14,12 @@ jobs: matrix: os: [ubuntu-latest, windows-latest] php: [8.2, 8.1] - laravel: [9.*] + laravel: [10.*, 9.*] stability: [prefer-lowest, prefer-stable] include: + - laravel: 10.* + testbench: 8.* + carbon: ^2.63 - laravel: 9.* testbench: 7.* carbon: ^2.63 diff --git a/CHANGELOG.md b/CHANGELOG.md index 87b3242..1c92e54 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-date-scopes` will be documented in this file. diff --git a/LICENSE.md b/LICENSE.md index 58c9ad4..1eeefdf 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) :vendor_name +Copyright (c) laracraft-tech 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 4b1e2fe..455e9b5 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,220 @@ -# :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) -[![Tests](https://github.com/:vendor_slug/:package_slug/actions/workflows/run-tests.yml/badge.svg?branch=main)](https://github.com/:vendor_slug/:package_slug/actions/workflows/run-tests.yml) -[![Check & fix styling](https://github.com/:vendor_slug/:package_slug/actions/workflows/fix-php-code-style-issues.yml/badge.svg?branch=main)](https://github.com/:vendor_slug/:package_slug/actions/workflows/fix-php-code-style-issues.yml) -[![License](https://img.shields.io/packagist/l/: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 this 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. -4. If you need help creating a package, consider picking up our Laravel Package Training video course. ---- - -This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. +# Laravel Date Scopes + +[![Latest Version on Packagist](https://img.shields.io/packagist/v/laracraft-tech/laravel-date-scopes.svg?style=flat-square)](https://packagist.org/packages/laracraft-tech/laravel-date-scopes) +[![Tests](https://github.com/laracraft-tech/laravel-date-scopes/actions/workflows/run-tests.yml/badge.svg?branch=main)](https://github.com/laracraft-tech/laravel-date-scopes/actions/workflows/run-tests.yml) +[![License](https://img.shields.io/packagist/l/laracraft-tech/laravel-date-scopes.svg?style=flat-square)](https://packagist.org/packages/laracraft-tech/laravel-date-scopes) + + +The package provides a big range of useful date scopes for your Laravel Eloquent models! ## Installation You can install the package via composer: ```bash -composer require :vendor_slug/:package_slug +composer require laracraft-tech/laravel-date-scopes ``` -You can publish and run the migrations with: +## Configuration -```bash -php artisan vendor:publish --tag=":package_slug-migrations" -php artisan migrate -``` +### Inclusive/Exclusive + +In **statistics**, when asking for "the last 7 days", the current day may or may not be included +in the calculation depending on the context and the specific requirements of the analysis. + +If you want to **include** the current day in the calculation, you would generally use an **inclusive** range, +meaning that you would include records created on the **current day** as well as records +created in the previous 6 days. + +If you want to **exclude** the current day in the calculation, you would generally use an **exclusive** range, +meaning that you would include records created in the previous 7 days, +but not records created on the **current day**. + +Ultimately, it **depends** on the context and what you're trying to achieve with your data. +It's always a good idea to clarify the requirements and expectations with stakeholders +to ensure that you're including or excluding the correct records. + +The same **concept** applies to other time intervals like weeks, months, quarters, and years etc. + +The default for this package is **exclusive** approach, +which means when you for instance query for the last 7 days it will **not include** the current day! +You can change the default if you need in the published config file. + +### Config You can publish the config file with: ```bash -php artisan vendor:publish --tag=":package_slug-config" +php artisan vendor:publish --tag="laravel-date-scopes-config" ``` This is the contents of the published config file: ```php return [ + /** + * If you want to include the current day/week/month/year etc. in the range, + * you could use the inclusive range here as a default. + * Note that you can also optionally specify it for quite every scope we offer + * directly when using the scope: + * Transaction::ofLast7Days(DateRange::INCLUSIVE); (this works for all but the singular "ofLast"-scopes) + * This will do an inclusive query, even though the global default range here is set to exclusive. + */ + 'default_range' => env('DATE_SCOPES_DEFAULT_RANGE', DateRange::EXCLUSIVE->value), + + /** + * If you have a custom created_at column name, change it here. + */ + 'created_column' => env('DATE_SCOPES_CREATED_COLUMN', 'created_at'), ]; ``` -Optionally, you can publish the views using +If you want to change the default range to inclusive set `DATE_SCOPES_DEFAULT_RANGE=inclusive` in your `.env`. -```bash -php artisan vendor:publish --tag=":package_slug-views" +## Scopes + +- [`seconds`](#seconds) +- [`minutes`](#minutes) +- [`hours`](#hours) +- [`months`](#months) +- [`quarters`](#quarters) +- [`years`](#years) +- [`decades`](#decades) +- [`millenniums`](#millenniums) +- [`toNow/toDate`](#toNowtoDate) + +Let's assume you have an `Transaction` model class. +Now when you give it the `DateScopes` trait, you can use the following scopes: + +```php +use LaracraftTech\LaravelDateScopes\DateScopes; + +class Transaction extends Model +{ + use DateScopes; +} +``` + +### Seconds + +```php +// query by SECONDS +Transaction::ofLastSecond(); // query transactions created during the last second +Transaction::ofLast15Seconds(); // query transactions created during the last 15 seconds +Transaction::ofLast30Seconds(); // query transactions created during the last 30 seconds +Transaction::ofLast45Seconds(); // query transactions created during the last 45 seconds +Transaction::ofLast60Seconds(); // query transactions created during the last 60 seconds +Transaction::ofLastSeconds(120); // query transactions created during the last N seconds +``` + +### Minutes + +```php +// query by MINUTES +Transaction::ofLastMinute(); // query transactions created during the last minute +Transaction::ofLast15Minutes(); // query transactions created during the last 15 minutes +Transaction::ofLast30Minutes(); // query transactions created during the last 30 minutes +Transaction::ofLast45Minutes(); // query transactions created during the last 45 minutes +Transaction::ofLast60Minutes(); // query transactions created during the last 60 minutes +Transaction::ofLastMinutes(120); // query transactions created during the last N minutes +``` + +### Hours + +```php +// query by HOURS +Transaction::ofLastHour(); // query transactions created during the last hour +Transaction::ofLast6Hours(); // query transactions created during the last 6 hours +Transaction::ofLast12Hours(); // query transactions created during the last 12 hours +Transaction::ofLast18Hours(); // query transactions created during the last 18 hours +Transaction::ofLast24Hours(); // query transactions created during the last 24 hours +Transaction::ofLastHours(48); // query transactions created during the last N hours +``` + +### Days + +```php +// query by DAYS +Transaction::ofToday(); // query transactions created today +Transaction::ofYesterday(); // query transactions created yesterday +Transaction::ofLast7Days(); // query transactions created during the last 7 days +Transaction::ofLast21Days(); // query transactions created during the last 21 days +Transaction::ofLast30Days(); // query transactions created during the last 30 days +Transaction::ofLastDays(60); // query transactions created during the last N days +``` + +### Weeks + +```php +// query by WEEKS +Transaction::ofLastWeek(); // query transactions created during the last week +Transaction::ofLast2Weeks(); // query transactions created during the last 2 weeks +Transaction::ofLast3Weeks(); // query transactions created during the last 3 weeks +Transaction::ofLast4Weeks(); // query transactions created during the last 4 weeks +Transaction::ofLastWeeks(8); // query transactions created during the last N weeks +``` + +### Months + +```php +// query by MONTHS +Transaction::ofLastMonth(); // query transactions created during the last month +Transaction::ofLast3Months(); // query transactions created during the last 3 months +Transaction::ofLast6Months(); // query transactions created during the last 6 months +Transaction::ofLast9Months(); // query transactions created during the last 9 months +Transaction::ofLast12Months(); // query transactions created during the last 12 months +Transaction::ofLastMonths(24); // query transactions created during the last N months +``` + +### Quarter + +```php +// query by QUARTERS +Transaction::ofLastQuarter(); // query transactions created during the last quarter +Transaction::ofLast2Quarters(); // query transactions created during the last 2 quarters +Transaction::ofLast3Quarters(); // query transactions created during the last 3 quarters +Transaction::ofLast4Quarters(); // query transactions created during the last 4 quarters +Transaction::ofLastQuarters(8); // query transactions created during the last N quarters +``` + +### Years + +```php +// query by YEARS +Transaction::ofLastYear(); // query transactions created during the last year +Transaction::ofLastYears(2); // query transactions created during the last N years +``` + +### Decades + +```php +// query by DECADES +Transaction::ofLastDecade(); // query transactions created during the last decade +Transaction::ofLastDecades(2); // query transactions created during the last N decades +``` + +### Millennium + +```php +// query by MILLENNIUM +Transaction::ofLastMillennium(); // query transactions created during the last millennium +Transaction::ofLastMillenniums(2); // query transactions created during the last N millenniums ``` -## Usage +### toNow/toDate ```php -$variable = new VendorName\Skeleton(); -echo $variable->echoPhrase('Hello, VendorName!'); +// query by toNow/toDate +Transaction::secondToNow(); // query transactions created during the start of the current second to now (not really usefull I guess) +Transaction::minuteToNow(); // query transactions created during the start of the current minute to now +Transaction::hourToNow(); // query transactions created during the start of the current hour to now +Transaction::dayToNow(); // query transactions created during the start of the current day to now +Transaction::weekToDate(); // query transactions created during the start of the current week to now +Transaction::monthToDate(); // query transactions created during the start of the current month to now +Transaction::quarterToDate(); // query transactions created during the start of the current quarter to now +Transaction::yearToDate(); // query transactions created during the start of the current year to now +Transaction::decadeToDate(); // query transactions created during the start of the current decade to now +Transaction::millenniumToDate(); // query transactions created during the start of the current millennium to now ``` ## Testing @@ -78,7 +237,7 @@ Please review [our security policy](../../security/policy) on how to report secu ## Credits -- [:author_name](https://github.com/:author_username) +- [Zacharias Creutznacher](https://github.com/laracraft-tech) - [All Contributors](../../contributors) ## License diff --git a/composer.json b/composer.json index a648a49..af6ea61 100644 --- a/composer.json +++ b/composer.json @@ -1,27 +1,26 @@ { - "name": ":vendor_slug/:package_slug", - "description": ":package_description", + "name": "laracraft-tech/laravel-date-scopes", + "description": "Some useful date scopes for your Laravel Eloquent models!", "keywords": [ - ":vendor_name", + "laracraft-tech", "laravel", - ":package_slug" + "laravel-date-scopes" ], - "homepage": "https://github.com/:vendor_slug/:package_slug", + "homepage": "https://github.com/laracraft-tech/laravel-date-scopes", "license": "MIT", "authors": [ { - "name": ":author_name", - "email": "author@domain.com", + "name": "Zacharias Creutznacher", + "email": "zacharias@laracraft.tech", "role": "Developer" } ], "require": { "php": "^8.1", "spatie/laravel-package-tools": "^1.13.0", - "illuminate/contracts": "^9.0" + "illuminate/contracts": "^9.0 || ^10.0" }, "require-dev": { - "laravel/pint": "^1.0", "nunomaduro/collision": "^7.9", "nunomaduro/larastan": "^2.0.1", "orchestra/testbench": "^8.0", @@ -34,21 +33,20 @@ }, "autoload": { "psr-4": { - "VendorName\\Skeleton\\": "src", - "VendorName\\Skeleton\\Database\\Factories\\": "database/factories" + "LaracraftTech\\LaravelDateScopes\\": "src", + "LaracraftTech\\LaravelDateScopes\\Database\\Factories\\": "database/factories" } }, "autoload-dev": { "psr-4": { - "VendorName\\Skeleton\\Tests\\": "tests" + "LaracraftTech\\LaravelDateScopes\\Tests\\": "tests" } }, "scripts": { "post-autoload-dump": "@php ./vendor/bin/testbench package:discover --ansi", "analyse": "vendor/bin/phpstan analyse", "test": "vendor/bin/pest", - "test-coverage": "vendor/bin/pest --coverage", - "format": "vendor/bin/pint" + "test-coverage": "vendor/bin/pest --coverage" }, "config": { "sort-packages": true, @@ -60,10 +58,10 @@ "extra": { "laravel": { "providers": [ - "VendorName\\Skeleton\\SkeletonServiceProvider" + "LaracraftTech\\LaravelDateScopes\\LaravelDateScopesServiceProvider" ], "aliases": { - "Skeleton": "VendorName\\Skeleton\\Facades\\Skeleton" + "LaravelDateScopes": "LaracraftTech\\LaravelDateScopes\\Facades\\LaravelDateScopes" } } }, diff --git a/config/date-scopes.php b/config/date-scopes.php new file mode 100644 index 0000000..5c94f51 --- /dev/null +++ b/config/date-scopes.php @@ -0,0 +1,20 @@ + env('DATE_SCOPES_DEFAULT_RANGE', DateRange::EXCLUSIVE->value), + + /** + * If you have a custom created_at column name, change it here. + */ + 'created_column' => env('DATE_SCOPES_CREATED_COLUMN', 'created_at'), +]; diff --git a/config/skeleton.php b/config/skeleton.php deleted file mode 100644 index 7e74186..0000000 --- a/config/skeleton.php +++ /dev/null @@ -1,6 +0,0 @@ - $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 = str_replace('-', '', 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); -$useLaravelPint = confirm('Enable Laravel Pint?', true); -$useDependabot = confirm('Enable Dependabot?', true); -$useLaravelRay = confirm('Use Ray for debugging?', 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 Laravel/Pint : '.($useLaravelPint ? 'yes' : 'no')); -writeln('Use Larastan/PhpStan : '.($usePhpStan ? 'yes' : 'no')); -writeln('Use Dependabot : '.($useDependabot ? 'yes' : 'no')); -writeln('Use Ray App : '.($useLaravelRay ? '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 (! $useLaravelPint) { - safeUnlink(__DIR__.'/.github/workflows/fix-php-code-style-issues.yml'); - safeUnlink(__DIR__.'/pint.json'); -} - -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 (! $useDependabot) { - safeUnlink(__DIR__.'/.github/dependabot.yml'); - safeUnlink(__DIR__.'/.github/workflows/dependabot-auto-merge.yml'); -} - -if (! $useLaravelRay) { - remove_composer_deps(['spatie/laravel-ray']); -} - -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 deleted file mode 100644 index c51604f..0000000 --- a/database/factories/ModelFactory.php +++ /dev/null @@ -1,19 +0,0 @@ -id(); - - // add fields - - $table->timestamps(); - }); - } - - public function down(): void - { - Schema::dropIfExists('migration_table_name_table'); - } -}; diff --git a/phpstan.neon.dist b/phpstan.neon.dist index a91953b..e005ac7 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -6,7 +6,6 @@ parameters: paths: - src - config - - database tmpDir: build/phpstan checkOctaneCompatibility: true checkModelProperties: true diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 3bbe22a..4151ab4 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -19,7 +19,7 @@ verbose="true" > - + tests diff --git a/resources/views/.gitkeep b/resources/views/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Commands/SkeletonCommand.php b/src/Commands/SkeletonCommand.php deleted file mode 100644 index 3e5f628..0000000 --- a/src/Commands/SkeletonCommand.php +++ /dev/null @@ -1,19 +0,0 @@ -comment('All done'); - - return self::SUCCESS; - } -} diff --git a/src/DateException.php b/src/DateException.php new file mode 100644 index 0000000..93802e3 --- /dev/null +++ b/src/DateException.php @@ -0,0 +1,13 @@ + now()->$startFunc()->$subFunc($value), + 'to' => now()->$endFunc()->$subFunc($sub), + ]; + } else { + $range = [ + 'from' => now()->$startFunc()->$subFunc($value - $sub), + 'to' => now()->$endFunc(), + ]; + } + + dd(collect($range)->transform(fn ($item) => $item->format('Y-m-d H:i:s'))); + + return $query->whereBetween(config('date-scopes.created_column'), $range); + } + + // START SECONDS + public function scopeOfLastSecond(Builder $query): Builder {return $query->ofLastSeconds(1);} + public function scopeOfLast15Seconds(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastSeconds(15, $customRange);} + public function scopeOfLast30Seconds(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastSeconds(30, $customRange);} + public function scopeOfLast45Seconds(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastSeconds(45, $customRange);} + public function scopeOfLast60Seconds(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastSeconds(60, $customRange);} + + public function scopeOfLastSeconds(Builder $query, int $seconds, DateRange $customRange = null): Builder + { + return $query->ofLastUnit('second', $seconds, $customRange); + } + + // START MINUTES + public function scopeOfLastMinute(Builder $query): Builder {return $query->ofLastMinutes(1);} + public function scopeOfLast15Minutes(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastMinutes(15, $customRange);} + public function scopeOfLast30Minutes(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastMinutes(30, $customRange);} + public function scopeOfLast45Minutes(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastMinutes(45, $customRange);} + public function scopeOfLast60Minutes(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastMinutes(60, $customRange);} + + public function scopeOfLastMinutes(Builder $query, int $minutes, DateRange $customRange = null): Builder + { + return $query->ofLastUnit('minute', $minutes, $customRange); + } + + // START HOURS + public function scopeOfLastHour(Builder $query): Builder {return $query->ofLastHours(1);} + public function scopeOfLast6Hours(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastHours(6, $customRange);} + public function scopeOfLast12Hours(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastHours(12, $customRange);} + public function scopeOfLast18Hours(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastHours(18, $customRange);} + public function scopeOfLast24Hours(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastHours(24, $customRange);} + + public function scopeOfLastHours(Builder $query, int $hours, DateRange $customRange = null): Builder + { + return $query->ofLastUnit('hour', $hours, $customRange); + } + + // START DAYS + public function scopeOfToday(Builder $query): Builder {return $query->ofLastDays(1, DateRange::INCLUSIVE);} + public function scopeOfYesterday(Builder $query): Builder {return $query->ofLastDays(1, DateRange::EXCLUSIVE);} + public function scopeOfLast7Days(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastDays(7, $customRange);} + public function scopeOfLast14Days(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastDays(14, $customRange);} + public function scopeOfLast21Days(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastDays(21, $customRange);} + public function scopeOfLast30Days(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastDays(30, $customRange);} + + public function scopeOfLastDays(Builder $query, int $days, DateRange $customRange = null): Builder + { + return $query->ofLastUnit('day', $days, $customRange); + } + + // START WEEKS + public function scopeOfLastWeek(Builder $query): Builder {return $query->ofLastWeeks(1);} + public function scopeOfLast2Weeks(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastWeeks(2, $customRange);} + public function scopeOfLast3Weeks(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastWeeks(3, $customRange);} + public function scopeOfLast4Weeks(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastWeeks(4, $customRange);} + + public function scopeOfLastWeeks(Builder $query, int $weeks, DateRange $customRange = null): Builder + { + return $query->ofLastUnit('week', $weeks, $customRange); + } + + // START MONTHS + public function scopeOfLastMonth(Builder $query): Builder {return $query->ofLastMonths(1);} + public function scopeOfLast3Months(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastMonths(3, $customRange);} + public function scopeOfLast6Months(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastMonths(6, $customRange);} + public function scopeOfLast9Months(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastMonths(9, $customRange);} + public function scopeOfLast12Months(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastMonths(12, $customRange);} + + public function scopeOfLastMonths(Builder $query, int $months, DateRange $customRange = null): Builder + { + return $query->ofLastUnit('month', $months, $customRange); + } + + // START QUARTER + public function scopeOfLastQuarter(Builder $query): Builder {return $query->ofLastQuarters(1);} + public function scopeOfLast2Quarters(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastQuarters(2, $customRange);} + public function scopeOfLast3Quarters(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastQuarters(3, $customRange);} + public function scopeOfLast4Quarters(Builder $query, DateRange $customRange = null): Builder {return $query->ofLastQuarters(4, $customRange);} + + public function scopeOfLastQuarters(Builder $query, int $quarters, DateRange $customRange = null): Builder + { + return $query->ofLastUnit('quarter', $quarters, $customRange); + } + + // START YEARS + public function scopeOfLastYear(Builder $query): Builder {return $query->ofLastYears(1);} + + public function scopeOfLastYears(Builder $query, int $years, DateRange $customRange = null): Builder + { + return $query->ofLastUnit('year', $years, $customRange); + } + + // START DECADE + public function scopeOfLastDecade(Builder $query): Builder {return $query->ofLastDecades(1);} + + public function scopeOfLastDecades(Builder $query, int $decades, DateRange $customRange = null): Builder + { + return $query->ofLastUnit('decade', $decades, $customRange); + } + + // START MILLENNIUM + public function scopeOfLastMillennium(Builder $query): Builder {return $query->ofLastMillenniums(1);} + + public function scopeOfLastMillenniums(Builder $query, int $millennium, DateRange $customRange = null): Builder + { + return $query->ofLastUnit('millennium', $millennium, $customRange); + } + + // START CURRENT TO NOW + + public function scopeSecondToNow(Builder $query): Builder {return $query->ofLastSeconds(1, DateRange::INCLUSIVE);} + public function scopeMinuteToNow(Builder $query): Builder {return $query->ofLastMinutes(1, DateRange::INCLUSIVE);} + public function scopeHourToNow(Builder $query): Builder {return $query->ofLastHours(1, DateRange::INCLUSIVE);} + public function scopeDayToNow(Builder $query): Builder {return $query->ofLastDays(1, DateRange::INCLUSIVE);} + public function scopeWeekToDate(Builder $query): Builder {return $query->ofLastWeeks(1, DateRange::INCLUSIVE);} + public function scopeMonthToDate(Builder $query): Builder {return $query->ofLastMonths(1, DateRange::INCLUSIVE);} + public function scopeQuarterToDate(Builder $query): Builder {return $query->ofLastQuarters(1, DateRange::INCLUSIVE);} + public function scopeYearToDate(Builder $query): Builder {return $query->ofLastYears(1, DateRange::INCLUSIVE);} + public function scopeDecadeToDate(Builder $query): Builder {return $query->ofLastDecades(1, DateRange::INCLUSIVE);} + public function scopeMillenniumToDate(Builder $query): Builder {return $query->ofLastMillenniums(1, DateRange::INCLUSIVE);} +} diff --git a/src/Facades/Skeleton.php b/src/Facades/Skeleton.php deleted file mode 100644 index 1fa9076..0000000 --- a/src/Facades/Skeleton.php +++ /dev/null @@ -1,16 +0,0 @@ -name('skeleton') - ->hasConfigFile() - ->hasViews() - ->hasMigration('create_skeleton_table') - ->hasCommand(SkeletonCommand::class); + ->name('laravel-date-scopes') + ->hasConfigFile(); } } diff --git a/src/Skeleton.php b/src/Skeleton.php deleted file mode 100755 index 66fab60..0000000 --- a/src/Skeleton.php +++ /dev/null @@ -1,7 +0,0 @@ -toBeTrue(); }); + +it('covers all cases', function () { + // Write tests for all kind of scopes + // Create a db with fixed date values + // and test with: Carbon::setTestNow('2023-01-01'); +})->todo(); diff --git a/tests/Pest.php b/tests/Pest.php index 7fe1500..c7e40db 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,5 @@ in(__DIR__); diff --git a/tests/TestCase.php b/tests/TestCase.php index d04fb0c..28c256c 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,10 +1,10 @@ 'VendorName\\Skeleton\\Database\\Factories\\'.class_basename($modelName).'Factory' + fn (string $modelName) => 'LaracraftTech\\LaravelDateScopes\\Database\\Factories\\'.class_basename($modelName).'Factory' ); } protected function getPackageProviders($app) { return [ - SkeletonServiceProvider::class, + LaravelDateScopesServiceProvider::class, ]; } @@ -29,7 +29,7 @@ public function getEnvironmentSetUp($app) config()->set('database.default', 'testing'); /* - $migration = include __DIR__.'/../database/migrations/create_skeleton_table.php.stub'; + $migration = include __DIR__.'/../database/migrations/create_laravel-date-scopes_table.php.stub'; $migration->up(); */ }