Compare commits

..
Author SHA1 Message Date
Stephen Jason Wang cc26683e8e fix: strip redundant builder @param tags for optional scalar defaults (#1785) 2026-08-04 14:28:01 +02:00
Thomas GnandtandClaude Opus 4.7 5060909c37 fix: Don't force |null on BelongsTo relations using ->withTrashed() (#1783)
When the related model uses SoftDeletes, `isRelationNullable()` was
forcing the BelongsTo relation type to nullable even if the relation
explicitly opted into trashed parents via `->withTrashed()`. Combined
with a NOT NULL FK column and DB-level FK constraint, the relation is
effectively non-nullable.

The SoftDeletes branch is now skipped when the relation has removed
the `SoftDeletingScope` and added no constraint on the qualified
`deleted_at` column. `->onlyTrashed()` and `->withoutTrashed()` keep
their nullable annotation because they restrict the parent to a
specific soft-delete state.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
2026-08-04 14:27:14 +02:00
Barry vd. Heuvel 3a53071650 Remove Laravel 11.x from integration test matrix 2026-07-10 10:50:01 +02:00
Youssef MansourandYoussef Mansour 04c8d5dd2f Add regression test for unique() column type resolution (#1787)
Confirms string()->unique() correctly resolves to string type.
Related to barryvdh/laravel-ide-helper#1747

Co-authored-by: Youssef Mansour <[email protected]>
2026-07-10 10:41:38 +02:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 3f742fd665 Bump actions/checkout from 6 to 7 in the deps group (#1792)
Bumps the deps group with 1 update: [actions/checkout](https://github.com/actions/checkout).


Updates `actions/checkout` from 6 to 7
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: deps
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-07-10 10:41:00 +02:00
Adedayo Oyetoke e1b1ef74aa Skip incrementEach and decrementEach for Eloquent helper (#1782) 2026-05-06 11:53:44 +02:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 7fd3b7aff0 Bump release-drafter/release-drafter from 6 to 7 in the deps group (#1776)
Bumps the deps group with 1 update: [release-drafter/release-drafter](https://github.com/release-drafter/release-drafter).


Updates `release-drafter/release-drafter` from 6 to 7
- [Release notes](https://github.com/release-drafter/release-drafter/releases)
- [Commits](https://github.com/release-drafter/release-drafter/compare/v6...v7)

---
updated-dependencies:
- dependency-name: release-drafter/release-drafter
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: deps
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-04-01 12:40:07 +02:00
Barry vd. Heuvel 1002cb567d Update branch alias from 3.6-dev to 3.7-dev 2026-03-17 16:27:12 +01:00
barryvdh 3e0c12ee0e Update CHANGELOG 2026-03-17 15:27:00 +00:00
Jesper Noordsij ad7e37676f Bump branch alias to 3.6 (#1774) 2026-03-17 15:12:51 +01:00
Barry vd. Heuvel 9027494e97 Remove closure in attribute test (#1772) 2026-03-05 21:35:19 +01:00
isaackaara c3f795e909 fix: skip autoload exception when class existence is being checked (#1764)
The MetaCommand's custom autoloader throws a ReflectionException for any
class not found during meta generation. However, this breaks libraries
that use class_exists() to check for optional dependencies before loading
them (e.g. Doctrine ORM checking for StaticReflectionService removed in
doctrine/persistence v4).

This fix checks the call stack (up to 3 frames) for class_exists(),
interface_exists(), trait_exists(), or enum_exists() calls and returns
gracefully instead of throwing, allowing the existence check to return
false as expected.

Fixes #1750
2026-03-04 17:15:04 +01:00
2fba281b14 Fix PHPDoc placement before PHP 8 class attributes and add regression tests (#1769)
* Initial plan

* Add tests for PHP class attribute placement and fix whitespace in regex

Co-authored-by: barryvdh <[email protected]>

* Add advanced edge case tests: final+nested-brackets and multiple attributes

Co-authored-by: barryvdh <[email protected]>

* Add PHP 8.5 test for closures inside attribute arguments

Co-authored-by: barryvdh <[email protected]>

* composer fix-style

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: barryvdh <[email protected]>
Co-authored-by: laravel-ide-helper <[email protected]>
2026-03-04 12:00:42 +01:00
laravel-ide-helper 39bcb60b7c composer fix-style 2026-03-04 09:53:06 +00:00
isaackaara 16f685aa9f fix: don't extend root's parent class for facade stubs in helper file (#1766)
Since #1674 (commit 09623f2), the generated IDE helper file adds an
`extends` declaration for Macroable classes to expose inherited methods.
However, the check to skip facades only excluded classes in the
`\Illuminate\Support\Facades` namespace, so third-party facades (e.g.
`Spatie\Menu\Laravel\Facades\Menu`) would incorrectly extend the
facade root's parent class.

This caused the generated stub to conflict with the real facade class:

    namespace Spatie\Menu\Laravel\Facades {
        class Menu extends \Spatie\Menu\Menu {  // wrong!

The fix checks whether the extends class IS a Facade subclass (using
`is_subclass_of`) rather than comparing namespace strings. This
correctly excludes ALL facade classes (both Laravel and third-party)
while still allowing non-facade Macroable classes to extend their
parent.

Fixes #1724
2026-03-04 10:52:43 +01:00
isaackaara 392d5cfc80 fix: place PHPDoc before class attributes when writing to models (#1765)
When using --write/-W with models that have PHP 8 attributes (e.g.
#[ObservedBy(...)]), the generated PHPDoc block was inserted between
the attribute and the class declaration:

    #[ObservedBy([ImageObserver::class])]
    /**
     * @property string $name
     */
    final class Image extends Model

This breaks PHPStan/Larastan because the docblock must come before
the attributes. The fix scans backward from the class declaration to
find any preceding PHP 8 attributes and inserts the docblock before
them:

    /**
     * @property string $name
     */
    #[ObservedBy([ImageObserver::class])]
    final class Image extends Model

Fixes #1734
2026-03-04 10:52:03 +01:00
isaackaara 3d8fccd700 fix: correct indentation in camel case config comment block (#1767)
The 'Support for camel cased models' comment block used 5-space
indentation for the pipe characters instead of the standard 4 spaces
used by all other comment blocks in the config file.

Fixes #1761
2026-03-04 10:48:05 +01:00
Laravel ShiftandBarry vd. Heuvel e9b62b6ee0 Laravel 13.x Compatibility (#1763)
* Bump dependencies for Laravel 13

* Update GitHub Actions for Laravel 13

* Update workflow to remove cron schedule

Removed cron schedule and adjusted pull request branches.

* Fix syntax, modify Laravel version in run-tests.yml

Updated Laravel version from '13.0' to '13.x' in CI configuration.

* Update test-ci command in composer.json

* Fix test-ci command in composer.json

---------

Co-authored-by: Barry vd. Heuvel <[email protected]>
2026-02-21 09:54:37 +01:00
Pieter Willekens 37dfcf9e14 chore: update test snapshots after dependency upgrade (#1762) 2026-02-20 14:51:32 +01:00
Pieter Willekens 573c9f3f57 ci: add PHP 8.5 to integration test matrix (#1760)
The unit test matrix already includes PHP 8.5 but it was missing
from the integration tests.
2026-02-11 11:45:28 +01:00
Pieter Willekensandlaravel-ide-helper fd3cfbe09d feat(ModelsCommand): add configuration option to disable model query methods (#1692)
* feat(ModelsCommand): add configuration option to disable model query methods

* composer fix-style

* update comment

* revert whitespace changes

* composer fix-style

* composer fix-style

---------

Co-authored-by: laravel-ide-helper <[email protected]>
2026-02-11 11:45:10 +01:00
Pieter Willekens 3bd70eafd0 fix: wrap bare intersection types in parentheses when adding nullable (#1756)
When a MorphTo relation's docblock uses a bare intersection type in the
generic parameter (e.g. `MorphTo<BaseModel&CanBeAssigned, $this>`), the
generated property type incorrectly becomes `BaseModel&CanBeAssigned|null`
instead of the correct `(BaseModel&CanBeAssigned)|null`.

This adds `wrapIntersectionType()` which ensures bare intersection types
are wrapped in parentheses before `|null` is appended, producing valid
DNF type syntax. Applied in both `setProperty()` and `applyNullability()`.
2026-02-10 15:19:29 +01:00
Pieter Willekens 5aca186d92 perf: reduce redundant lookups and file I/O in generation hot paths (#1757)
- Convert usedMethods from list to hash map for O(1) dedup lookups
- Cache getRelationTypes() and getRelationReturnTypes() per command run
- Reuse SplFileObject instances by filename instead of re-opening per method
- Cache ContextFactory results per declaring class across docblock helpers

Benchmarked with hyperfine (10 runs, 2 warmup): 1.37x faster (~27%).
2026-02-10 15:18:58 +01:00
barryvdh 148f956272 normalize composer.json 2026-02-07 13:33:03 +00:00
Barry vd. Heuvel cff155b0d3 Replace psalm with larastan (#1755)
* Use larastan instead of psalm

* Fix cs

* Fix baseline
2026-02-07 14:32:53 +01:00
SavaandSava Markovic d87ec5835d Support all DNF types from PHP RFC (#1751)
* Support all DNF types from PHP RFC

* Update failing test

---------

Co-authored-by: Sava Markovic <[email protected]>
2026-01-26 14:24:36 +01:00
Evan Burrell b0dcd7c62f Make Soft Deleted Relationships Nullable (#1749) 2026-01-11 14:34:18 +01:00
JaspurandBarry vd. Heuvel 2ac73f2953 Skip calling fake() when required parameters exist (Socialite compatibility) (#1746)
* Skip calling fake() on facades that require parameters (fix Socialite error)

The ide-helper attempted to invoke Facade::fake() unconditionally, which
breaks when a facade (such as Laravel Socialite) requires a mandatory
parameter in its fake() method signature. This resulted in an
ArgumentCountError during `php artisan ide-helper:generate`.

This patch adds a ReflectionMethod check and skips calling fake() when
required parameters are present, ensuring compatibility with Socialite
and preserving expected behavior for facades that support parameterless
faking.

* Update Alias.php

---------

Co-authored-by: Barry vd. Heuvel <[email protected]>
2025-12-10 10:31:15 +01:00
Barry vd. Heuvel c95825a745 Fix test 2025-12-10 10:16:51 +01:00
barryvdh db606f30d1 Update CHANGELOG 2025-12-10 09:12:44 +00:00
Yannick Schinko b106f7ee85 Add support for decimal column type (#1739)
* Add support for `decimal` column type

Previously `decimal` columns were represented with a cast. This now is no longer the case and instead the column type itself is `decimal`. This change takes that into account.

* The column type may also be `numeric`

* Update tests
2025-12-10 10:11:07 +01:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> d61d20357e Bump the deps group across 1 directory with 2 updates (#1743)
Bumps the deps group with 2 updates in the / directory: [actions/checkout](https://github.com/actions/checkout) and [stefanzweifel/git-auto-commit-action](https://github.com/stefanzweifel/git-auto-commit-action).


Updates `actions/checkout` from 5 to 6
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v5...v6)

Updates `stefanzweifel/git-auto-commit-action` from 6 to 7
- [Release notes](https://github.com/stefanzweifel/git-auto-commit-action/releases)
- [Changelog](https://github.com/stefanzweifel/git-auto-commit-action/blob/master/CHANGELOG.md)
- [Commits](https://github.com/stefanzweifel/git-auto-commit-action/compare/v6...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: deps
- dependency-name: stefanzweifel/git-auto-commit-action
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: deps
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-12-10 10:10:25 +01:00
Jesper Noordsij e9283c40a2 Remove calls to PHP 8.5-deprecated setAccessible (#1744)
These are no-op as of PHP 8.1 and thus no longer needed

See also https://wiki.php.net/rfc/make-reflection-setaccessible-no-op
2025-12-10 10:10:09 +01:00
WentTheFox 12a0d7d54c Fix alias fake error (#1745)
* Add catch block in Alias::detectFake

* Update Alias unit tests
2025-12-10 10:09:42 +01:00
Serhii Petrov 9ef25f60e7 Add php 8.5 support (#1735) 2025-10-01 15:12:26 +02:00
Keita Shima 8dff6bb5ff Fix typos in documentation and code comments (#1733)
- Fixed 'seperate' to 'separate' in README.md (2 occurrences)
- Fixed 'columname' to 'columnname' in README.md (2 occurrences)
- Fixed 'Wether' to 'Whether' in src/Method.php PHPDoc comments (2 occurrences)
2025-09-15 14:14:26 +02:00
dependabot[bot]anddependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> 53854ea7d9 Bump actions/checkout from 4 to 5 in the deps group (#1731)
Bumps the deps group with 1 update: [actions/checkout](https://github.com/actions/checkout).


Updates `actions/checkout` from 4 to 5
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v5)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '5'
  dependency-type: direct:production
  update-type: version-update:semver-major
  dependency-group: deps
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2025-09-02 16:32:00 +02:00
Peter Jørgensen 1fa84a3b65 fix methodsto typo (#1723) 2025-08-04 15:07:10 +02:00
barryvdh 5e973967a7 Update CHANGELOG 2025-07-18 14:10:29 +00:00
erikn69andJoel Stein 8d00250cba Add magic *_exists properties (#1712)
* Added magic `*_exists` properties.

* fix return datatype

* disabled by default

---------

Co-authored-by: Joel Stein <[email protected]>
2025-07-17 22:11:57 +02:00
Barry vd. Heuvel 877f5ed0a7 Trim strings and bump reflection docblock (#1721)
* Update version restraint

* UPdate snapshots

* update strings
2025-07-17 08:20:10 +02:00
83 changed files with 2263 additions and 384 deletions
+2 -2
View File
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-22.04
steps:
- name: Git checkout
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Validate Composer configuration
run: composer validate --strict
@@ -23,6 +23,6 @@ jobs:
composer global require ergebnis/composer-normalize
composer normalize
- uses: stefanzweifel/git-auto-commit-action@v6
- uses: stefanzweifel/git-auto-commit-action@v7
with:
commit_message: normalize composer.json
+2 -2
View File
@@ -13,7 +13,7 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v7
- name: Setup PHP
uses: shivammathur/setup-php@v2
@@ -27,7 +27,7 @@ jobs:
- run: composer fix-style
continue-on-error: true
- uses: stefanzweifel/git-auto-commit-action@v6
- uses: stefanzweifel/git-auto-commit-action@v7
with:
commit_message: composer fix-style
commit_author: laravel-ide-helper <[email protected]>
+1 -1
View File
@@ -32,7 +32,7 @@ jobs:
# echo "GHE_HOST=${GITHUB_SERVER_URL##https:\/\/}" >> $GITHUB_ENV
# Drafts your next Release notes as Pull Requests are merged into "master"
- uses: release-drafter/release-drafter@v6
- uses: release-drafter/release-drafter@v7
# (Optional) specify config name to use, relative to .github/. Default: release-drafter.yml
# with:
# config-name: my-config.yml
+65 -61
View File
@@ -1,75 +1,79 @@
name: Integration Tests
on:
push:
branches:
- master
pull_request:
branches:
- "*"
schedule:
- cron: '0 0 * * *'
push:
branches:
- master
pull_request:
branches:
- "*"
jobs:
php-laravel-integration-tests:
runs-on: ubuntu-22.04
timeout-minutes: 15
env:
COMPOSER_NO_INTERACTION: 1
strategy:
fail-fast: false
matrix:
php: [8.4, 8.3, 8.2]
laravel: [11.x, 12.x]
php-laravel-integration-tests:
runs-on: ubuntu-22.04
name: P${{ matrix.php }} - Laravel${{ matrix.laravel }}
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
path: src
timeout-minutes: 15
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
env:
COMPOSER_NO_INTERACTION: 1
- name: Install dependencies
run: |
composer create-project --prefer-dist laravel/laravel:${{ matrix.laravel }} --stability=dev --no-progress sample
cd sample
composer config minimum-stability dev
composer update --prefer-stable --prefer-dist --no-progress
strategy:
fail-fast: false
matrix:
php: [8.5, 8.4, 8.3, 8.2]
laravel: [12.x, 13.x]
exclude:
- laravel: 13.x
php: 8.2
- name: Add package from source
run: |
cd sample
sed -e 's|"type": "project",|&\n"repositories": [ { "type": "path", "url": "../src" } ],|' -i composer.json
composer require --dev "barryvdh/laravel-ide-helper:*" --with-all-dependencies
name: P${{ matrix.php }} - Laravel${{ matrix.laravel }}
- name: Execute generate run
run: |
cd sample
php artisan ide-helper:generate
steps:
- name: Checkout code
uses: actions/checkout@v7
with:
path: src
- name: Execute meta run
run: |
cd sample
php artisan ide-helper:meta -v
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
- name: Check file existence
run: |
ls sample/_ide_helper.php
ls sample/.phpstorm.meta.php
- name: Install dependencies
run: |
composer create-project --prefer-dist laravel/laravel:${{ matrix.laravel }} --stability=dev --no-progress sample
cd sample
composer config minimum-stability dev
composer update --prefer-stable --prefer-dist --no-progress
- name: Add package from source
run: |
cd sample
sed -e 's|"type": "project",|&\n"repositories": [ { "type": "path", "url": "../src" } ],|' -i composer.json
composer require --dev "barryvdh/laravel-ide-helper:*" --with-all-dependencies
- name: Check logs
run: |
if [ `ls -1q "sample/storage/logs/" | wc -l` -gt 0 ]; then
for logfile in sample/storage/logs/*; do
echo "-- $logfile --"
cat $logfile
done
exit 1
fi
- name: Execute generate run
run: |
cd sample
php artisan ide-helper:generate
- name: Execute meta run
run: |
cd sample
php artisan ide-helper:meta -v
- name: Check file existence
run: |
ls sample/_ide_helper.php
ls sample/.phpstorm.meta.php
- name: Check logs
run: |
if [ `ls -1q "sample/storage/logs/" | wc -l` -gt 0 ]; then
for logfile in sample/storage/logs/*; do
echo "-- $logfile --"
cat $logfile
done
exit 1
fi
+2 -2
View File
@@ -12,7 +12,7 @@ jobs:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v7
- name: Setup PHP
uses: shivammathur/setup-php@v2
@@ -25,4 +25,4 @@ jobs:
run: composer install --prefer-dist --no-progress --no-suggest
- name: Analyze
run: composer analyze
run: vendor/bin/phpstan --no-progress --error-format=github
+29 -25
View File
@@ -7,13 +7,13 @@ on:
pull_request:
branches:
- "*"
schedule:
- cron: '0 0 * * *'
jobs:
php-tests:
runs-on: ${{ matrix.os }}
timeout-minutes: 15
env:
COMPOSER_NO_INTERACTION: 1
@@ -21,37 +21,41 @@ jobs:
fail-fast: false
matrix:
os: [ubuntu-latest]
php: [8.4, 8.3, 8.2]
laravel: [~11.15, 12.x]
php: [8.5, 8.4, 8.3, 8.2]
laravel: [12.x, 13.x, ~11.15]
stability: [prefer-lowest, prefer-stable]
include:
- os: windows-latest
php: 8.3
laravel: 12.x
stability: prefer-stable
exclude:
- laravel: 13.x
php: 8.2
steps:
- name: Set git to use LF
if: ${{ matrix.os == 'windows-latest' }}
run: |
git config --global core.autocrlf false
git config --global core.eol lf
- name: Set git to use LF
if: "${{ matrix.os == 'windows-latest' }}"
run: |
git config --global core.autocrlf false
git config --global core.eol lf
- name: Checkout code
uses: actions/checkout@v4
- name: Checkout code
uses: actions/checkout@v7
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
extensions: pdo_sqlite, fileinfo
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
coverage: none
extensions: pdo_sqlite, fileinfo
- name: Install dependencies
run: |
composer remove vimeo/psalm --no-update --dev
composer remove friendsofphp/php-cs-fixer --no-update --dev
composer require "laravel/framework:${{ matrix.laravel }}" --no-update --no-progress
composer update --prefer-dist --no-progress --${{ matrix.stability }}
- name: Install dependencies
run: |
composer remove vimeo/psalm --no-update --dev
composer remove friendsofphp/php-cs-fixer --no-update --dev
composer require "laravel/framework:${{ matrix.laravel }}" --no-update --no-progress
composer update --prefer-dist --no-progress --${{ matrix.stability }}
- name: Execute Unit Tests
run: composer test-ci
- name: Execute Unit Tests
run: composer test-ci
+2 -2
View File
@@ -16,7 +16,7 @@ jobs:
steps:
- name: Checkout code
uses: actions/checkout@v4
uses: actions/checkout@v7
with:
ref: ${{ github.event.release.target_commitish }}
@@ -27,7 +27,7 @@ jobs:
release-notes: ${{ github.event.release.body }}
- name: Commit updated CHANGELOG
uses: stefanzweifel/git-auto-commit-action@v6
uses: stefanzweifel/git-auto-commit-action@v7
with:
branch: ${{ github.event.release.target_commitish }}
commit_message: Update CHANGELOG
+2 -1
View File
@@ -1,5 +1,6 @@
.phpunit.result.cache
/auth.json
/build
/.idea
/.php-cs-fixer.cache
/.php-cs-fixer.php
+1 -1
View File
@@ -3,7 +3,7 @@ require __DIR__ . '/vendor/autoload.php';
$finder = PhpCsFixer\Finder::create()
->in(__DIR__)
->exclude('tests');
->exclude(['tests', 'build']);
$config = require __DIR__ . '/.php-cs-fixer.common.php';
+87
View File
@@ -1,5 +1,92 @@
# Changelog
## v3.7.0 - 2026-03-17
### What's Changed
* Skip calling fake() when required parameters exist (Socialite compatibility) by @Jaspur in https://github.com/barryvdh/laravel-ide-helper/pull/1746
* Make Soft Deleted Relationships Nullable by @evan-burrell in https://github.com/barryvdh/laravel-ide-helper/pull/1749
* Support all DNF types from PHP RFC by @gurmanolog in https://github.com/barryvdh/laravel-ide-helper/pull/1751
* Replace psalm with larastan by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1755
* perf: reduce redundant lookups and file I/O in generation hot paths by @pataar in https://github.com/barryvdh/laravel-ide-helper/pull/1757
* fix: wrap bare intersection types in parentheses when adding nullable by @pataar in https://github.com/barryvdh/laravel-ide-helper/pull/1756
* feat(ModelsCommand): add configuration option to disable model query methods by @pataar in https://github.com/barryvdh/laravel-ide-helper/pull/1692
* ci: add PHP 8.5 to integration test matrix by @pataar in https://github.com/barryvdh/laravel-ide-helper/pull/1760
* chore: update test snapshots after merge order issue by @pataar in https://github.com/barryvdh/laravel-ide-helper/pull/1762
* Laravel 13.x Compatibility by @laravel-shift in https://github.com/barryvdh/laravel-ide-helper/pull/1763
* fix: Correct indentation in camel case config comment block by @isaackaara in https://github.com/barryvdh/laravel-ide-helper/pull/1767
* fix: Place PHPDoc before class attributes when writing to models by @isaackaara in https://github.com/barryvdh/laravel-ide-helper/pull/1765
* fix: Don't extend root's parent class for facade stubs in helper file by @isaackaara in https://github.com/barryvdh/laravel-ide-helper/pull/1766
* Fix PHPDoc placement before PHP 8 class attributes and add regression tests by @Copilot in https://github.com/barryvdh/laravel-ide-helper/pull/1769
* fix: Skip autoload exception when class existence is being checked by @isaackaara in https://github.com/barryvdh/laravel-ide-helper/pull/1764
* Remove closure in attribute test by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1772
* Bump branch alias to 3.6 by @jnoordsij in https://github.com/barryvdh/laravel-ide-helper/pull/1774
### New Contributors
* @Jaspur made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1746
* @evan-burrell made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1749
* @gurmanolog made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1751
* @laravel-shift made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1763
* @isaackaara made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1767
* @Copilot made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1769
**Full Changelog**: https://github.com/barryvdh/laravel-ide-helper/compare/v3.6.1...v3.7.0
## v3.6.1 - 2025-12-10
### What's Changed
* Fix `methodsto` typo in README by @peterchrjoergensen in https://github.com/barryvdh/laravel-ide-helper/pull/1723
* Bump actions/checkout from 4 to 5 in the deps group by @dependabot[bot] in https://github.com/barryvdh/laravel-ide-helper/pull/1731
* Fix typos in documentation and code comments by @kei1111 in https://github.com/barryvdh/laravel-ide-helper/pull/1733
* Add php 8.5 support by @sergiy-petrov in https://github.com/barryvdh/laravel-ide-helper/pull/1735
* Fix alias fake error by @WentTheFox in https://github.com/barryvdh/laravel-ide-helper/pull/1745
* Remove calls to PHP 8.5-deprecated `setAccessible` by @jnoordsij in https://github.com/barryvdh/laravel-ide-helper/pull/1744
* Bump the deps group across 1 directory with 2 updates by @dependabot[bot] in https://github.com/barryvdh/laravel-ide-helper/pull/1743
* Add support for `decimal` column type by @BrainStone in https://github.com/barryvdh/laravel-ide-helper/pull/1739
### New Contributors
* @peterchrjoergensen made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1723
* @kei1111 made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1733
* @WentTheFox made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1745
* @BrainStone made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1739
**Full Changelog**: https://github.com/barryvdh/laravel-ide-helper/compare/v3.6.0...v3.6.1
## v3.6.0 - 2025-07-18
### What's Changed
* fix: Change AsArrayObject cast to be Laravel's ArrayObject by @wsamoht in https://github.com/barryvdh/laravel-ide-helper/pull/1675
* Add extends declaration for Macroable classes to fix missing inherited methods by @KentarouTakeda in https://github.com/barryvdh/laravel-ide-helper/pull/1674
* fix(meta): ignore aliases in the autoloader (Fixes #1671) by @pataar in https://github.com/barryvdh/laravel-ide-helper/pull/1686
* feat(ModelsCommand): add support for the new Scope attribute by @pataar in https://github.com/barryvdh/laravel-ide-helper/pull/1694
* fix type change for scope default float parameter by @nivseb in https://github.com/barryvdh/laravel-ide-helper/pull/1697
* Revert #1629 - *Allow adding custom Macroable classes* by @erikn69 in https://github.com/barryvdh/laravel-ide-helper/pull/1707
* Configurable macro return type defaults by @erikn69 in https://github.com/barryvdh/laravel-ide-helper/pull/1711
* docs(readme): add Laravel 12 support information by @SantosVilanculos in https://github.com/barryvdh/laravel-ide-helper/pull/1717
* Add multi-level directory support for translation files by @RosiersRobin in https://github.com/barryvdh/laravel-ide-helper/pull/1718
* Support `AsCollection::of($map)`, `AsCollection::using($class, $map)` by @erikn69 in https://github.com/barryvdh/laravel-ide-helper/pull/1714
* fix: Fixed wrong doc for SoftDeletes `withTrashed` method by @eldair in https://github.com/barryvdh/laravel-ide-helper/pull/1688
* Support other OS on tests by @erikn69 in https://github.com/barryvdh/laravel-ide-helper/pull/1715
* Fix tests on windows by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1720
* Bump stefanzweifel/git-auto-commit-action from 5 to 6 in the deps group by @dependabot[bot] in https://github.com/barryvdh/laravel-ide-helper/pull/1719
* Update .gitattributes - avoid all `.php-cs-fixer` files on vendor by @erikn69 in https://github.com/barryvdh/laravel-ide-helper/pull/1708
* fix(ModelsCommand): use 'string' as realType for 'encrypted' casts by @pataar in https://github.com/barryvdh/laravel-ide-helper/pull/1698
* Trim strings and bump reflection docblock by @barryvdh in https://github.com/barryvdh/laravel-ide-helper/pull/1721
* Add magic *_exists properties by @erikn69 in https://github.com/barryvdh/laravel-ide-helper/pull/1712
### New Contributors
* @wsamoht made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1675
* @nivseb made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1697
* @SantosVilanculos made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1717
* @RosiersRobin made their first contribution in https://github.com/barryvdh/laravel-ide-helper/pull/1718
**Full Changelog**: https://github.com/barryvdh/laravel-ide-helper/compare/v3.5.5...v3.6.0
## v3.5.5 - 2025-02-21
### What's Changed
+4 -4
View File
@@ -51,7 +51,7 @@ php artisan ide-helper:models -RW
If you don't want the full _ide_helper.php file, you can run add `--write-eloquent-helper` to the model command to generate small version, which is required for the `@mixin \Eloquent` to be able to add the QueryBuilder methods.
If you don't want to add all the phpdocs to your Models directly, you can use `--nowrite` to create a seperate file. The `--write-mixin` option can be used to only add a `@mixin` to your models, but add the generated phpdocs in a seperate file. This avoids having the results marked as duplicate.
If you don't want to add all the phpdocs to your Models directly, you can use `--nowrite` to create a separate file. The `--write-mixin` option can be used to only add a `@mixin` to your models, but add the generated phpdocs in a separate file. This avoids having the results marked as duplicate.
_Check out [this Laracasts video](https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/15) for a quick introduction/explanation!_
@@ -210,11 +210,11 @@ Eloquent allows calling `where<Attribute>` on your models, e.g. `Post::whereTitl
If for some reason it's undesired to have them generated (one for each column), you can disable this via config `write_model_magic_where` and setting it to `false`.
#### Magic `*_count` properties
#### Magic `*_count` and `*_exists` properties
You may use the [`::withCount`](https://laravel.com/docs/master/eloquent-relationships#counting-related-models) method to count the number results from a relationship without actually loading them. Those results are then placed in attributes following the `<columname>_count` convention.
You may use the [`::withCount`](https://laravel.com/docs/master/eloquent-relationships#counting-related-models) and [`::withExists`](https://laravel.com/docs/master/eloquent-relationships#other-aggregate-functions) methods to count the number results from a relationship without actually loading them. Those results are then placed in attributes following the `<columnname>_count` and `<columnname>_exists` convention.
By default, these attributes are generated in the phpdoc. You can turn them off by setting the config `write_model_relation_count_properties` to `false`.
By default, these attributes are generated in the phpdoc. You can turn them off by setting the config `write_model_relation_count_properties` and `write_model_relation_exists_properties` to `false`.
#### Generics annotations
+14 -13
View File
@@ -25,21 +25,22 @@
"ext-json": "*",
"barryvdh/reflection-docblock": "^2.4",
"composer/class-map-generator": "^1.0",
"illuminate/console": "^11.15 || ^12",
"illuminate/database": "^11.15 || ^12",
"illuminate/filesystem": "^11.15 || ^12",
"illuminate/support": "^11.15 || ^12"
"illuminate/console": "^11.15 || ^12 || ^13.0",
"illuminate/database": "^11.15 || ^12 || ^13.0",
"illuminate/filesystem": "^11.15 || ^12 || ^13.0",
"illuminate/support": "^11.15 || ^12 || ^13.0"
},
"require-dev": {
"ext-pdo_sqlite": "*",
"friendsofphp/php-cs-fixer": "^3",
"illuminate/config": "^11.15 || ^12",
"illuminate/view": "^11.15 || ^12",
"illuminate/config": "^11.15 || ^12 || ^13.0",
"illuminate/view": "^11.15 || ^12 || ^13.0",
"larastan/larastan": "^3.1",
"mockery/mockery": "^1.4",
"orchestra/testbench": "^9.2 || ^10",
"phpunit/phpunit": "^10.5 || ^11.5.3",
"orchestra/testbench": "^9.2 || ^10 || ^11.0",
"phpstan/phpstan-phpunit": "^2.0",
"phpunit/phpunit": "^10.5 || ^11.5.3 || ^12.5.12",
"spatie/phpunit-snapshot-assertions": "^4 || ^5",
"vimeo/psalm": "^5.4",
"vlucas/phpdotenv": "^5"
},
"suggest": {
@@ -65,7 +66,7 @@
},
"extra": {
"branch-alias": {
"dev-master": "3.5-dev"
"dev-master": "3.7-dev"
},
"laravel": {
"providers": [
@@ -74,7 +75,8 @@
}
},
"scripts": {
"analyze": "psalm",
"analyze": "phpstan",
"analyze-set-baseline": "phpstan --generate-baseline",
"check-style": [
"php-cs-fixer fix --diff --diff-format=udiff --dry-run",
"php-cs-fixer fix --diff --diff-format=udiff --dry-run --config=.php_cs.tests.php"
@@ -83,9 +85,8 @@
"php-cs-fixer fix",
"php-cs-fixer fix --config=.php-cs-fixer.tests.php"
],
"psalm-set-baseline": "psalm --set-baseline=psalm-baseline.xml",
"test": "phpunit",
"test-ci": "phpunit -d --without-creating-snapshots",
"test-ci": "phpunit",
"test-regenerate": "phpunit -d --update-snapshots"
}
}
+53 -31
View File
@@ -49,17 +49,14 @@ return [
/*
|--------------------------------------------------------------------------
| Factory builders
| Write model query methods
|--------------------------------------------------------------------------
|
| Set to true to generate factory generators for better factory()
| method auto-completion.
|
| Deprecated for Laravel 8 or latest.
| Set to false to disable generated docs for the 'query()', 'newQuery()' and 'newModelQuery()' methods.
|
*/
'include_factory_builders' => false,
'write_query_methods' => true,
/*
|--------------------------------------------------------------------------
@@ -85,14 +82,16 @@ return [
/*
|--------------------------------------------------------------------------
| Write model relation count properties
| Write model relation count and exists properties
|--------------------------------------------------------------------------
|
| Set to false to disable writing of relation count properties to model DocBlocks.
| Set to false to disable writing of relation count and exists properties
| to model DocBlocks.
|
*/
'write_model_relation_count_properties' => true,
'write_model_relation_exists_properties' => false,
/*
|--------------------------------------------------------------------------
@@ -202,29 +201,29 @@ return [
],
/*
|--------------------------------------------------------------------------
| Support for camel cased models
|--------------------------------------------------------------------------
|
| There are some Laravel packages (such as Eloquence) that allow for accessing
| Eloquent model properties via camel case, instead of snake case.
|
| Enabling this option will support these packages by saving all model
| properties as camel case, instead of snake case.
|
| For example, normally you would see this:
|
| * @property \Illuminate\Support\Carbon $created_at
| * @property \Illuminate\Support\Carbon $updated_at
|
| With this enabled, the properties will be this:
|
| * @property \Illuminate\Support\Carbon $createdAt
| * @property \Illuminate\Support\Carbon $updatedAt
|
| Note, it is currently an all-or-nothing option.
|
*/
|--------------------------------------------------------------------------
| Support for camel cased models
|--------------------------------------------------------------------------
|
| There are some Laravel packages (such as Eloquence) that allow for accessing
| Eloquent model properties via camel case, instead of snake case.
|
| Enabling this option will support these packages by saving all model
| properties as camel case, instead of snake case.
|
| For example, normally you would see this:
|
| * @property \Illuminate\Support\Carbon $created_at
| * @property \Illuminate\Support\Carbon $updated_at
|
| With this enabled, the properties will be this:
|
| * @property \Illuminate\Support\Carbon $createdAt
| * @property \Illuminate\Support\Carbon $updatedAt
|
| Note, it is currently an all-or-nothing option.
|
*/
'model_camel_case_properties' => false,
/*
@@ -337,6 +336,29 @@ return [
'enforce_nullable_relationships' => true,
/*
|--------------------------------------------------------------------------
| Make soft deletable relations nullable
|--------------------------------------------------------------------------
|
| When set to true (default), relationships to models using SoftDeletes trait
| will be marked as nullable. This is because soft-deleted records are excluded
| from queries by default, meaning even non-nullable foreign keys can return
| null when the related model is soft-deleted.
|
| Default: true
| A relationship to a soft-deletable model will include |null in the type:
| * @property-read Team|null $team
|
| Option: false
| A relationship to a soft-deletable model will NOT include |null (unless
| nullable for other reasons such as nullable foreign key column):
| * @property-read Team $team
|
*/
'soft_deletes_force_nullable' => true,
/*
|--------------------------------------------------------------------------
| Run artisan commands after migrations to generate model helpers
-1
View File
@@ -124,7 +124,6 @@ $reflection = new ReflectionClass($loader);
$property = $reflection->hasProperty('paths')
? $reflection->getProperty('paths')
: $reflection->getProperty('path');
$property->setAccessible(true);
$paths = Illuminate\Support\Arr::wrap($property->getValue($loader));
+67
View File
@@ -0,0 +1,67 @@
parameters:
ignoreErrors:
-
message: '#^File ends with a trailing whitespace\. This may cause problems when running the code in the web browser\. Remove the closing \?\> mark or remove the whitespace\.$#'
identifier: whitespace.fileEnd
count: 1
path: resources/views/helper.php
-
message: '#^Call to an undefined method Illuminate\\Contracts\\Filesystem\\Filesystem\:\:requireOnce\(\)\.$#'
identifier: method.notFound
count: 1
path: src/Console/MetaCommand.php
-
message: '#^Call to an undefined method Illuminate\\Contracts\\Foundation\\Application\:\:getBindings\(\)\.$#'
identifier: method.notFound
count: 1
path: src/Console/MetaCommand.php
-
message: '#^Call to an undefined method Barryvdh\\Reflection\\DocBlock\\Tag\:\:getMethodName\(\)\.$#'
identifier: method.notFound
count: 1
path: src/Console/ModelsCommand.php
-
message: '#^Call to an undefined method Barryvdh\\Reflection\\DocBlock\\Tag\:\:getType\(\)\.$#'
identifier: method.notFound
count: 1
path: src/Console/ModelsCommand.php
-
message: '#^Call to an undefined method Barryvdh\\Reflection\\DocBlock\\Tag\:\:getVariableName\(\)\.$#'
identifier: method.notFound
count: 1
path: src/Console/ModelsCommand.php
-
message: '#^Call to an undefined method Illuminate\\Support\\Optional\:\:getNumberOfParameters\(\)\.$#'
identifier: method.notFound
count: 1
path: src/Console/ModelsCommand.php
-
message: '#^Call to an undefined method Illuminate\\Support\\Optional\:\:getParameters\(\)\.$#'
identifier: method.notFound
count: 1
path: src/Console/ModelsCommand.php
-
message: '#^Call to an undefined method Illuminate\\Support\\Optional\:\:getReturnType\(\)\.$#'
identifier: method.notFound
count: 1
path: src/Console/ModelsCommand.php
-
message: '#^Call to an undefined static method Illuminate\\Database\\Eloquent\\Model\:\:newFactory\(\)\.$#'
identifier: staticMethod.notFound
count: 2
path: src/Console/ModelsCommand.php
-
message: '#^Call to an undefined method ReflectionFunctionAbstract\:\:getDeclaringClass\(\)\.$#'
identifier: method.notFound
count: 1
path: src/Method.php
+11
View File
@@ -0,0 +1,11 @@
includes:
- phpstan-baseline.neon
- vendor/phpstan/phpstan-phpunit/extension.neon
parameters:
level: 2
paths:
- src
- resources/views
excludePaths:
-24
View File
@@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<files psalm-version="5.4.0@62db5d4f6a7ae0a20f7cc5a4952d730272fc0863">
<file src="src/Factories.php">
<UndefinedClass occurrences="2">
<code>Factory</code>
<code>Factory</code>
</UndefinedClass>
</file>
<file src="src/Generator.php">
<UndefinedClass occurrences="6">
<code>\Auth</code>
<code>\Cache</code>
<code>\Cache</code>
<code>\DB</code>
<code>\Queue</code>
<code>\Storage</code>
</UndefinedClass>
</file>
<file src="src/Console/ModelsCommand.php">
<UndefinedClass occurrences="1">
<code>\UnitEnum</code>
</UndefinedClass>
</file>
</files>
-16
View File
@@ -1,16 +0,0 @@
<?xml version="1.0"?>
<psalm
errorLevel="7"
resolveFromConfigFile="true"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://getpsalm.org/schema/config"
xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd"
errorBaseline="psalm-baseline.xml"
>
<projectFiles>
<directory name="src" />
<ignoreFiles>
<directory name="vendor" />
</ignoreFiles>
</projectFiles>
</psalm>
+1 -9
View File
@@ -3,6 +3,7 @@
/**
* @var Barryvdh\LaravelIdeHelper\Alias[][] $namespaces_by_alias_ns
* @var Barryvdh\LaravelIdeHelper\Alias[][] $namespaces_by_extends_ns
* @var string[] $real_time_facades
* @var bool $include_fluent
* @var string $helpers
*/
@@ -119,12 +120,3 @@ namespace Illuminate\Support {
}
<?php endif ?>
<?php foreach ($factories as $factory) : ?>
namespace <?=$factory->getNamespaceName()?> {
/**
* @method \Illuminate\Database\Eloquent\Collection|<?=$factory->getShortName()?>[]|<?=$factory->getShortName()?> create($attributes = [])
* @method \Illuminate\Database\Eloquent\Collection|<?=$factory->getShortName()?>[]|<?=$factory->getShortName()?> make($attributes = [])
*/
class <?=$factory->getShortName()?>FactoryBuilder extends \Illuminate\Database\Eloquent\FactoryBuilder {}
}
<?php endforeach; ?>
+14 -11
View File
@@ -1,4 +1,16 @@
<?= '<?php' ?>
<?php
/**
* @var array $bindings
* @var string[] $methods
* @var string[] $configMethods
* @var Illuminate\Support\Collection $configValues
* @var array<string, array> $expectedArgumentSets
* @var array $expectedArguments
* @var string[] $userMethods
* @var string $userModel/
* */
?>
/* @noinspection ALL */
// @formatter:off
@@ -35,15 +47,6 @@ namespace PHPSTORM_META {
]));
<?php endforeach; ?>
<?php if (count($factories)) : ?>
override(\factory(0), map([
'' => '@FactoryBuilder',
<?php foreach ($factories as $factory) : ?>
'<?= $factory->getName() ?>' => \<?= $factory->getName() ?>FactoryBuilder::class,
<?php endforeach; ?>
]));
<?php endif; ?>
override(\Illuminate\Foundation\Testing\Concerns\InteractsWithContainer::mock(0), map(["" => "@&\Mockery\MockInterface"]));
override(\Illuminate\Foundation\Testing\Concerns\InteractsWithContainer::partialMock(0), map(["" => "@&\Mockery\MockInterface"]));
override(\Illuminate\Foundation\Testing\Concerns\InteractsWithContainer::instance(0), type(1));
@@ -79,7 +82,7 @@ namespace PHPSTORM_META {
override(\tap(0), type(0));
override(\optional(0), type(0));
<?php if (isset($expectedArgumentSets)): ?>
<?php if ($expectedArgumentSets): ?>
<?php foreach ($expectedArgumentSets as $name => $argumentsList) : ?>
registerArgumentsSet('<?= $name ?>', <?php foreach ($argumentsList as $i => $arg) : ?><?php if ($i % 5 == 0) {
echo "\n";
@@ -87,7 +90,7 @@ namespace PHPSTORM_META {
<?php endforeach; ?>
<?php endif ?>
<?php if (isset($expectedArguments)) : ?>
<?php if ($expectedArguments) : ?>
<?php foreach ($expectedArguments as $arguments) : ?>
<?php
$classes = isset($arguments['class']) ? (array) $arguments['class'] : [null];
+25 -18
View File
@@ -101,7 +101,12 @@ class Alias
}
if ($facade === '\Illuminate\Database\Eloquent\Model') {
$this->usedMethods = ['decrement', 'increment'];
$this->usedMethods = [
'decrement' => true,
'decrementEach' => true,
'increment' => true,
'incrementEach' => true,
];
}
}
@@ -187,7 +192,7 @@ class Alias
public function shouldExtendParentClass()
{
return $this->parentClass
&& $this->getExtendsNamespace() !== '\\Illuminate\\Support\\Facades';
&& !is_subclass_of($this->extends, Facade::class);
}
/**
@@ -248,11 +253,17 @@ class Alias
return;
}
$reflection = new \ReflectionMethod($facade, 'fake');
if ($reflection->getNumberOfRequiredParameters() > 0) {
return;
}
$real = $facade::getFacadeRoot();
try {
$facade::fake();
$fake = $facade::getFacadeRoot();
if ($fake !== $real) {
$this->addClass(get_class($fake));
}
@@ -319,9 +330,8 @@ class Alias
/**
* Get the real root of a facade
*
* @return bool|string
*/
protected function detectRoot()
protected function detectRoot(): void
{
$facade = $this->facade;
@@ -376,11 +386,10 @@ class Alias
$method = new \ReflectionMethod($className, $name);
$class = new ReflectionClass($className);
if (!in_array($magic, $this->usedMethods)) {
if (!isset($this->usedMethods[$magic])) {
if ($class !== $this->root) {
$this->methods[] = new Method(
$method,
$this->alias,
$class,
$magic,
$this->interfaces,
@@ -389,7 +398,7 @@ class Alias
$this->getTemplateNames()
);
}
$this->usedMethods[] = $magic;
$this->usedMethods[$magic] = true;
}
}
}
@@ -397,7 +406,6 @@ class Alias
/**
* Get the methods for one or multiple classes.
*
* @return string
*/
protected function detectMethods()
{
@@ -407,13 +415,12 @@ class Alias
$methods = $reflection->getMethods(\ReflectionMethod::IS_PUBLIC);
if ($methods) {
foreach ($methods as $method) {
if (!in_array($method->name, $this->usedMethods)) {
if (!isset($this->usedMethods[$method->name])) {
// Only add the methods to the output when the root is not the same as the class.
// And don't add the __*() methods
if ($this->extends !== $class && substr($method->name, 0, 2) !== '__') {
$this->methods[] = new Method(
$method,
$this->alias,
$reflection,
$method->name,
$this->interfaces,
@@ -422,7 +429,7 @@ class Alias
$this->getTemplateNames(),
);
}
$this->usedMethods[] = $method->name;
$this->usedMethods[$method->name] = true;
}
}
}
@@ -433,7 +440,7 @@ class Alias
$properties = $reflection->getStaticProperties();
$macros = isset($properties['macros']) ? $properties['macros'] : [];
foreach ($macros as $macro_name => $macro_func) {
if (!in_array($macro_name, $this->usedMethods)) {
if (!isset($this->usedMethods[$macro_name])) {
try {
$method = $this->getMacroFunction($macro_func);
} catch (Throwable $e) {
@@ -443,14 +450,13 @@ class Alias
// Add macros
$this->methods[] = new Macro(
$method,
$this->alias,
$reflection,
$macro_name,
$this->interfaces,
$this->classAliases,
$this->getReturnTypeNormalizers($reflection)
);
$this->usedMethods[] = $macro_name;
$this->usedMethods[$macro_name] = true;
}
}
}
@@ -588,12 +594,13 @@ class Alias
*/
protected function removeDuplicateMethodsFromPhpDoc()
{
$methodNames = array_map(function (Method $method) {
return $method->getName();
}, $this->getMethods());
$methodNames = [];
foreach ($this->getMethods() as $method) {
$methodNames[$method->getName()] = true;
}
foreach ($this->phpdoc->getTags() as $tag) {
if ($tag instanceof MethodTag && in_array($tag->getMethodName(), $methodNames)) {
if ($tag instanceof MethodTag && isset($methodNames[$tag->getMethodName()])) {
$this->phpdoc->deleteTag($tag);
}
}
+12 -5
View File
@@ -11,7 +11,6 @@
namespace Barryvdh\LaravelIdeHelper\Console;
use Barryvdh\LaravelIdeHelper\Factories;
use Dotenv\Parser\Entry;
use Dotenv\Parser\Parser;
use Illuminate\Console\Command;
@@ -108,9 +107,6 @@ class MetaCommand extends Command
*/
public function handle()
{
// Needs to run before exception handler is registered
$factories = $this->config->get('ide-helper.include_factory_builders') ? Factories::all() : [];
$ourAutoloader = $this->registerClassAutoloadExceptions();
$bindings = [];
@@ -149,7 +145,6 @@ class MetaCommand extends Command
$content = $this->view->make('ide-helper::meta', [
'bindings' => $bindings,
'methods' => $this->methods,
'factories' => $factories,
'configMethods' => $this->configMethods,
'configValues' => $configValues,
'expectedArgumentSets' => $this->getExpectedArgumentSets(),
@@ -200,6 +195,18 @@ class MetaCommand extends Command
return;
}
// Don't throw when class existence is being checked via class_exists(),
// interface_exists(), trait_exists(), or enum_exists(). These functions
// expect the autoloader to return gracefully when the class doesn't exist.
// Throwing here would break libraries that use class_exists() to check for
// optional dependencies (e.g. Doctrine ORM checking for removed classes).
$existsFunctions = ['class_exists', 'interface_exists', 'trait_exists', 'enum_exists'];
foreach (debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3) as $frame) {
if (isset($frame['function']) && in_array($frame['function'], $existsFunctions, true)) {
return;
}
}
throw new \ReflectionException("Class '$class' not found.");
};
+208 -41
View File
@@ -44,6 +44,7 @@ use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\Relations\MorphToMany;
use Illuminate\Database\Eloquent\Relations\Pivot;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\SoftDeletingScope;
use Illuminate\Database\Schema\Builder;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
@@ -114,6 +115,7 @@ class ModelsCommand extends Command
protected $write_model_magic_where;
protected $write_model_relation_count_properties;
protected $write_model_relation_exists_properties;
protected $properties = [];
protected $methods = [];
protected $write = false;
@@ -122,6 +124,14 @@ class ModelsCommand extends Command
protected $reset;
protected $phpstorm_noinspections;
protected $write_model_external_builder_methods;
/**
* @var array<string, \SplFileObject>
*/
protected $fileCache = [];
/**
* @var array<string, Context>
*/
protected $contextCache = [];
/**
* @var array<string, true>
*/
@@ -173,6 +183,8 @@ class ModelsCommand extends Command
$this->write_model_external_builder_methods = $this->laravel['config']->get('ide-helper.write_model_external_builder_methods', true);
$this->write_model_relation_count_properties =
$this->laravel['config']->get('ide-helper.write_model_relation_count_properties', true);
$this->write_model_relation_exists_properties =
$this->laravel['config']->get('ide-helper.write_model_relation_exists_properties', false);
$this->write = $this->write_mixin ? true : $this->write;
//If filename is default and Write is not specified, ask what to do
@@ -523,7 +535,7 @@ class ModelsCommand extends Command
}
if ($isNullable) {
$type .= '|null';
$type = $this->wrapIntersectionType($type) . '|null';
} else {
$type = str_replace($nullString, '', $type);
}
@@ -531,6 +543,22 @@ class ModelsCommand extends Command
return $type;
}
/**
* Wraps a bare intersection type in parentheses for correct DNF syntax.
*
* For example, `A&B` becomes `(A&B)` so that adding `|null` produces
* `(A&B)|null` instead of the ambiguous `A&B|null`.
* Types that are already parenthesized or contain union types are returned as-is.
*/
protected function wrapIntersectionType(string $type): string
{
if (str_contains($type, '&') && !str_contains($type, '|') && $type[0] !== '(') {
return '(' . $type . ')';
}
return $type;
}
/**
* Returns the override type for the give type.
*
@@ -581,6 +609,8 @@ class ModelsCommand extends Command
'float', 'real', 'float4',
'double', 'float8' => 'float',
'decimal', 'numeric' => 'numeric',
default => 'string',
};
}
@@ -691,13 +721,16 @@ class ModelsCommand extends Command
);
$this->setMethod($name, $builder . '<static>|' . $modelName, $args, $comment);
}
} elseif (in_array($method, ['query', 'newQuery', 'newModelQuery'])) {
$builder = $this->getClassNameInDestinationFile($model, get_class($model->newModelQuery()));
} elseif (in_array($method, ['query', 'newQuery', 'newModelQuery'])
) {
if ($this->laravel['config']->get('ide-helper.write_query_methods', true)) {
$builder = $this->getClassNameInDestinationFile($model, get_class($model->newModelQuery()));
$this->setMethod(
$method,
$builder . '<static>|' . $this->getClassNameInDestinationFile($model, get_class($model))
);
$this->setMethod(
$method,
$builder . '<static>|' . $this->getClassNameInDestinationFile($model, get_class($model))
);
}
if ($this->write_model_external_builder_methods) {
$this->writeModelExternalBuilderMethods($model);
@@ -716,14 +749,19 @@ class ModelsCommand extends Command
$type = (string)$this->getReturnTypeFromDocBlock($reflection);
}
$file = new \SplFileObject($reflection->getFileName());
$fileName = $reflection->getFileName();
if (!isset($this->fileCache[$fileName])) {
$this->fileCache[$fileName] = new \SplFileObject($fileName);
}
$file = $this->fileCache[$fileName];
$file->seek($reflection->getStartLine() - 1);
$code = '';
$lines = [];
while ($file->key() < $reflection->getEndLine()) {
$code .= $file->current();
$lines[] = $file->current();
$file->next();
}
$code = implode('', $lines);
$code = trim(preg_replace('/\s\s+/', '', $code));
$begin = strpos($code, 'function(');
$code = substr($code, $begin, strrpos($code, '}') - $begin + 1);
@@ -820,6 +858,15 @@ class ModelsCommand extends Command
// What kind of comments should be added to the relation count here?
);
}
if ($this->write_model_relation_exists_properties) {
$this->setProperty(
Str::snake($method) . '_exists',
'bool|null',
true,
false
// What kind of comments should be added to the relation count here?
);
}
} elseif (
$relationReturnType === 'morphTo' ||
(
@@ -875,7 +922,6 @@ class ModelsCommand extends Command
if (in_array($relation, ['hasOne', 'hasOneThrough', 'morphOne'], true)) {
$defaultProp = $reflectionObj->getProperty('withDefault');
$defaultProp->setAccessible(true);
return !$defaultProp->getValue($relationObj);
}
@@ -885,7 +931,6 @@ class ModelsCommand extends Command
}
$fkProp = $reflectionObj->getProperty('foreignKey');
$fkProp->setAccessible(true);
$enforceNullableRelation = $this->laravel['config']->get('ide-helper.enforce_nullable_relationships', true);
@@ -899,9 +944,73 @@ class ModelsCommand extends Command
}
}
if (
$this->relatedModelUsesSoftDeletes($relationObj)
&& !$this->relationIncludesNonTrashedParents($relationObj)
) {
return true;
}
return false;
}
/**
* Check whether the relation explicitly opts into returning non-soft-deleted parents
* via ->withTrashed(), in which case the SoftDeletes-based nullability no longer applies.
*
* Returns false for ->onlyTrashed() and ->withoutTrashed(), which still leave the
* relation potentially empty depending on the parent's soft-delete state.
*
* @param Relation $relationObj
*
* @return bool
*/
protected function relationIncludesNonTrashedParents(Relation $relationObj): bool
{
$query = $relationObj->getQuery();
if (!in_array(SoftDeletingScope::class, $query->removedScopes(), true)) {
return false;
}
$relatedModel = $relationObj->getRelated();
if (!method_exists($relatedModel, 'getQualifiedDeletedAtColumn')) {
return true;
}
$deletedAtColumn = $relatedModel->getQualifiedDeletedAtColumn();
foreach ($query->getQuery()->wheres ?? [] as $where) {
if (
($where['column'] ?? null) === $deletedAtColumn
&& in_array($where['type'] ?? null, ['Null', 'NotNull'], true)
) {
return false;
}
}
return true;
}
/**
* Check if the related model uses the SoftDeletes trait
*
* @param Relation $relationObj
*
* @return bool
*/
protected function relatedModelUsesSoftDeletes(Relation $relationObj): bool
{
if (!$this->laravel['config']->get('ide-helper.soft_deletes_force_nullable', true)) {
return false;
}
$relatedModel = $relationObj->getRelated();
return in_array('Illuminate\\Database\\Eloquent\\SoftDeletes', class_uses_recursive($relatedModel));
}
/**
* Check if the morphTo relation is nullable
*
@@ -918,7 +1027,6 @@ class ModelsCommand extends Command
}
$fkProp = $reflectionObj->getProperty('foreignKey');
$fkProp->setAccessible(true);
foreach (Arr::wrap($fkProp->getValue($relationObj)) as $foreignKey) {
if (isset($this->nullableColumns[$foreignKey])) {
@@ -949,7 +1057,7 @@ class ModelsCommand extends Command
if ($type !== null) {
$newType = $this->getTypeOverride($type);
if ($nullable) {
$newType .= '|null';
$newType = $this->wrapIntersectionType($newType) . '|null';
}
$this->properties[$name]['type'] = $newType;
}
@@ -1100,6 +1208,7 @@ class ModelsCommand extends Command
$serializer = new DocBlockSerializer();
$docComment = $serializer->getDocComment($phpdoc);
$mixinClassName = null;
if ($this->write_mixin) {
$phpdocMixin = new DocBlock($reflection, new Context($namespace));
@@ -1136,6 +1245,14 @@ class ModelsCommand extends Command
$replace = "{$modelDocComment}\n";
$pos = strpos($contents, "final class {$classname}") ?: strpos($contents, "class {$classname}");
if ($pos !== false) {
// If PHP 8 attributes (e.g. #[ObservedBy(...)]) precede the class
// declaration, insert the docblock before the first attribute so that
// the resulting order is: docblock → attributes → class.
$before = substr($contents, 0, $pos);
if (preg_match('/((?:#\[.+?\]\s*)+)$/s', $before, $matches)) {
$pos -= strlen($matches[1]);
$replace = "{$modelDocComment}\n";
}
$contents = substr_replace($contents, $replace, $pos, 0);
}
}
@@ -1241,13 +1358,18 @@ class ModelsCommand extends Command
}
}
protected ?array $cachedRelationTypes = null;
protected ?array $cachedRelationReturnTypes = null;
/**
* Returns the available relation types
*/
protected function getRelationTypes(): array
{
$configuredRelations = $this->laravel['config']->get('ide-helper.additional_relation_types', []);
return array_merge(self::RELATION_TYPES, $configuredRelations);
return $this->cachedRelationTypes ??= array_merge(
self::RELATION_TYPES,
$this->laravel['config']->get('ide-helper.additional_relation_types', [])
);
}
/**
@@ -1255,7 +1377,7 @@ class ModelsCommand extends Command
*/
protected function getRelationReturnTypes(): array
{
return $this->laravel['config']->get('ide-helper.additional_relation_return_types', []);
return $this->cachedRelationReturnTypes ??= $this->laravel['config']->get('ide-helper.additional_relation_return_types', []);
}
/**
@@ -1271,9 +1393,6 @@ class ModelsCommand extends Command
*/
protected function getAttributeTypes(Model $model, \ReflectionMethod $reflectionMethod): Collection
{
// Private/protected ReflectionMethods require setAccessible prior to PHP 8.1
$reflectionMethod->setAccessible(true);
/** @var Attribute $attribute */
$attribute = $reflectionMethod->invoke($model);
@@ -1333,11 +1452,7 @@ class ModelsCommand extends Command
*/
protected function getCommentFromDocBlock(\ReflectionMethod $reflection)
{
$phpDocContext = (new ContextFactory())->createFromReflector($reflection);
$context = new Context(
$phpDocContext->getNamespace(),
$phpDocContext->getNamespaceAliases()
);
$context = $this->getDocBlockContext($reflection);
$comment = '';
$phpdoc = new DocBlock($reflection, $context);
@@ -1358,11 +1473,7 @@ class ModelsCommand extends Command
*/
protected function getReturnTypeFromDocBlock(\ReflectionMethod $reflection, ?\Reflector $reflectorForContext = null)
{
$phpDocContext = (new ContextFactory())->createFromReflector($reflectorForContext ?? $reflection);
$context = new Context(
$phpDocContext->getNamespace(),
$phpDocContext->getNamespaceAliases()
);
$context = $this->getDocBlockContext($reflectorForContext ?? $reflection);
$type = null;
$phpdoc = new DocBlock($reflection, $context);
@@ -1380,6 +1491,31 @@ class ModelsCommand extends Command
return $type;
}
protected function getDocBlockContext(\Reflector $reflector): Context
{
if ($reflector instanceof \ReflectionMethod) {
$key = $reflector->getDeclaringClass()->getName();
} elseif ($reflector instanceof ReflectionClass) {
$key = $reflector->getName();
} else {
$phpDocContext = (new ContextFactory())->createFromReflector($reflector);
return new Context(
$phpDocContext->getNamespace(),
$phpDocContext->getNamespaceAliases()
);
}
if (!isset($this->contextCache[$key])) {
$phpDocContext = (new ContextFactory())->createFromReflector($reflector);
$this->contextCache[$key] = new Context(
$phpDocContext->getNamespace(),
$phpDocContext->getNamespaceAliases()
);
}
return $this->contextCache[$key];
}
protected function getReturnTypeFromReflection(\ReflectionMethod $reflection): ?string
{
$returnType = $reflection->getReturnType();
@@ -1585,9 +1721,10 @@ class ModelsCommand extends Command
*/
protected function getUsedClassNames(ReflectionClass $reflection): array
{
$context = $this->getDocBlockContext($reflection);
$namespaceAliases = array_flip(array_map(function ($alias) {
return ltrim($alias, '\\');
}, (new ContextFactory())->createFromReflector($reflection)->getNamespaceAliases()));
}, $context->getNamespaceAliases()));
$namespaceAliases[$reflection->getName()] = $reflection->getShortName();
return $namespaceAliases;
@@ -1631,7 +1768,8 @@ class ModelsCommand extends Command
$type = implode('|', $types);
if ($paramType->allowsNull()) {
if (count($types) == 1) {
// Use ?Type syntax only for single named types, not for intersection types
if (count($types) == 1 && !str_starts_with($type, '(')) {
$type = '?' . $type;
} else {
$type .= '|null';
@@ -1649,7 +1787,7 @@ class ModelsCommand extends Command
preg_match(
'/@param ((?:(?:[\w?|\\\\<>])+(?:\[])?)+)/',
$docComment ?? '',
$docComment,
$matches
);
$type = $matches[1] ?? '';
@@ -1704,24 +1842,53 @@ class ModelsCommand extends Command
return $type;
}
protected function extractReflectionTypes(ReflectionType $reflection_type)
protected function extractReflectionTypes(ReflectionType $reflection_type): array
{
if ($reflection_type instanceof ReflectionNamedType) {
$types[] = $this->getReflectionNamedType($reflection_type);
} else {
$types = [];
foreach ($reflection_type->getTypes() as $named_type) {
if ($named_type->getName() === 'null') {
return [$this->getReflectionNamedType($reflection_type)];
}
if ($reflection_type instanceof \ReflectionIntersectionType) {
return [$this->formatIntersectionType($reflection_type)];
}
if ($reflection_type instanceof \ReflectionUnionType) {
return $this->extractUnionTypes($reflection_type);
}
// Unknown type - return empty array as fallback
return [];
}
protected function extractUnionTypes(\ReflectionUnionType $union_type): array
{
$types = [];
foreach ($union_type->getTypes() as $inner_type) {
if ($inner_type instanceof ReflectionNamedType) {
if ($inner_type->getName() === 'null') {
continue;
}
$types[] = $this->getReflectionNamedType($named_type);
$types[] = $this->getReflectionNamedType($inner_type);
} elseif ($inner_type instanceof \ReflectionIntersectionType) {
$types[] = $this->formatIntersectionType($inner_type);
}
// ReflectionUnionType cannot be nested per PHP's DNF rules
}
return $types;
}
protected function formatIntersectionType(\ReflectionIntersectionType $intersection_type): string
{
$parts = [];
foreach ($intersection_type->getTypes() as $type) {
$parts[] = $this->getReflectionNamedType($type);
}
return '(' . implode('&', $parts) . ')';
}
protected function getReflectionNamedType(ReflectionNamedType $paramType): string
{
$parameterName = $paramType->getName();
-36
View File
@@ -1,36 +0,0 @@
<?php
namespace Barryvdh\LaravelIdeHelper;
use Exception;
use Illuminate\Database\Eloquent\Factory;
use ReflectionClass;
class Factories
{
public static function all()
{
$factories = [];
if (static::isLaravelSevenOrLower()) {
$factory = app(Factory::class);
$definitions = (new ReflectionClass(Factory::class))->getProperty('definitions');
$definitions->setAccessible(true);
foreach ($definitions->getValue($factory) as $factory_target => $config) {
try {
$factories[] = new ReflectionClass($factory_target);
} catch (Exception $exception) {
}
}
}
return $factories;
}
protected static function isLaravelSevenOrLower()
{
return class_exists('Illuminate\Database\Eloquent\Factory');
}
}
+1 -2
View File
@@ -74,7 +74,7 @@ class Generator
/**
* Generate the helper file contents;
*
* @return string;
* @return string
*/
public function generate()
{
@@ -85,7 +85,6 @@ class Generator
->with('real_time_facades', $this->getRealTimeFacades())
->with('helpers', $this->detectHelpers())
->with('include_fluent', $this->config->get('ide-helper.include_fluent', true))
->with('factories', $this->config->get('ide-helper.include_factory_builders') ? Factories::all() : [])
->render();
}
+39 -10
View File
@@ -15,7 +15,6 @@ class Macro extends Method
* Macro constructor.
*
* @param \ReflectionFunctionAbstract $method
* @param string $alias
* @param \ReflectionClass $class
* @param null $methodName
* @param array $interfaces
@@ -24,14 +23,13 @@ class Macro extends Method
*/
public function __construct(
$method,
$alias,
$class,
$methodName = null,
$interfaces = [],
$classAliases = [],
$returnTypeNormalizers = []
) {
parent::__construct($method, $alias, $class, $methodName, $interfaces, $classAliases, $returnTypeNormalizers);
parent::__construct($method, $class, $methodName, $interfaces, $classAliases, $returnTypeNormalizers);
}
public static function setDefaultReturnTypes(array $map = [])
@@ -75,8 +73,8 @@ class Macro extends Method
$type = $this->concatReflectionTypes($return);
/** @psalm-suppress UndefinedClass */
if (!$return instanceof \ReflectionUnionType) {
/** @phpstan-ignore method.notFound */
$type .= $this->root === "\\{$builder}" && $return->getName() === $builder ? '|static' : '';
$type .= $return->allowsNull() ? '|null' : '';
}
@@ -93,17 +91,48 @@ class Macro extends Method
protected function concatReflectionTypes(?\ReflectionType $type): string
{
/** @psalm-suppress UndefinedClass */
$returnTypes = $type instanceof \ReflectionUnionType
? $type->getTypes()
: [$type];
if ($type instanceof \ReflectionNamedType) {
return $type->getName();
}
return Collection::make($returnTypes)
if ($type instanceof \ReflectionIntersectionType) {
return $this->formatIntersectionType($type);
}
if ($type instanceof \ReflectionUnionType) {
return $this->formatUnionType($type);
}
// Unknown or null type
return '';
}
protected function formatUnionType(\ReflectionUnionType $type): string
{
return Collection::make($type->getTypes())
->map(function (\ReflectionType $inner) {
if ($inner instanceof \ReflectionNamedType) {
return $inner->getName();
}
if ($inner instanceof \ReflectionIntersectionType) {
return $this->formatIntersectionType($inner);
}
// ReflectionUnionType cannot be nested per PHP's DNF rules
return null;
})
->filter()
->map->getName()
->implode('|');
}
protected function formatIntersectionType(\ReflectionIntersectionType $type): string
{
$parts = Collection::make($type->getTypes())
->map(fn (\ReflectionNamedType $t) => $t->getName())
->toArray();
return '(' . implode('&', $parts) . ')';
}
protected function addLocationToPhpDoc()
{
if ($this->method->name === '__invoke') {
+49 -4
View File
@@ -44,7 +44,6 @@ class Method
/**
* @param \ReflectionMethod|\ReflectionFunctionAbstract $method
* @param string $alias
* @param \ReflectionClass $class
* @param string|null $methodName
* @param array $interfaces
@@ -52,7 +51,7 @@ class Method
* @param array $returnTypeNormalizers
* @param string[] $templateNames
*/
public function __construct($method, $alias, $class, $methodName = null, $interfaces = [], array $classAliases = [], array $returnTypeNormalizers = [], array $templateNames = [])
public function __construct($method, $class, $methodName = null, $interfaces = [], array $classAliases = [], array $returnTypeNormalizers = [], array $templateNames = [])
{
$this->method = $method;
$this->interfaces = $interfaces;
@@ -77,6 +76,8 @@ class Method
} catch (\Exception $e) {
}
$this->removePhpDocParamTagsForOptionalParameters();
//Get the parameters, including formatted default values
$this->getParameters($method);
@@ -178,7 +179,7 @@ class Method
/**
* Get the parameters for this method
*
* @param bool $implode Wether to implode the array or not
* @param bool $implode Whether to implode the array or not
* @return string
*/
public function getParams($implode = true)
@@ -208,7 +209,7 @@ class Method
/**
* Get the parameters for this method including default values
*
* @param bool $implode Wether to implode the array or not
* @param bool $implode Whether to implode the array or not
* @return string
*/
public function getParamsWithDefault($implode = true)
@@ -249,6 +250,50 @@ class Method
}
}
/**
* Remove @param tags for optional reflection parameters so generated stubs match arity
* checks in static analysis (optional params still appear in the PHP signature).
*/
protected function removePhpDocParamTagsForOptionalParameters(): void
{
if (!$this->method instanceof \ReflectionMethod) {
return;
}
$declaring = $this->method->getDeclaringClass()->getName();
if (
$declaring !== \Illuminate\Database\Query\Builder::class
&& $declaring !== \Illuminate\Database\Eloquent\Builder::class
) {
return;
}
foreach ($this->method->getParameters() as $param) {
if (!$param->isOptional() || $param->isVariadic()) {
continue;
}
if (!$param->isDefaultValueAvailable()) {
continue;
}
$default = $param->getDefaultValue();
// Keep @param for null/array defaults (nullable and list defaults stay documented).
// Strip only non-null scalars (e.g. $boolean = 'and', $not = false) so tools that
// count @param tags do not report false "missing argument" errors on shortened calls.
if ($default === null || is_array($default) || !is_scalar($default)) {
continue;
}
$varName = '$' . $param->getName();
$paramTags = $this->phpdoc->getTagsByName('param');
foreach (array_values($paramTags) as $tag) {
if ($tag instanceof ParamTag && $tag->getVariableName() === $varName) {
$this->phpdoc->deleteTag($tag);
}
}
}
}
/**
* Normalize the parameters
*
+39
View File
@@ -9,6 +9,7 @@ use Barryvdh\LaravelIdeHelper\Macro;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Facade;
/**
* @internal
@@ -66,6 +67,22 @@ class AliasTest extends TestCase
$this->assertNotNull($this->getAliasMacro($alias, EloquentBuilder::class, $macro));
}
/**
* @covers ::detectFake
*/
public function testNoExceptionOnRequiredFakeParameters(): void
{
// Mock
$alias = new AliasMock();
// Prepare
$alias->setFacade(MockFacade::class);
$this->expectNotToPerformAssertions();
// Test
$alias->detectFake();
}
/**
* @covers ::detectTemplateNames
*/
@@ -118,4 +135,26 @@ class AliasMock extends Alias
{
parent::detectMethods();
}
public function detectFake()
{
parent::detectFake();
}
public function setFacade(string $facade)
{
$this->facade = $facade;
}
}
class MockFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'Illuminate\Foundation\Exceptions\Handler';
}
public static function fake(string $test1, $test2 = null)
{
}
}
@@ -50,5 +50,7 @@ abstract class AbstractModelsCommand extends TestCase
// Don't override integer -> int for tests
$config->set('ide-helper.type_overrides', []);
$config->set('ide-helper.write_model_relation_exists_properties', true);
}
}
@@ -42,8 +42,8 @@ use Illuminate\Database\Eloquent\Model;
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -21,6 +21,7 @@ use Illuminate\Database\Eloquent\Relations\MorphTo;
* @property-read string $not_comment
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationHasMany HasMany relations.
* @property-read int|null $relation_has_many_count
* @property-read bool|null $relation_has_many_exists
* @property-read Simple|null $relationHasOne Others relations.
* @property-read Model|\Eloquent $relationMorphTo MorphTo relations.
* @property-write mixed $first_name Set the user's first name.
@@ -12,6 +12,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* @property int $id
* @property-read SimpleCollection<int, Simple> $relationHasMany
* @property-read int|null $relation_has_many_count
* @property-read bool|null $relation_has_many_exists
* @method static SimpleCollection<int, static> all($columns = ['*'])
* @method static SimpleCollection<int, static> get($columns = ['*'])
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newModelQuery()
@@ -0,0 +1,218 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DnfTypes\Models;
use ArrayAccess;
use Countable;
use Illuminate\Database\Eloquent\Model;
use Iterator;
use Stringable;
use Traversable;
/**
* Test model covering all DNF type scenarios from PHP RFC.
*
* @see https://wiki.php.net/rfc/dnf_types
*/
class DnfTypeModel extends Model
{
// =========================================================================
// RFC Example 1: (A&B)|null - Intersection with null
// =========================================================================
/**
* Basic DNF: intersection OR null.
*/
public function getBasicDnfAttribute(): (Countable&Iterator)|null
{
return null;
}
// =========================================================================
// RFC Example 2: (A&B)|D - Intersection OR single type (no null)
// =========================================================================
/**
* Intersection OR single class type.
*/
public function getIntersectionOrClassAttribute(): (Countable&Iterator)|\stdClass
{
return new \stdClass();
}
// =========================================================================
// RFC Example 3: C|(X&D)|null - Single type OR intersection OR null
// =========================================================================
/**
* Single type OR intersection OR null.
*/
public function getSingleOrIntersectionOrNullAttribute(): \stdClass|(Countable&Iterator)|null
{
return null;
}
// =========================================================================
// RFC Example 4: (A&B&D)|int|null - Triple intersection OR primitive OR null
// =========================================================================
/**
* Triple intersection OR primitive OR null.
*/
public function getTripleIntersectionAttribute(): (Countable&Iterator&Traversable)|int|null
{
return null;
}
// =========================================================================
// RFC Example 5: (A&B)|(C&D)|null - Multiple intersection segments
// =========================================================================
/**
* Multiple intersection segments OR null.
*/
public function getMultipleIntersectionsAttribute(): (Countable&Iterator)|(ArrayAccess&Stringable)|null
{
return null;
}
// =========================================================================
// RFC Example 6: (A&B)|(C&D)|(E&F) - Multiple intersections without null
// =========================================================================
/**
* Multiple intersection segments without null.
*/
public function getMultipleIntersectionsNoNullAttribute(): (Countable&Iterator)|(ArrayAccess&Stringable)|(Traversable&Countable)
{
return new class () implements Countable, Iterator {
public function count(): int
{
return 0;
}
public function current(): mixed
{
return null;
}
public function key(): mixed
{
return null;
}
public function next(): void
{
}
public function rewind(): void
{
}
public function valid(): bool
{
return false;
}
};
}
// =========================================================================
// Pure intersection type (A&B) - No union, just intersection
// =========================================================================
/**
* Pure intersection type without union.
*/
public function getPureIntersectionAttribute(): Countable&Iterator
{
return new class () implements Countable, Iterator {
public function count(): int
{
return 0;
}
public function current(): mixed
{
return null;
}
public function key(): mixed
{
return null;
}
public function next(): void
{
}
public function rewind(): void
{
}
public function valid(): bool
{
return false;
}
};
}
// =========================================================================
// Parameter context: DNF types in method parameters
// =========================================================================
/**
* Scope with DNF parameter: (A&B)|null.
*/
public function scopeWithBasicDnfParam(
\Illuminate\Database\Query\Builder $query,
(Countable&Iterator)|null $param
): \Illuminate\Database\Query\Builder {
return $query;
}
/**
* Scope with complex DNF parameter: C|(A&B)|null.
*/
public function scopeWithComplexDnfParam(
\Illuminate\Database\Query\Builder $query,
\stdClass|(Countable&Iterator)|null $param
): \Illuminate\Database\Query\Builder {
return $query;
}
/**
* Scope with multiple intersection parameters.
*/
public function scopeWithMultipleIntersectionParam(
\Illuminate\Database\Query\Builder $query,
(Countable&Iterator)|(ArrayAccess&Stringable) $param
): \Illuminate\Database\Query\Builder {
return $query;
}
/**
* Scope with intersection OR primitive parameter.
*/
public function scopeWithIntersectionOrPrimitive(
\Illuminate\Database\Query\Builder $query,
(Countable&Iterator)|int $param
): \Illuminate\Database\Query\Builder {
return $query;
}
// =========================================================================
// Mixed: DNF in both parameter and return type
// =========================================================================
/**
* DNF in both parameter and return type.
*/
public function scopeWithDnfParamAndReturn(
\Illuminate\Database\Query\Builder $query,
(Countable&Iterator)|null $param
): (Countable&Iterator)|\Illuminate\Database\Query\Builder {
return $query;
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DnfTypes;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
@@ -0,0 +1,234 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DnfTypes\Models;
use ArrayAccess;
use Countable;
use Illuminate\Database\Eloquent\Model;
use Iterator;
use Stringable;
use Traversable;
/**
* Test model covering all DNF type scenarios from PHP RFC.
*
* @see https://wiki.php.net/rfc/dnf_types
* @property-read (\Countable&\Iterator)|null $basic_dnf
* @property-read (\Countable&\Iterator)|\stdClass $intersection_or_class
* @property-read (\Countable&\Iterator)|(\ArrayAccess&\Stringable)|null $multiple_intersections
* @property-read (\Countable&\Iterator)|(\ArrayAccess&\Stringable)|(\Traversable&\Countable) $multiple_intersections_no_null
* @property-read (\Countable&\Iterator) $pure_intersection
* @property-read \stdClass|(\Countable&\Iterator)|null $single_or_intersection_or_null
* @property-read (\Countable&\Iterator&\Traversable)|int|null $triple_intersection
* @method static \Illuminate\Database\Eloquent\Builder<static>|DnfTypeModel newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DnfTypeModel newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DnfTypeModel query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|DnfTypeModel withBasicDnfParam((\Countable&\Iterator)|null $param)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DnfTypeModel withComplexDnfParam(\stdClass|(\Countable&\Iterator)|null $param)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DnfTypeModel withDnfParamAndReturn((\Countable&\Iterator)|null $param)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DnfTypeModel withIntersectionOrPrimitive((\Countable&\Iterator)|int $param)
* @method static \Illuminate\Database\Eloquent\Builder<static>|DnfTypeModel withMultipleIntersectionParam((\Countable&\Iterator)|(\ArrayAccess&\Stringable) $param)
* @mixin \Eloquent
*/
class DnfTypeModel extends Model
{
// =========================================================================
// RFC Example 1: (A&B)|null - Intersection with null
// =========================================================================
/**
* Basic DNF: intersection OR null.
*/
public function getBasicDnfAttribute(): (Countable&Iterator)|null
{
return null;
}
// =========================================================================
// RFC Example 2: (A&B)|D - Intersection OR single type (no null)
// =========================================================================
/**
* Intersection OR single class type.
*/
public function getIntersectionOrClassAttribute(): (Countable&Iterator)|\stdClass
{
return new \stdClass();
}
// =========================================================================
// RFC Example 3: C|(X&D)|null - Single type OR intersection OR null
// =========================================================================
/**
* Single type OR intersection OR null.
*/
public function getSingleOrIntersectionOrNullAttribute(): \stdClass|(Countable&Iterator)|null
{
return null;
}
// =========================================================================
// RFC Example 4: (A&B&D)|int|null - Triple intersection OR primitive OR null
// =========================================================================
/**
* Triple intersection OR primitive OR null.
*/
public function getTripleIntersectionAttribute(): (Countable&Iterator&Traversable)|int|null
{
return null;
}
// =========================================================================
// RFC Example 5: (A&B)|(C&D)|null - Multiple intersection segments
// =========================================================================
/**
* Multiple intersection segments OR null.
*/
public function getMultipleIntersectionsAttribute(): (Countable&Iterator)|(ArrayAccess&Stringable)|null
{
return null;
}
// =========================================================================
// RFC Example 6: (A&B)|(C&D)|(E&F) - Multiple intersections without null
// =========================================================================
/**
* Multiple intersection segments without null.
*/
public function getMultipleIntersectionsNoNullAttribute(): (Countable&Iterator)|(ArrayAccess&Stringable)|(Traversable&Countable)
{
return new class () implements Countable, Iterator {
public function count(): int
{
return 0;
}
public function current(): mixed
{
return null;
}
public function key(): mixed
{
return null;
}
public function next(): void
{
}
public function rewind(): void
{
}
public function valid(): bool
{
return false;
}
};
}
// =========================================================================
// Pure intersection type (A&B) - No union, just intersection
// =========================================================================
/**
* Pure intersection type without union.
*/
public function getPureIntersectionAttribute(): Countable&Iterator
{
return new class () implements Countable, Iterator {
public function count(): int
{
return 0;
}
public function current(): mixed
{
return null;
}
public function key(): mixed
{
return null;
}
public function next(): void
{
}
public function rewind(): void
{
}
public function valid(): bool
{
return false;
}
};
}
// =========================================================================
// Parameter context: DNF types in method parameters
// =========================================================================
/**
* Scope with DNF parameter: (A&B)|null.
*/
public function scopeWithBasicDnfParam(
\Illuminate\Database\Query\Builder $query,
(Countable&Iterator)|null $param
): \Illuminate\Database\Query\Builder {
return $query;
}
/**
* Scope with complex DNF parameter: C|(A&B)|null.
*/
public function scopeWithComplexDnfParam(
\Illuminate\Database\Query\Builder $query,
\stdClass|(Countable&Iterator)|null $param
): \Illuminate\Database\Query\Builder {
return $query;
}
/**
* Scope with multiple intersection parameters.
*/
public function scopeWithMultipleIntersectionParam(
\Illuminate\Database\Query\Builder $query,
(Countable&Iterator)|(ArrayAccess&Stringable) $param
): \Illuminate\Database\Query\Builder {
return $query;
}
/**
* Scope with intersection OR primitive parameter.
*/
public function scopeWithIntersectionOrPrimitive(
\Illuminate\Database\Query\Builder $query,
(Countable&Iterator)|int $param
): \Illuminate\Database\Query\Builder {
return $query;
}
// =========================================================================
// Mixed: DNF in both parameter and return type
// =========================================================================
/**
* DNF in both parameter and return type.
*/
public function scopeWithDnfParamAndReturn(
\Illuminate\Database\Query\Builder $query,
(Countable&Iterator)|null $param
): (Countable&Iterator)|\Illuminate\Database\Query\Builder {
return $query;
}
}
@@ -48,8 +48,8 @@ namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\DoesNotGenerateP
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -12,6 +12,7 @@ use Illuminate\Database\Eloquent\Relations\HasOne;
/**
* @property-read \Illuminate\Database\Eloquent\Collection<int, Dynamic> $regularHasMany
* @property-read int|null $regular_has_many_count
* @property-read bool|null $regular_has_many_exists
* @method static \Illuminate\Database\Eloquent\Builder<static>|Dynamic newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Dynamic newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Dynamic query()
@@ -44,8 +44,8 @@ use Illuminate\Database\Eloquent\Model;
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -42,8 +42,8 @@ use Illuminate\Database\Eloquent\Model;
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -42,8 +42,8 @@ use Illuminate\Database\Eloquent\Model;
* @property float $floatNotNullable
* @property float|null $doubleNullable
* @property float $doubleNotNullable
* @property string|null $decimalNullable
* @property string $decimalNotNullable
* @property numeric|null $decimalNullable
* @property numeric $decimalNotNullable
* @property int|null $booleanNullable
* @property int $booleanNotNullable
* @property string|null $enumNullable
@@ -42,8 +42,8 @@ use Illuminate\Database\Eloquent\Model;
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -48,8 +48,8 @@ namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWi
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -43,8 +43,8 @@ use Illuminate\Database\Eloquent\Model;
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -44,8 +44,8 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -82,6 +82,7 @@ use Illuminate\Database\Eloquent\SoftDeletes;
* @property \Illuminate\Support\Carbon|null $updated_at
* @property-read \Illuminate\Database\Eloquent\Collection<int, \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithForcedFqn\Models\Post> $posts
* @property-read int|null $posts_count
* @property-read bool|null $posts_exists
* @method static \Illuminate\Database\Eloquent\Builder<static>|\Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithForcedFqn\Models\Post newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|\Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithForcedFqn\Models\Post newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|\Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWithForcedFqn\Models\Post null(string $unusedParam)
@@ -50,8 +50,8 @@ use Illuminate\Support\Carbon;
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -88,6 +88,7 @@ use Illuminate\Support\Carbon;
* @property Carbon|null $updated_at
* @property-read Collection<int, Post> $posts
* @property-read int|null $posts_count
* @property-read bool|null $posts_exists
* @method static EloquentBuilder<static>|Post newModelQuery()
* @method static EloquentBuilder<static>|Post newQuery()
* @method static EloquentBuilder<static>|Post null(string $unusedParam)
@@ -48,8 +48,8 @@ namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWi
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -95,8 +95,8 @@ namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\GeneratePhpdocWi
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -12,8 +12,10 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* @property int $id
* @property-read \Illuminate\Database\Eloquent\Collection|Simple[] $regularBelongsToMany
* @property-read int|null $regular_belongs_to_many_count
* @property-read bool|null $regular_belongs_to_many_exists
* @property-read \Illuminate\Database\Eloquent\Collection|Simple[] $regularHasMany
* @property-read int|null $regular_has_many_count
* @property-read bool|null $regular_has_many_exists
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple query()
@@ -42,8 +42,8 @@ use Illuminate\Database\Eloquent\Model;
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\MorphToIntersection\Models;
use Illuminate\Database\Eloquent\Model;
abstract class BaseModel extends Model
{
}
@@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\MorphToIntersection\Models;
interface CanBeAssigned
{
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\MorphToIntersection\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class MorphToIntersection extends Model
{
protected $table = 'morphs';
/** @return MorphTo<(BaseModel&CanBeAssigned), $this> */
public function assigneeWithParens(): MorphTo
{
return $this->morphTo(type: 'nullable_relation_morph_to_type', id: 'nullable_relation_morph_to_id');
}
/** @return MorphTo<BaseModel&CanBeAssigned, $this> */
public function assigneeWithoutParens(): MorphTo
{
return $this->morphTo(type: 'nullable_relation_morph_to_type', id: 'nullable_relation_morph_to_id');
}
/** @return MorphTo<(BaseModel&CanBeAssigned), $this> */
public function nonNullableAssignee(): MorphTo
{
return $this->morphTo(type: 'relation_morph_to_type', id: 'relation_morph_to_id');
}
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\MorphToIntersection;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
@@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\MorphToIntersection\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphTo;
/**
* @property string $relation_morph_to_type
* @property int $relation_morph_to_id
* @property string|null $nullable_relation_morph_to_type
* @property int|null $nullable_relation_morph_to_id
* @property-read (BaseModel&CanBeAssigned)|null $assigneeWithParens
* @property-read (BaseModel&CanBeAssigned)|null $assigneeWithoutParens
* @property-read (BaseModel&CanBeAssigned) $nonNullableAssignee
* @method static \Illuminate\Database\Eloquent\Builder<static>|MorphToIntersection newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|MorphToIntersection newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|MorphToIntersection query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|MorphToIntersection whereNullableRelationMorphToId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|MorphToIntersection whereNullableRelationMorphToType($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|MorphToIntersection whereRelationMorphToId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|MorphToIntersection whereRelationMorphToType($value)
* @mixin \Eloquent
*/
class MorphToIntersection extends Model
{
protected $table = 'morphs';
/** @return MorphTo<(BaseModel&CanBeAssigned), $this> */
public function assigneeWithParens(): MorphTo
{
return $this->morphTo(type: 'nullable_relation_morph_to_type', id: 'nullable_relation_morph_to_id');
}
/** @return MorphTo<BaseModel&CanBeAssigned, $this> */
public function assigneeWithoutParens(): MorphTo
{
return $this->morphTo(type: 'nullable_relation_morph_to_type', id: 'nullable_relation_morph_to_id');
}
/** @return MorphTo<(BaseModel&CanBeAssigned), $this> */
public function nonNullableAssignee(): MorphTo
{
return $this->morphTo(type: 'relation_morph_to_type', id: 'relation_morph_to_id');
}
}
@@ -0,0 +1,14 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PhpAttributesBeforeClass\Models;
use Illuminate\Database\Eloquent\Model;
// Tests: final class + attribute with nested array argument (e.g. ObservedBy([...]))
#[ObservedByStub([StubObserver::class])]
final class FinalWithNested extends Model
{
protected $table = 'simples';
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PhpAttributesBeforeClass\Models;
use Illuminate\Database\Eloquent\Model;
// Tests: multiple consecutive PHP 8 attributes before the class declaration
#[\AllowDynamicProperties]
#[SecondAttribute]
class MultipleAttributes extends Model
{
protected $table = 'simples';
}
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PhpAttributesBeforeClass\Models;
use Illuminate\Database\Eloquent\Model;
#[\AllowDynamicProperties]
class Simple extends Model
{
}
@@ -0,0 +1,24 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PhpAttributesBeforeClass;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PhpAttributesBeforeClass\Models;
use Illuminate\Database\Eloquent\Model;
// Tests: final class + attribute with nested array argument (e.g. ObservedBy([...]))
/**
* @property int $id
* @method static \Illuminate\Database\Eloquent\Builder<static>|FinalWithNested newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|FinalWithNested newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|FinalWithNested query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|FinalWithNested whereId($value)
* @mixin \Eloquent
*/
#[ObservedByStub([StubObserver::class])]
final class FinalWithNested extends Model
{
protected $table = 'simples';
}
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PhpAttributesBeforeClass\Models;
use Illuminate\Database\Eloquent\Model;
// Tests: multiple consecutive PHP 8 attributes before the class declaration
/**
* @property int $id
* @method static \Illuminate\Database\Eloquent\Builder<static>|MultipleAttributes newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|MultipleAttributes newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|MultipleAttributes query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|MultipleAttributes whereId($value)
* @mixin \Eloquent
*/
#[\AllowDynamicProperties]
#[SecondAttribute]
class MultipleAttributes extends Model
{
protected $table = 'simples';
}
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\PhpAttributesBeforeClass\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple whereId($value)
* @mixin \Eloquent
*/
#[\AllowDynamicProperties]
class Simple extends Model
{
}
@@ -12,16 +12,21 @@ use Illuminate\Database\Eloquent\Model;
* @property-read DifferentCustomPivot|CustomPivot|null $pivot
* @property-read \Illuminate\Database\Eloquent\Collection<int, ModelWithPivot> $relationCustomPivotUsingSameAccessor
* @property-read int|null $relation_custom_pivot_using_same_accessor_count
* @property-read bool|null $relation_custom_pivot_using_same_accessor_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, ModelWithPivot> $relationCustomPivotUsingSameAccessorAndClass
* @property-read int|null $relation_custom_pivot_using_same_accessor_and_class_count
* @property-read bool|null $relation_custom_pivot_using_same_accessor_and_class_exists
* @property-read CustomPivot|null $customAccessor
* @property-read \Illuminate\Database\Eloquent\Collection<int, ModelWithPivot> $relationWithCustomPivot
* @property-read int|null $relation_with_custom_pivot_count
* @property-read bool|null $relation_with_custom_pivot_exists
* @property-read DifferentCustomPivot|null $differentCustomAccessor
* @property-read \Illuminate\Database\Eloquent\Collection<int, ModelWithPivot> $relationWithDifferentCustomPivot
* @property-read int|null $relation_with_different_custom_pivot_count
* @property-read bool|null $relation_with_different_custom_pivot_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, ModelWithPivot> $relationWithDifferentCustomPivotUsingSameAccessor
* @property-read int|null $relation_with_different_custom_pivot_using_same_accessor_count
* @property-read bool|null $relation_with_different_custom_pivot_using_same_accessor_exists
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithPivot newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithPivot newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithPivot query()
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\QueryMethods\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\QueryMethods;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
protected function getEnvironmentSetUp($app)
{
parent::getEnvironmentSetUp($app);
$app['config']->set('ide-helper.write_query_methods', false);
}
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
$this->assertStringNotContainsString("@method static \Illuminate\Database\Eloquent\Builder<static>|Post query()", $this->mockFilesystemOutput);
}
}
@@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\QueryMethods\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string|null $char_nullable
* @property string $char_not_nullable
* @property string|null $string_nullable
* @property string $string_not_nullable
* @property string|null $text_nullable
* @property string $text_not_nullable
* @property string|null $medium_text_nullable
* @property string $medium_text_not_nullable
* @property string|null $long_text_nullable
* @property string $long_text_not_nullable
* @property int|null $integer_nullable
* @property int $integer_not_nullable
* @property int|null $tiny_integer_nullable
* @property int $tiny_integer_not_nullable
* @property int|null $small_integer_nullable
* @property int $small_integer_not_nullable
* @property int|null $medium_integer_nullable
* @property int $medium_integer_not_nullable
* @property int|null $big_integer_nullable
* @property int $big_integer_not_nullable
* @property int|null $unsigned_integer_nullable
* @property int $unsigned_integer_not_nullable
* @property int|null $unsigned_tiny_integer_nullable
* @property int $unsigned_tiny_integer_not_nullable
* @property int|null $unsigned_small_integer_nullable
* @property int $unsigned_small_integer_not_nullable
* @property int|null $unsigned_medium_integer_nullable
* @property int $unsigned_medium_integer_not_nullable
* @property int|null $unsigned_big_integer_nullable
* @property int $unsigned_big_integer_not_nullable
* @property float|null $float_nullable
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
* @property string $enum_not_nullable
* @property string|null $json_nullable
* @property string $json_not_nullable
* @property string|null $jsonb_nullable
* @property string $jsonb_not_nullable
* @property string|null $date_nullable
* @property string $date_not_nullable
* @property string|null $datetime_nullable
* @property string $datetime_not_nullable
* @property string|null $datetimetz_nullable
* @property string $datetimetz_not_nullable
* @property string|null $time_nullable
* @property string $time_not_nullable
* @property string|null $timetz_nullable
* @property string $timetz_not_nullable
* @property string|null $timestamp_nullable
* @property string $timestamp_not_nullable
* @property string|null $timestamptz_nullable
* @property string $timestamptz_not_nullable
* @property int|null $year_nullable
* @property int $year_not_nullable
* @property string|null $binary_nullable
* @property string $binary_not_nullable
* @property string|null $uuid_nullable
* @property string $uuid_not_nullable
* @property string|null $ipaddress_nullable
* @property string $ipaddress_not_nullable
* @property string|null $macaddress_nullable
* @property string $macaddress_not_nullable
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBigIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBigIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBinaryNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBinaryNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBooleanNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereBooleanNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereCharNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereCharNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDateNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDateNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimeNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimeNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimetzNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDatetimetzNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDecimalNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDecimalNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDoubleNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereDoubleNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereEnumNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereEnumNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereFloatNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereFloatNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIpaddressNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereIpaddressNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonbNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereJsonbNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereLongTextNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereLongTextNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMacaddressNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMacaddressNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumTextNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereMediumTextNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereSmallIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereSmallIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereStringNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereStringNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTextNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTextNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimeNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimeNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestampNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestampNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestamptzNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimestamptzNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimetzNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTimetzNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTinyIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereTinyIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedBigIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedBigIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedMediumIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedMediumIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedSmallIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedSmallIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedTinyIntegerNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUnsignedTinyIntegerNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUpdatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUuidNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereUuidNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereYearNotNullable($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|Post whereYearNullable($value)
* @mixin \Eloquent
*/
class Post extends Model
{
}
@@ -81,8 +81,8 @@ namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\QueryScopes\Mode
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -14,6 +14,7 @@ class Test extends AbstractModelsCommand
parent::getEnvironmentSetUp($app);
$app['config']->set('ide-helper.write_model_relation_count_properties', false);
$app['config']->set('ide-helper.write_model_relation_exists_properties', false);
}
public function test(): void
@@ -43,8 +43,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* @property float $float_not_nullable
* @property float|null $double_nullable
* @property float $double_not_nullable
* @property string|null $decimal_nullable
* @property string $decimal_not_nullable
* @property numeric|null $decimal_nullable
* @property numeric $decimal_not_nullable
* @property int|null $boolean_nullable
* @property int $boolean_not_nullable
* @property string|null $enum_nullable
@@ -133,26 +133,34 @@ use Illuminate\Database\Eloquent\Relations\MorphToMany;
* @property-read AnotherModel $relationBelongsToInAnotherNamespace
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToMany
* @property-read int|null $relation_belongs_to_many_count
* @property-read bool|null $relation_belongs_to_many_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToManyWithSub
* @property-read int|null $relation_belongs_to_many_with_sub_count
* @property-read bool|null $relation_belongs_to_many_with_sub_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToManyWithSubAnother
* @property-read int|null $relation_belongs_to_many_with_sub_another_count
* @property-read bool|null $relation_belongs_to_many_with_sub_another_exists
* @property-read AnotherModel $relationBelongsToSameNameAsColumn
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationHasMany
* @property-read int|null $relation_has_many_count
* @property-read bool|null $relation_has_many_exists
* @property-read Simple|null $relationHasOne
* @property-read Simple $relationHasOneWithDefault
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationMorphMany
* @property-read int|null $relation_morph_many_count
* @property-read bool|null $relation_morph_many_exists
* @property-read Simple|null $relationMorphOne
* @property-read Model|\Eloquent $relationMorphTo
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationMorphedByMany
* @property-read int|null $relation_morphed_by_many_count
* @property-read bool|null $relation_morphed_by_many_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationSampleRelationType
* @property-read int|null $relation_sample_relation_type_count
* @property-read bool|null $relation_sample_relation_type_exists
* @property-read Model|\Eloquent $relationSampleToAnyMorphedRelationType
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationSampleToAnyRelationType
* @property-read int|null $relation_sample_to_any_relation_type_count
* @property-read bool|null $relation_sample_to_any_relation_type_exists
* @property-read Simple $relationSampleToBadlyNamedNotManyRelation
* @property-read Simple $relationSampleToManyRelationType
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newModelQuery()
@@ -133,26 +133,34 @@ use Illuminate\Database\Eloquent\Relations\MorphToMany;
* @property-read AnotherModel|null $relationBelongsToInAnotherNamespace
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToMany
* @property-read int|null $relation_belongs_to_many_count
* @property-read bool|null $relation_belongs_to_many_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToManyWithSub
* @property-read int|null $relation_belongs_to_many_with_sub_count
* @property-read bool|null $relation_belongs_to_many_with_sub_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationBelongsToManyWithSubAnother
* @property-read int|null $relation_belongs_to_many_with_sub_another_count
* @property-read bool|null $relation_belongs_to_many_with_sub_another_exists
* @property-read AnotherModel|null $relationBelongsToSameNameAsColumn
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationHasMany
* @property-read int|null $relation_has_many_count
* @property-read bool|null $relation_has_many_exists
* @property-read Simple|null $relationHasOne
* @property-read Simple $relationHasOneWithDefault
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationMorphMany
* @property-read int|null $relation_morph_many_count
* @property-read bool|null $relation_morph_many_exists
* @property-read Simple|null $relationMorphOne
* @property-read Model|\Eloquent $relationMorphTo
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationMorphedByMany
* @property-read int|null $relation_morphed_by_many_count
* @property-read bool|null $relation_morphed_by_many_exists
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationSampleRelationType
* @property-read int|null $relation_sample_relation_type_count
* @property-read bool|null $relation_sample_relation_type_exists
* @property-read Model|\Eloquent $relationSampleToAnyMorphedRelationType
* @property-read \Illuminate\Database\Eloquent\Collection<int, Simple> $relationSampleToAnyRelationType
* @property-read int|null $relation_sample_to_any_relation_type_count
* @property-read bool|null $relation_sample_to_any_relation_type_exists
* @property-read Simple $relationSampleToBadlyNamedNotManyRelation
* @property-read Simple $relationSampleToManyRelationType
* @method static \Illuminate\Database\Eloquent\Builder<static>|Simple newModelQuery()
@@ -0,0 +1,49 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
class ModelWithRelations extends Model
{
protected $table = 'models_with_relations';
public function softDeletable(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id');
}
public function softDeletableWithTrashed(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id')->withTrashed();
}
public function softDeletableOnlyTrashed(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id')->onlyTrashed();
}
public function softDeletableWithoutTrashed(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id')->withoutTrashed();
}
public function nonSoftDeletable(): BelongsTo
{
return $this->belongsTo(NonSoftDeletableModel::class, 'non_soft_deletable_model_id');
}
public function softDeletableHasOne(): HasOne
{
return $this->hasOne(SoftDeletableModel::class, 'model_with_relations_id');
}
public function nonSoftDeletableHasOne(): HasOne
{
return $this->hasOne(NonSoftDeletableModel::class, 'model_with_relations_id');
}
}
@@ -0,0 +1,11 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models;
use Illuminate\Database\Eloquent\Model;
class NonSoftDeletableModel extends Model
{
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class SoftDeletableModel extends Model
{
use SoftDeletes;
}
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
use Illuminate\Support\Facades\Config;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
public function testSoftDeletesForceNullableDisabled(): void
{
Config::set('ide-helper.soft_deletes_force_nullable', false);
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
Config::set('ide-helper.soft_deletes_force_nullable', true);
}
}
@@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
/**
* @property int $id
* @property int $soft_deletable_model_id
* @property int $non_soft_deletable_model_id
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\NonSoftDeletableModel $nonSoftDeletable
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\NonSoftDeletableModel|null $nonSoftDeletableHasOne
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\SoftDeletableModel $softDeletable
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\SoftDeletableModel|null $softDeletableHasOne
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\SoftDeletableModel $softDeletableOnlyTrashed
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\SoftDeletableModel $softDeletableWithTrashed
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\SoftDeletableModel $softDeletableWithoutTrashed
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations whereNonSoftDeletableModelId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations whereSoftDeletableModelId($value)
* @mixin \Eloquent
*/
class ModelWithRelations extends Model
{
protected $table = 'models_with_relations';
public function softDeletable(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id');
}
public function softDeletableWithTrashed(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id')->withTrashed();
}
public function softDeletableOnlyTrashed(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id')->onlyTrashed();
}
public function softDeletableWithoutTrashed(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id')->withoutTrashed();
}
public function nonSoftDeletable(): BelongsTo
{
return $this->belongsTo(NonSoftDeletableModel::class, 'non_soft_deletable_model_id');
}
public function softDeletableHasOne(): HasOne
{
return $this->hasOne(SoftDeletableModel::class, 'model_with_relations_id');
}
public function nonSoftDeletableHasOne(): HasOne
{
return $this->hasOne(NonSoftDeletableModel::class, 'model_with_relations_id');
}
}
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property int|null $model_with_relations_id
* @method static \Illuminate\Database\Eloquent\Builder<static>|NonSoftDeletableModel newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|NonSoftDeletableModel newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|NonSoftDeletableModel query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|NonSoftDeletableModel whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|NonSoftDeletableModel whereModelWithRelationsId($value)
* @mixin \Eloquent
*/
class NonSoftDeletableModel extends Model
{
}
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* @property int $id
* @property int|null $model_with_relations_id
* @property \Illuminate\Support\Carbon|null $deleted_at
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel onlyTrashed()
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel whereDeletedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel whereModelWithRelationsId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel withTrashed(bool $withTrashed = true)
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel withoutTrashed()
* @mixin \Eloquent
*/
class SoftDeletableModel extends Model
{
use SoftDeletes;
}
@@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
/**
* @property int $id
* @property int $soft_deletable_model_id
* @property int $non_soft_deletable_model_id
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\NonSoftDeletableModel $nonSoftDeletable
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\NonSoftDeletableModel|null $nonSoftDeletableHasOne
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\SoftDeletableModel|null $softDeletable
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\SoftDeletableModel|null $softDeletableHasOne
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\SoftDeletableModel|null $softDeletableOnlyTrashed
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\SoftDeletableModel $softDeletableWithTrashed
* @property-read \Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models\SoftDeletableModel|null $softDeletableWithoutTrashed
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations whereNonSoftDeletableModelId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|ModelWithRelations whereSoftDeletableModelId($value)
* @mixin \Eloquent
*/
class ModelWithRelations extends Model
{
protected $table = 'models_with_relations';
public function softDeletable(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id');
}
public function softDeletableWithTrashed(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id')->withTrashed();
}
public function softDeletableOnlyTrashed(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id')->onlyTrashed();
}
public function softDeletableWithoutTrashed(): BelongsTo
{
return $this->belongsTo(SoftDeletableModel::class, 'soft_deletable_model_id')->withoutTrashed();
}
public function nonSoftDeletable(): BelongsTo
{
return $this->belongsTo(NonSoftDeletableModel::class, 'non_soft_deletable_model_id');
}
public function softDeletableHasOne(): HasOne
{
return $this->hasOne(SoftDeletableModel::class, 'model_with_relations_id');
}
public function nonSoftDeletableHasOne(): HasOne
{
return $this->hasOne(NonSoftDeletableModel::class, 'model_with_relations_id');
}
}
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property int|null $model_with_relations_id
* @method static \Illuminate\Database\Eloquent\Builder<static>|NonSoftDeletableModel newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|NonSoftDeletableModel newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|NonSoftDeletableModel query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|NonSoftDeletableModel whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|NonSoftDeletableModel whereModelWithRelationsId($value)
* @mixin \Eloquent
*/
class NonSoftDeletableModel extends Model
{
}
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\SoftDeletesRelations\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* @property int $id
* @property int|null $model_with_relations_id
* @property \Illuminate\Support\Carbon|null $deleted_at
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel onlyTrashed()
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel whereDeletedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel whereModelWithRelationsId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel withTrashed(bool $withTrashed = true)
* @method static \Illuminate\Database\Eloquent\Builder<static>|SoftDeletableModel withoutTrashed()
* @mixin \Eloquent
*/
class SoftDeletableModel extends Model
{
use SoftDeletes;
}
@@ -12,6 +12,7 @@ use Illuminate\Database\Query\Builder;
* @property-read string|int|null $foo
* @property-read \Illuminate\Database\Eloquent\Collection<int, UnionTypeModel> $withUnionTypeReturn
* @property-read int|null $with_union_type_return_count
* @property-read bool|null $with_union_type_return_exists
* @method static \Illuminate\Database\Eloquent\Builder<static>|UnionTypeModel newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|UnionTypeModel newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|UnionTypeModel query()
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\UniqueColumn\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users_unique';
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\UniqueColumn;
use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
use Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\AbstractModelsCommand;
class Test extends AbstractModelsCommand
{
public function test(): void
{
$command = $this->app->make(ModelsCommand::class);
$tester = $this->runCommand($command, [
'--write' => true,
]);
$this->assertSame(0, $tester->getStatusCode());
$this->assertStringContainsString('Written new phpDocBlock to', $tester->getDisplay());
$this->assertMatchesMockedSnapshot();
}
}
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Console\ModelsCommand\UniqueColumn\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $name
* @property string $email
* @property string $password
* @property \Illuminate\Support\Carbon|null $created_at
* @property \Illuminate\Support\Carbon|null $updated_at
* @method static \Illuminate\Database\Eloquent\Builder<static>|User newModelQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|User newQuery()
* @method static \Illuminate\Database\Eloquent\Builder<static>|User query()
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereCreatedAt($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereEmail($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereId($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereName($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User wherePassword($value)
* @method static \Illuminate\Database\Eloquent\Builder<static>|User whereUpdatedAt($value)
* @mixin \Eloquent
*/
class User extends Model
{
protected $table = 'users_unique';
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class SoftDeletesRelationsTable extends Migration
{
public function up(): void
{
Schema::create('soft_deletable_models', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('model_with_relations_id')->nullable();
$table->softDeletes();
});
Schema::create('non_soft_deletable_models', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('model_with_relations_id')->nullable();
});
Schema::create('models_with_relations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('soft_deletable_model_id');
$table->unsignedBigInteger('non_soft_deletable_model_id');
$table->foreign('soft_deletable_model_id')
->references('id')
->on('soft_deletable_models');
$table->foreign('non_soft_deletable_model_id')
->references('id')
->on('non_soft_deletable_models');
});
}
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class UsersUniqueTable extends Migration
{
public function up(): void
{
Schema::create('users_unique', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
}
}
-18
View File
@@ -1,18 +0,0 @@
<?php
declare(strict_types=1);
namespace Barryvdh\LaravelIdeHelper\Tests\Factories;
use Barryvdh\LaravelIdeHelper\Factories;
use PHPUnit\Framework\TestCase;
class AllTest extends TestCase
{
public function testAll(): void
{
$factories = Factories::all();
self::assertEmpty($factories);
}
}
+60 -3
View File
@@ -207,6 +207,63 @@ class MacroTest extends TestCase
$this->assertEquals('@return \Stringable|string|null', $this->tagsToString($phpdoc, 'return'));
}
public function testInitPhpDocParamsWithDnfTypes(): void
{
$phpdoc = (new MacroMock())->getPhpDoc(eval(<<<'PHP'
return new ReflectionFunction(
/**
* Test docblock with DNF types.
*/
function ((\Countable&\Iterator)|null $a): (\Countable&\Iterator)|\stdClass|null {
return $a;
}
);
PHP));
$this->assertNotNull($phpdoc);
$this->assertStringContainsString('Test docblock with DNF types', $phpdoc->getText());
$this->assertEquals('@param (Countable&Iterator)|null $a', $this->tagsToString($phpdoc, 'param'));
$this->assertEquals('@return (Countable&Iterator)|\stdClass|null', $this->tagsToString($phpdoc, 'return'));
}
public function testInitPhpDocParamsWithPureIntersectionType(): void
{
$phpdoc = (new MacroMock())->getPhpDoc(eval(<<<'PHP'
return new ReflectionFunction(
/**
* Test docblock with pure intersection type.
*/
function (\Countable&\Iterator $a): \Countable&\Iterator {
return $a;
}
);
PHP));
$this->assertNotNull($phpdoc);
$this->assertStringContainsString('Test docblock with pure intersection type', $phpdoc->getText());
$this->assertEquals('@param (Countable&Iterator) $a', $this->tagsToString($phpdoc, 'param'));
$this->assertEquals('@return (Countable&Iterator)', $this->tagsToString($phpdoc, 'return'));
}
public function testInitPhpDocParamsWithMultipleIntersections(): void
{
$phpdoc = (new MacroMock())->getPhpDoc(eval(<<<'PHP'
return new ReflectionFunction(
/**
* Test docblock with multiple intersection segments.
*/
function ((\Countable&\Iterator)|(\ArrayAccess&\Stringable) $a): (\Countable&\Iterator)|(\ArrayAccess&\Stringable)|null {
return $a;
}
);
PHP));
$this->assertNotNull($phpdoc);
$this->assertStringContainsString('Test docblock with multiple intersection segments', $phpdoc->getText());
$this->assertEquals('@param (Countable&Iterator)|(ArrayAccess&Stringable) $a', $this->tagsToString($phpdoc, 'param'));
$this->assertEquals('@return (Countable&Iterator)|(ArrayAccess&Stringable)|null', $this->tagsToString($phpdoc, 'return'));
}
protected function tagsToString(DocBlock $docBlock, string $name)
{
$tags = $docBlock->getTagsByName($name);
@@ -227,7 +284,7 @@ class MacroTest extends TestCase
{
$reflectionMethod = new \ReflectionMethod(UrlGeneratorMacroClass::class, '__invoke');
$macro = new Macro($reflectionMethod, UrlGenerator::class, new ReflectionClass(UrlGenerator::class), 'macroName');
$macro = new Macro($reflectionMethod, new ReflectionClass(UrlGenerator::class), 'macroName');
$this->assertInstanceOf(Macro::class, $macro);
}
@@ -239,7 +296,7 @@ class MacroTest extends TestCase
{
$reflectionMethod = new \ReflectionMethod(UrlGeneratorMacroClass::class, '__invoke');
$macro = new Macro($reflectionMethod, 'URL', new ReflectionClass(UrlGenerator::class), 'macroName');
$macro = new Macro($reflectionMethod, new ReflectionClass(UrlGenerator::class), 'macroName');
$output = <<<'DOC'
/**
* @param string $foo
@@ -274,7 +331,7 @@ class MacroMock extends Macro
public function getPhpDoc(ReflectionFunctionAbstract $method, ?ReflectionClass $class = null): DocBlock
{
return (new Macro($method, '', $class ?? $method->getClosureScopeClass()))->phpdoc;
return (new Macro($method, $class ?? $method->getClosureScopeClass()))->phpdoc;
}
}
+8 -11
View File
@@ -19,7 +19,7 @@ class MethodTest extends TestCase
$reflectionClass = new \ReflectionClass(ExampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('setName');
$method = new Method($reflectionMethod, 'Example', $reflectionClass);
$method = new Method($reflectionMethod, $reflectionClass);
$this->assertInstanceOf(Method::class, $method);
}
@@ -32,7 +32,7 @@ class MethodTest extends TestCase
$reflectionClass = new \ReflectionClass(ExampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('setName');
$method = new Method($reflectionMethod, 'Example', $reflectionClass);
$method = new Method($reflectionMethod, $reflectionClass);
$output = <<<'DOC'
/**
@@ -60,7 +60,7 @@ DOC;
$reflectionClass = new \ReflectionClass(EloquentBuilder::class);
$reflectionMethod = $reflectionClass->getMethod('upsert');
$method = new Method($reflectionMethod, 'Builder', $reflectionClass);
$method = new Method($reflectionMethod, $reflectionClass);
$output = <<<'DOC'
/**
@@ -92,7 +92,7 @@ DOC;
$reflectionClass = new \ReflectionClass(EloquentBuilder::class);
$reflectionMethod = $reflectionClass->getMethod('where');
$method = new Method($reflectionMethod, 'Builder', $reflectionClass, null, [], [], ['$this' => '\\' . EloquentBuilder::class . '<static>']);
$method = new Method($reflectionMethod, $reflectionClass, null, [], [], ['$this' => '\\' . EloquentBuilder::class . '<static>']);
$output = <<<'DOC'
/**
@@ -101,7 +101,6 @@ DOC;
* @param (\Closure(static): mixed)|string|array|\Illuminate\Contracts\Database\Query\Expression $column
* @param mixed $operator
* @param mixed $value
* @param string $boolean
* @return \Illuminate\Database\Eloquent\Builder<static>
* @static
*/
@@ -123,15 +122,13 @@ DOC;
$reflectionClass = new \ReflectionClass(QueryBuilder::class);
$reflectionMethod = $reflectionClass->getMethod('whereNull');
$method = new Method($reflectionMethod, 'Builder', $reflectionClass, null, [], [], ['$this' => '\\' . EloquentBuilder::class . '<static>']);
$method = new Method($reflectionMethod, $reflectionClass, null, [], [], ['$this' => '\\' . EloquentBuilder::class . '<static>']);
$output = <<<'DOC'
/**
* Add a "where null" clause to the query.
*
* @param string|array|\Illuminate\Contracts\Database\Query\Expression $columns
* @param string $boolean
* @param bool $not
* @return \Illuminate\Database\Eloquent\Builder<static>
* @static
*/
@@ -154,7 +151,7 @@ DOC;
$reflectionClass = new \ReflectionClass(ExampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('setSpecialChars');
$method = new Method($reflectionMethod, 'Example', $reflectionClass);
$method = new Method($reflectionMethod, $reflectionClass);
$this->assertSame('$chars', $method->getParams(true));
$this->assertSame(['$chars'], $method->getParams(false));
$this->assertSame('$chars = \'$\\\'\\\\\'', $method->getParamsWithDefault(true));
@@ -169,7 +166,7 @@ DOC;
$reflectionClass = new \ReflectionClass(ExampleClass::class);
$reflectionMethod = $reflectionClass->getMethod('getApplication');
$method = new Method($reflectionMethod, 'Example', $reflectionClass, null, [], [
$method = new Method($reflectionMethod, $reflectionClass, null, [], [
'Application' => '\\Illuminate\\Foundation\\Application',
]);
@@ -195,7 +192,7 @@ DOC;
$reflectionClass = new \ReflectionClass(EloquentBuilder::class);
$reflectionMethod = $reflectionClass->getMethod('firstOr');
$method = new Method($reflectionMethod, 'Builder', $reflectionClass, null, [], [], [], ['TModel']);
$method = new Method($reflectionMethod, $reflectionClass, null, [], [], [], ['TModel']);
$output = <<<'DOC'
/**