├── .chglog
├── CHANGELOG.tpl.md
└── config.yml
├── .editorconfig
├── .github
├── CONTRIBUTING.md
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── SECURITY.md
├── dependabot.yml
├── stale.yml
└── workflows
│ ├── dependabot-auto-merge.yml
│ ├── issues-translator.yml
│ ├── label.yml
│ ├── lint-md.yml
│ ├── php-cs-fixer.yml
│ ├── psalm.yml
│ ├── rector.yml
│ ├── stale.yml
│ ├── tests.yml
│ └── update-changelog.yml
├── .lintmdrc
├── .php-cs-fixer.php
├── CHANGELOG.md
├── LICENSE
├── README.md
├── _ide_helper.php
├── composer-updater
├── composer.json
├── config
└── dump-sql.php
├── docs
├── dd.png
├── ddSql.png
├── dump-server.gif
├── dump-server.png
└── usage.png
├── monorepo-builder.php
├── psalm-baseline.xml
├── psalm.xml.dist
├── rector.php
└── src
├── CliDescriptor.php
├── Commands
└── DumpSqlServerCommand.php
├── ContextProviders
└── RequestContextProvider.php
├── Dumper.php
├── Handlers
├── ListenedSqlHandler.php
└── SetVarDumperHandler.php
├── Macros
└── QueryBuilderMacro.php
├── ServiceProvider.php
├── Traits
├── FetchesStackTrace.php
└── RegisterDatabaseBuilderMethodAble.php
└── helpers.php
/.chglog/CHANGELOG.tpl.md:
--------------------------------------------------------------------------------
1 |
2 | # Changelog
3 |
4 | All notable changes to this project will be documented in this file.
5 |
6 |
7 | {{ if .Versions -}}
8 |
9 | ## [Unreleased]
10 |
11 | {{ if .Unreleased.CommitGroups -}}
12 | {{ range .Unreleased.CommitGroups -}}
13 | ### {{ .Title }}
14 | {{ range .Commits -}}
15 | - {{ if .Scope }}**{{ .Scope }}:** {{ end }}{{ .Subject }}
16 | {{ end }}
17 | {{ end -}}
18 | {{ end -}}
19 | {{ end -}}
20 |
21 | {{ range .Versions }}
22 |
23 | ## {{ if .Tag.Previous }}[{{ .Tag.Name }}]{{ else }}{{ .Tag.Name }}{{ end }} - {{ datetime "2006-01-02" .Tag.Date }}
24 | {{ range .CommitGroups -}}
25 | ### {{ .Title }}
26 | {{ range .Commits -}}
27 | - {{ if .Scope }}**{{ .Scope }}:** {{ end }}{{ .Subject }}
28 | {{ end }}
29 | {{ end -}}
30 |
31 | {{- if .RevertCommits -}}
32 | ### Reverts
33 | {{ range .RevertCommits -}}
34 | - {{ .Revert.Header }}
35 | {{ end }}
36 | {{ end -}}
37 |
38 | {{- if .MergeCommits -}}
39 | ### Pull Requests
40 | {{ range .MergeCommits -}}
41 | - {{ .Header }}
42 | {{ end }}
43 | {{ end -}}
44 |
45 | {{- if .NoteGroups -}}
46 | {{ range .NoteGroups -}}
47 | ### {{ .Title }}
48 | {{ range .Notes }}
49 | {{ .Body }}
50 | {{ end }}
51 | {{ end -}}
52 | {{ end -}}
53 | {{ end -}}
54 |
55 | {{- if .Versions }}
56 | [Unreleased]: {{ .Info.RepositoryURL }}/compare/{{ $latest := index .Versions 0 }}{{ $latest.Tag.Name }}...HEAD
57 | {{ range .Versions -}}
58 | {{ if .Tag.Previous -}}
59 | [{{ .Tag.Name }}]: {{ $.Info.RepositoryURL }}/compare/{{ .Tag.Previous.Name }}...{{ .Tag.Name }}
60 | {{ end -}}
61 | {{ end -}}
62 | {{ end -}}
63 |
--------------------------------------------------------------------------------
/.chglog/config.yml:
--------------------------------------------------------------------------------
1 | style: github
2 | template: CHANGELOG.tpl.md
3 | info:
4 | title: CHANGELOG
5 | repository_url: https://github.com/guanguans/laravel-dump-sql
6 | options:
7 | commits:
8 | filters:
9 | Type:
10 | - feat
11 | - fix
12 | - perf
13 | - refactor
14 | - docs
15 | - test
16 | - ci
17 | - revert
18 | commit_groups:
19 | title_maps:
20 | ci: CI
21 | # feat: Features
22 | # fix: Bug Fixes
23 | # perf: Performance Improvements
24 | # refactor: Code Refactoring
25 | header:
26 | pattern: "^(\\w*)(?:\\(([\\w\\$\\.\\-\\*\\s]*)\\))?\\:\\s(.*)$"
27 | pattern_maps:
28 | - Type
29 | - Scope
30 | - Subject
31 | notes:
32 | keywords:
33 | - BREAKING CHANGE
34 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | end_of_line = lf
6 | indent_size = 4
7 | indent_style = space
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | trim_trailing_whitespace = false
13 |
14 | [*.{yml,yaml,xml,xml.dist}]
15 | indent_size = 2
16 |
--------------------------------------------------------------------------------
/.github/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Contributions are **welcome** and will be fully **credited**.
4 |
5 | Please read and understand the contribution guide before creating an issue or pull request.
6 |
7 | ## Etiquette
8 |
9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code
10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be
11 | extremely unfair for them to suffer abuse or anger for their hard work.
12 |
13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
14 | world that developers are civilized and selfless people.
15 |
16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.
18 |
19 | ## Viability
20 |
21 | When requesting or submitting new features, first consider whether it might be useful to others. Open
22 | source projects are used by many developers, who may have entirely different needs to your own. Think about
23 | whether or not your feature is likely to be used by other users of the project.
24 |
25 | ## Procedure
26 |
27 | Before filing an issue:
28 |
29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
30 | - Check to make sure your feature suggestion isn't already present within the project.
31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
32 | - Check the pull requests tab to ensure that the feature isn't already in progress.
33 |
34 | Before submitting a pull request:
35 |
36 | - Check the codebase to ensure that your feature doesn't already exist.
37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix.
38 |
39 | ## Requirements
40 |
41 | If the project maintainer has any additional requirements, you will find them listed here.
42 |
43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).
44 |
45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests.
46 |
47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
48 |
49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
50 |
51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
52 |
53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
54 |
55 | **Happy coding**!
56 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | patreon: guanguans
4 | custom: https://www.guanguans.cn/images/wechat.jpeg
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: bug
6 | assignees: guanguans
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Additional context**
27 | Add any other context about the problem here.
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: good idea
6 | assignees: guanguans
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
--------------------------------------------------------------------------------
/.github/SECURITY.md:
--------------------------------------------------------------------------------
1 | # Security Policy
2 |
3 | If you discover any security related issues, please email ityaozm@gmail.com instead of using the issue tracker.
4 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: github-actions
4 | directory: "/"
5 | schedule:
6 | interval: daily
7 | time: "21:00"
8 | open-pull-requests-limit: 10
9 |
10 | - package-ecosystem: composer
11 | directory: "/"
12 | schedule:
13 | interval: daily
14 | time: "21:00"
15 | open-pull-requests-limit: 10
--------------------------------------------------------------------------------
/.github/stale.yml:
--------------------------------------------------------------------------------
1 | # Number of days of inactivity before an issue becomes stale
2 | daysUntilStale: 60
3 | # Number of days of inactivity before a stale issue is closed
4 | daysUntilClose: 7
5 | # Issues with these labels will never be considered stale
6 | exemptLabels:
7 | - pinned
8 | - security
9 | # Label to use when marking an issue as stale
10 | staleLabel: wontfix
11 | # Comment to post when marking an issue as stale. Set to `false` to disable
12 | markComment: >
13 | This issue has been automatically marked as stale because it has not had
14 | recent activity. It will be closed if no further activity occurs. Thank you
15 | for your contributions.
16 | # Comment to post when closing a stale issue. Set to `false` to disable
17 | closeComment: false
--------------------------------------------------------------------------------
/.github/workflows/dependabot-auto-merge.yml:
--------------------------------------------------------------------------------
1 | name: dependabot-auto-merge
2 | on: pull_request_target
3 |
4 | permissions:
5 | pull-requests: write
6 | contents: write
7 |
8 | jobs:
9 | dependabot:
10 | runs-on: ubuntu-latest
11 | if: ${{ github.actor == 'dependabot[bot]' }}
12 | steps:
13 |
14 | - name: Dependabot metadata
15 | id: metadata
16 | uses: dependabot/fetch-metadata@v2.4.0
17 | with:
18 | github-token: "${{ secrets.GITHUB_TOKEN }}"
19 |
20 | - name: Auto-merge Dependabot PRs for semver-minor updates
21 | if: ${{steps.metadata.outputs.update-type == 'version-update:semver-minor'}}
22 | run: gh pr merge --auto --merge "$PR_URL"
23 | env:
24 | PR_URL: ${{github.event.pull_request.html_url}}
25 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
26 |
27 | - name: Auto-merge Dependabot PRs for semver-patch updates
28 | if: ${{steps.metadata.outputs.update-type == 'version-update:semver-patch'}}
29 | run: gh pr merge --auto --merge "$PR_URL"
30 | env:
31 | PR_URL: ${{github.event.pull_request.html_url}}
32 | GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}}
--------------------------------------------------------------------------------
/.github/workflows/issues-translator.yml:
--------------------------------------------------------------------------------
1 | name: issues-translator
2 |
3 | on:
4 | issue_comment:
5 | types: [ created ]
6 | issues:
7 | types: [ opened ]
8 |
9 | jobs:
10 | build:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: usthe/issues-translate-action@v2.7
14 | with:
15 | IS_MODIFY_TITLE: true
16 |
--------------------------------------------------------------------------------
/.github/workflows/label.yml:
--------------------------------------------------------------------------------
1 | # This workflow will triage pull requests and apply a label based on the
2 | # paths that are modified in the pull request.
3 | #
4 | # To use this workflow, you will need to set up a .github/labeler.yml
5 | # file with configuration. For more information, see:
6 | # https://github.com/actions/labeler
7 |
8 | name: labeler
9 | on: [ pull_request ]
10 |
11 | jobs:
12 | label:
13 |
14 | runs-on: ubuntu-latest
15 | permissions:
16 | contents: read
17 | pull-requests: write
18 |
19 | steps:
20 | - uses: actions/labeler@v5
21 | with:
22 | repo-token: "${{ secrets.GITHUB_TOKEN }}"
23 |
--------------------------------------------------------------------------------
/.github/workflows/lint-md.yml:
--------------------------------------------------------------------------------
1 | name: lint markdown
2 |
3 | on: [ push, pull_request ]
4 |
5 | jobs:
6 | lint-markdown:
7 | runs-on: ubuntu-latest
8 | steps:
9 | - name: Checkout
10 | uses: actions/checkout@v4
11 |
12 | - name: Set node version
13 | uses: actions/setup-node@v4
14 |
15 | - name: Install lint-md
16 | run: npm install -g @lint-md/cli
17 |
18 | - name: Lint markdown
19 | run: lint-md --config .lintmdrc ./*.md ./.github/ ./docs/
20 |
--------------------------------------------------------------------------------
/.github/workflows/php-cs-fixer.yml:
--------------------------------------------------------------------------------
1 | name: check & fix styling
2 |
3 | on: [ push ]
4 |
5 | jobs:
6 | php-cs-fixer:
7 | name: php-cs-fixer
8 | runs-on: ubuntu-latest
9 | steps:
10 | - uses: actions/checkout@v4
11 |
12 | - name: Setup PHP
13 | uses: shivammathur/setup-php@v2
14 | with:
15 | php-version: '7.4'
16 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick
17 | coverage: none
18 |
19 | - name: Cache composer dependencies
20 | uses: actions/cache@v4
21 | with:
22 | path: vendor
23 | key: composer-${{ hashFiles('composer.lock') }}
24 |
25 | - name: Run composer install
26 | run: composer install --no-interaction --prefer-dist --ansi -v
27 |
28 | - name: Run php-cs-fixer
29 | run: composer style-fix
30 |
31 | - name: Commit changes
32 | uses: stefanzweifel/git-auto-commit-action@v5
33 | with:
34 | commit_message: Fix styling
35 | file_pattern: '**.php'
36 |
37 |
--------------------------------------------------------------------------------
/.github/workflows/psalm.yml:
--------------------------------------------------------------------------------
1 | name: psalm
2 |
3 | on:
4 | push:
5 | paths:
6 | - '**.php'
7 | - '.github/**.yml'
8 | - '.github/**.yaml'
9 | - '*.xml'
10 | - '*.xml.dist'
11 |
12 | jobs:
13 | psalm:
14 | name: psalm
15 | runs-on: ubuntu-latest
16 | steps:
17 | - uses: actions/checkout@v4
18 |
19 | - name: Setup PHP
20 | uses: shivammathur/setup-php@v2
21 | with:
22 | php-version: '7.4'
23 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick
24 | coverage: none
25 |
26 | - name: Cache composer dependencies
27 | uses: actions/cache@v4
28 | with:
29 | path: vendor
30 | key: composer-${{ hashFiles('composer.lock') }}
31 |
32 | - name: Run composer install
33 | run: composer install --no-interaction --prefer-dist --ansi -v
34 |
35 | - name: Run psalm
36 | run: composer psalm
37 |
--------------------------------------------------------------------------------
/.github/workflows/rector.yml:
--------------------------------------------------------------------------------
1 | name: rector
2 |
3 | on:
4 | push:
5 | paths:
6 | - '**.php'
7 | - '.github/**.yml'
8 | - '.github/**.yaml'
9 | - '*.xml'
10 | - '*.xml.dist'
11 |
12 | jobs:
13 | rector:
14 | name: rector
15 | runs-on: ubuntu-latest
16 | steps:
17 | - uses: actions/checkout@v4
18 |
19 | - name: Setup PHP
20 | uses: shivammathur/setup-php@v2
21 | with:
22 | php-version: '7.4'
23 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick
24 | coverage: none
25 |
26 | - name: Cache composer dependencies
27 | uses: actions/cache@v4
28 | with:
29 | path: vendor
30 | key: composer-${{ hashFiles('composer.lock') }}
31 |
32 | - name: Run composer install
33 | run: composer install --no-interaction --prefer-dist --ansi -v
34 |
35 | - name: Run rector
36 | run: composer rector-dry-run
37 |
--------------------------------------------------------------------------------
/.github/workflows/stale.yml:
--------------------------------------------------------------------------------
1 | # This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time.
2 | #
3 | # You can adjust the behavior by modifying this file.
4 | # For more information, see:
5 | # https://github.com/actions/stale
6 | name: Mark stale issues and pull requests
7 |
8 | on:
9 | schedule:
10 | - cron: '30 08 * * *'
11 |
12 | jobs:
13 | stale:
14 |
15 | runs-on: ubuntu-latest
16 | permissions:
17 | issues: write
18 | pull-requests: write
19 |
20 | steps:
21 | - uses: actions/stale@v9
22 | with:
23 | repo-token: ${{ secrets.GITHUB_TOKEN }}
24 | stale-issue-message: 'Stale issue message'
25 | stale-pr-message: 'Stale pull request message'
26 | stale-issue-label: 'no-issue-activity'
27 | stale-pr-label: 'no-pr-activity'
28 |
--------------------------------------------------------------------------------
/.github/workflows/tests.yml:
--------------------------------------------------------------------------------
1 | name: tests
2 |
3 | on: [push, pull_request]
4 |
5 | jobs:
6 | test:
7 | runs-on: ${{ matrix.os }}
8 | strategy:
9 | fail-fast: true
10 | matrix:
11 | os: [ubuntu-latest]
12 | php: [7.3, 8.3]
13 | dependency-version: [prefer-stable]
14 |
15 | name: P${{ matrix.php }} - ${{ matrix.dependency-version }} - ${{ matrix.os }}
16 |
17 | steps:
18 | - name: Checkout code
19 | uses: actions/checkout@v4
20 |
21 | - name: Cache dependencies
22 | uses: actions/cache@v4
23 | with:
24 | path: ~/.composer/cache/files
25 | key: dependencies-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }}
26 |
27 | - name: Setup PHP
28 | uses: shivammathur/setup-php@v2
29 | with:
30 | php-version: ${{ matrix.php }}
31 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick
32 | coverage: xdebug
33 |
34 | - name: Install dependencies
35 | run: composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction --ansi -v
36 |
37 | - name: Execute tests
38 | run: composer test-c
39 |
40 | - name: Upload coverage to Codecov
41 | uses: codecov/codecov-action@v5
42 | with:
43 | files: ./build/clover.xml
44 | token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos
45 | fail_ci_if_error: true # optional (default = false)
46 | verbose: true # optional (default = false)
47 |
--------------------------------------------------------------------------------
/.github/workflows/update-changelog.yml:
--------------------------------------------------------------------------------
1 | name: "update changelog"
2 |
3 | on:
4 | release:
5 | types: [released]
6 |
7 | jobs:
8 | update:
9 | runs-on: ubuntu-latest
10 |
11 | steps:
12 | - name: Checkout code
13 | uses: actions/checkout@v4
14 | with:
15 | ref: master
16 |
17 | - name: Update Changelog
18 | uses: stefanzweifel/changelog-updater-action@v1
19 | with:
20 | latest-version: ${{ github.event.release.name }}
21 | release-notes: ${{ github.event.release.body }}
22 |
23 | - name: Commit updated CHANGELOG
24 | uses: stefanzweifel/git-auto-commit-action@v5
25 | with:
26 | branch: master
27 | commit_message: Update CHANGELOG
28 | file_pattern: CHANGELOG.md
29 |
--------------------------------------------------------------------------------
/.lintmdrc:
--------------------------------------------------------------------------------
1 | {
2 | "excludeFiles": [
3 | "src/",
4 | "tests/",
5 | "vendor/",
6 | "./CHANGELOG.md"
7 | ],
8 | "rules": {
9 | "space-around-alphabet": 2,
10 | "space-around-number": 2,
11 | "no-empty-code-lang": 2,
12 | "no-empty-url": 2,
13 | "no-empty-list": 2,
14 | "no-empty-code": 2,
15 | "no-empty-inline-code": 2,
16 | "no-empty-blockquote": 2,
17 | "no-special-characters": 2,
18 | "use-standard-ellipsis": 2,
19 | "no-fullwidth-number": 2,
20 | "no-space-in-link": 2,
21 | "no-multiple-space-blockquote": 2,
22 | "correct-title-trailing-punctuation": 2,
23 | "no-space-in-inline-code": 2,
24 | "no-long-code": [
25 | 1,
26 | {
27 | "length": 200,
28 | "exclude": [
29 | "dot"
30 | ]
31 | }
32 | ]
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/.php-cs-fixer.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | $header = <<
15 |
16 | This source file is subject to the MIT license that is bundled.
17 | EOF;
18 |
19 | $finder = PhpCsFixer\Finder::create()
20 | ->in([
21 | __DIR__.'/config',
22 | __DIR__.'/src',
23 | __DIR__.'/tests',
24 | ])
25 | ->exclude([
26 | '.github/',
27 | 'doc/',
28 | 'docs/',
29 | 'vendor/',
30 | ])
31 | ->append(glob(__DIR__.'/{*,.*}.php', GLOB_BRACE))
32 | ->append([
33 | __DIR__.'/composer-updater',
34 | ])
35 | ->name('*.php')
36 | ->notName('*.blade.php')
37 | ->notName('_ide_helper.php')
38 | ->ignoreDotFiles(true)
39 | ->ignoreVCS(true);
40 |
41 | return (new PhpCsFixer\Config())
42 | ->setRules([
43 | '@PHP70Migration' => true,
44 | // '@PHP70Migration:risky' => true,
45 | '@PHP71Migration' => true,
46 | // '@PHP71Migration:risky' => true,
47 | '@PHP73Migration' => true,
48 | // '@PHP74Migration' => true,
49 | // '@PHP74Migration:risky' => true,
50 | // '@PHP80Migration' => true,
51 | // '@PHP80Migration:risky' => true,
52 | // '@PHP81Migration' => true,
53 | // '@PHP82Migration' => true,
54 |
55 | // '@PHPUnit75Migration:risky' => true,
56 | // '@PHPUnit84Migration:risky' => true,
57 | // '@PHPUnit100Migration:risky' => true,
58 | '@Symfony' => true,
59 | 'header_comment' => [
60 | 'header' => $header,
61 | 'comment_type' => 'PHPDoc',
62 | ],
63 | 'array_syntax' => ['syntax' => 'short'],
64 | 'ordered_imports' => ['sort_algorithm' => 'alpha'],
65 | 'no_unused_imports' => true,
66 | 'not_operator_with_successor_space' => true,
67 | 'no_useless_else' => true,
68 | 'no_useless_return' => true,
69 | 'single_quote' => true,
70 | 'class_attributes_separation' => true,
71 | 'standardize_not_equals' => true,
72 | // 'trailing_comma_in_multiline' => true,
73 | // 'php_unit_construct' => true,
74 | // 'php_unit_strict' => true,
75 | // 'declare_strict_types' => true,
76 | ])
77 | ->setRiskyAllowed(false)
78 | ->setFinder($finder);
79 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 |
2 | # Changelog
3 |
4 | All notable changes to this project will be documented in this file.
5 |
6 |
7 |
8 | ## [Unreleased]
9 |
10 |
11 |
12 | ## [2.5.0] - 2024-03-14
13 |
14 |
15 | ## [2.4.0] - 2024-03-13
16 | ### Pull Requests
17 | - Merge pull request [#29](https://github.com/guanguans/laravel-dump-sql/issues/29) from guanguans/dependabot/github_actions/actions/cache-4
18 | - Merge pull request [#28](https://github.com/guanguans/laravel-dump-sql/issues/28) from guanguans/dependabot/github_actions/actions/stale-9
19 | - Merge pull request [#27](https://github.com/guanguans/laravel-dump-sql/issues/27) from guanguans/dependabot/github_actions/stefanzweifel/git-auto-commit-action-5
20 | - Merge pull request [#26](https://github.com/guanguans/laravel-dump-sql/issues/26) from guanguans/dependabot/github_actions/codecov/codecov-action-4
21 | - Merge pull request [#25](https://github.com/guanguans/laravel-dump-sql/issues/25) from guanguans/dependabot/github_actions/actions/checkout-4
22 | - Merge pull request [#24](https://github.com/guanguans/laravel-dump-sql/issues/24) from guanguans/dependabot/github_actions/dependabot/fetch-metadata-1.6.0
23 | - Merge pull request [#23](https://github.com/guanguans/laravel-dump-sql/issues/23) from guanguans/dependabot/github_actions/dependabot/fetch-metadata-1.5.1
24 | - Merge pull request [#22](https://github.com/guanguans/laravel-dump-sql/issues/22) from guanguans/dependabot/github_actions/dependabot/fetch-metadata-1.5.0
25 | - Merge pull request [#21](https://github.com/guanguans/laravel-dump-sql/issues/21) from guanguans/dependabot/github_actions/dependabot/fetch-metadata-1.4.0
26 |
27 |
28 |
29 | ## [v2.3.0] - 2023-03-25
30 | ### Pull Requests
31 | - Merge pull request [#20](https://github.com/guanguans/laravel-dump-sql/issues/20) from guanguans/dependabot/github_actions/actions/stale-8
32 | - Merge pull request [#18](https://github.com/guanguans/laravel-dump-sql/issues/18) from guanguans/dependabot/github_actions/dependabot/fetch-metadata-1.3.6
33 | - Merge pull request [#17](https://github.com/guanguans/laravel-dump-sql/issues/17) from guanguans/dependabot/github_actions/actions/stale-7
34 | - Merge pull request [#16](https://github.com/guanguans/laravel-dump-sql/issues/16) from guanguans/dependabot/github_actions/dependabot/fetch-metadata-1.3.5
35 | - Merge pull request [#15](https://github.com/guanguans/laravel-dump-sql/issues/15) from guanguans/dependabot/github_actions/dependabot/fetch-metadata-1.3.4
36 | - Merge pull request [#14](https://github.com/guanguans/laravel-dump-sql/issues/14) from guanguans/dependabot/github_actions/actions/stale-6
37 |
38 |
39 |
40 | ## [v2.2.1] - 2022-07-06
41 | ### Pull Requests
42 | - Merge pull request [#13](https://github.com/guanguans/laravel-dump-sql/issues/13) from guanguans/dependabot/composer/phpunit/phpunit-tw-9.5
43 | - Merge pull request [#12](https://github.com/guanguans/laravel-dump-sql/issues/12) from guanguans/dependabot/github_actions/dependabot/fetch-metadata-1.3.3
44 |
45 |
46 |
47 | ## [v2.2.0] - 2022-04-01
48 |
49 |
50 | ## [v2.1.0] - 2022-02-14
51 |
52 |
53 | ## [v2.0.9] - 2021-11-05
54 |
55 |
56 | ## [v2.0.8] - 2021-11-04
57 | ### Pull Requests
58 | - Merge pull request [#11](https://github.com/guanguans/laravel-dump-sql/issues/11) from guanguans/imgbot
59 |
60 |
61 |
62 | ## [v2.0.7] - 2021-11-04
63 |
64 |
65 | ## [v2.0.6] - 2021-11-04
66 |
67 |
68 | ## [v2.0.5] - 2021-11-04
69 |
70 |
71 | ## [v2.0.4] - 2021-11-04
72 |
73 |
74 | ## [v2.0.3] - 2021-11-03
75 | ### Pull Requests
76 | - Merge pull request [#10](https://github.com/guanguans/laravel-dump-sql/issues/10) from guanguans/imgbot
77 |
78 |
79 |
80 | ## [v2.0.2] - 2021-11-03
81 |
82 |
83 | ## [v2.0.1] - 2021-11-03
84 |
85 |
86 | ## [v2.0.0] - 2021-11-03
87 |
88 |
89 | ## [v1.2.2] - 2021-11-03
90 |
91 |
92 | ## [v1.2.1] - 2021-11-02
93 |
94 |
95 | ## [v1.2.0] - 2021-10-26
96 | ### Pull Requests
97 | - Merge pull request [#9](https://github.com/guanguans/laravel-dump-sql/issues/9) from guanguans/imgbot
98 |
99 |
100 |
101 | ## [v1.1.3] - 2021-10-17
102 |
103 |
104 | ## [v1.1.2] - 2021-10-16
105 |
106 |
107 | ## [v1.1.1] - 2021-09-30
108 |
109 |
110 | ## [v1.1.0] - 2021-09-29
111 |
112 |
113 | ## [v1.0.6] - 2021-09-29
114 |
115 |
116 | ## [v1.0.5] - 2021-09-28
117 |
118 |
119 | ## [v1.0.4] - 2021-06-11
120 |
121 |
122 | ## [v1.0.3] - 2020-11-12
123 |
124 |
125 | ## [v1.0.2] - 2020-10-19
126 |
127 |
128 | ## [v1.0.1] - 2020-07-17
129 |
130 |
131 | ## v1.0.0 - 2020-07-12
132 | ### Pull Requests
133 | - Merge pull request [#6](https://github.com/guanguans/laravel-dump-sql/issues/6) from guanguans/imgbot
134 | - Merge pull request [#5](https://github.com/guanguans/laravel-dump-sql/issues/5) from guanguans/imgbot
135 | - Merge pull request [#1](https://github.com/guanguans/laravel-dump-sql/issues/1) from guanguans/add-license-1
136 |
137 |
138 | [Unreleased]: https://github.com/guanguans/laravel-dump-sql/compare/2.5.0...HEAD
139 | [2.5.0]: https://github.com/guanguans/laravel-dump-sql/compare/2.4.0...2.5.0
140 | [2.4.0]: https://github.com/guanguans/laravel-dump-sql/compare/v2.3.0...2.4.0
141 | [v2.3.0]: https://github.com/guanguans/laravel-dump-sql/compare/v2.2.1...v2.3.0
142 | [v2.2.1]: https://github.com/guanguans/laravel-dump-sql/compare/v2.2.0...v2.2.1
143 | [v2.2.0]: https://github.com/guanguans/laravel-dump-sql/compare/v2.1.0...v2.2.0
144 | [v2.1.0]: https://github.com/guanguans/laravel-dump-sql/compare/v2.0.9...v2.1.0
145 | [v2.0.9]: https://github.com/guanguans/laravel-dump-sql/compare/v2.0.8...v2.0.9
146 | [v2.0.8]: https://github.com/guanguans/laravel-dump-sql/compare/v2.0.7...v2.0.8
147 | [v2.0.7]: https://github.com/guanguans/laravel-dump-sql/compare/v2.0.6...v2.0.7
148 | [v2.0.6]: https://github.com/guanguans/laravel-dump-sql/compare/v2.0.5...v2.0.6
149 | [v2.0.5]: https://github.com/guanguans/laravel-dump-sql/compare/v2.0.4...v2.0.5
150 | [v2.0.4]: https://github.com/guanguans/laravel-dump-sql/compare/v2.0.3...v2.0.4
151 | [v2.0.3]: https://github.com/guanguans/laravel-dump-sql/compare/v2.0.2...v2.0.3
152 | [v2.0.2]: https://github.com/guanguans/laravel-dump-sql/compare/v2.0.1...v2.0.2
153 | [v2.0.1]: https://github.com/guanguans/laravel-dump-sql/compare/v2.0.0...v2.0.1
154 | [v2.0.0]: https://github.com/guanguans/laravel-dump-sql/compare/v1.2.2...v2.0.0
155 | [v1.2.2]: https://github.com/guanguans/laravel-dump-sql/compare/v1.2.1...v1.2.2
156 | [v1.2.1]: https://github.com/guanguans/laravel-dump-sql/compare/v1.2.0...v1.2.1
157 | [v1.2.0]: https://github.com/guanguans/laravel-dump-sql/compare/v1.1.3...v1.2.0
158 | [v1.1.3]: https://github.com/guanguans/laravel-dump-sql/compare/v1.1.2...v1.1.3
159 | [v1.1.2]: https://github.com/guanguans/laravel-dump-sql/compare/v1.1.1...v1.1.2
160 | [v1.1.1]: https://github.com/guanguans/laravel-dump-sql/compare/v1.1.0...v1.1.1
161 | [v1.1.0]: https://github.com/guanguans/laravel-dump-sql/compare/v1.0.6...v1.1.0
162 | [v1.0.6]: https://github.com/guanguans/laravel-dump-sql/compare/v1.0.5...v1.0.6
163 | [v1.0.5]: https://github.com/guanguans/laravel-dump-sql/compare/v1.0.4...v1.0.5
164 | [v1.0.4]: https://github.com/guanguans/laravel-dump-sql/compare/v1.0.3...v1.0.4
165 | [v1.0.3]: https://github.com/guanguans/laravel-dump-sql/compare/v1.0.2...v1.0.3
166 | [v1.0.2]: https://github.com/guanguans/laravel-dump-sql/compare/v1.0.1...v1.0.2
167 | [v1.0.1]: https://github.com/guanguans/laravel-dump-sql/compare/v1.0.0...v1.0.1
168 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 琯琯
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # laravel-dump-sql
2 |
3 | 
4 |
5 | [](https://github.com/guanguans/laravel-dump-sql/actions)
6 | [](https://github.com/guanguans/laravel-dump-sql/actions)
7 | [](https://codecov.io/gh/guanguans/laravel-dump-sql)
8 | [](//packagist.org/packages/guanguans/laravel-dump-sql)
9 | [](//packagist.org/packages/guanguans/laravel-dump-sql)
10 | [](//packagist.org/packages/guanguans/laravel-dump-sql)
11 |
12 | > Assist laravel application to obtain complete sql statement. - 辅助 laravel 应用获取完整的 sql 语句。
13 |
14 | > The sql statement obtained by the query construction method in laravel is not bound to the conditional parameters, similar to `select * from users where id= ?`. This expansion pack can help you get a complete sql statement. - laravel 中查询构造方法得到的 sql 语句没有绑定条件参数,类似于`select * from users where id= ?`。这个扩展包可辅助你获取完整的 sql 语句。
15 |
16 | ## 功能
17 |
18 | * 添加获取 sql 语句的查询构建便捷方法(`toRawSql`、`dumpSql`、`ddSql`、`logListenedSql`、`dumpListenedSql`、`ddListenedSql`)
19 | * 添加监控 sql 语句的服务命令
20 |
21 | ## 环境要求
22 |
23 | * laravel || lumen >= 6.10
24 |
25 | ## 安装
26 |
27 | ```shell
28 | $ composer require guanguans/laravel-dump-sql -v
29 | ```
30 |
31 | ### lumen 中配置(laravel 中请忽略)
32 |
33 | 将下面代码添加到 `bootstrap/app.php` 文件中的 `Register Service Providers` 部分
34 |
35 | ```php
36 | $app->register(\Guanguans\LaravelDumpSql\ServiceProvider::class);
37 | ```
38 |
39 | ## 使用
40 |
41 | ### 监控 sql 语句的服务的使用
42 |
43 | ```shell
44 | $ php artisan server:dump-sql
45 | ```
46 |
47 | 
48 |
49 | ### 获取 sql 语句的查询构建便捷方法的使用
50 |
51 | 安装配置完毕后数据库查询构造方法会新增以下几个方法:
52 |
53 | * toRawSql() - 获取完整的 sql
54 | * dumpSql() - 打印完整的 sql
55 | * ddSql() - 打印完整的 sql 并且退出
56 | * logListenedSql() - 记录被监听到的 sql
57 | * dumpListenedSql() - 打印被监听到的 sql
58 | * ddListenedSql() - 打印被监听到的 sql 并且退出
59 |
60 | #### toRawSql() - 获取完整的 sql
61 |
62 | ```php
63 | $sql = User::query()->where('id', 1)->toRawSql();
64 | dd($sql);
65 | ```
66 |
67 | ```sql
68 | "select * from `xb_users` where `id` = 1"
69 | ```
70 |
71 | #### dumpSql() - 打印完整的 sql
72 |
73 | ```php
74 | User::query()->where('id', 1)->dumpSql();
75 | User::query()->where('id', 2)->dumpSql();
76 | ```
77 |
78 | ```sql
79 | "select * from `xb_users` where `id` = 1"
80 | "select * from `xb_users` where `id` = 2"
81 | ```
82 |
83 | #### ddSql() - 打印完整的 sql 并且退出
84 |
85 | ```php
86 | User::query()->where('id', 1)->ddSql();
87 | User::query()->where('id', 2)->ddSql();
88 | ```
89 |
90 | ```sql
91 | "select * from `xb_users` where `id` = 1"
92 | ```
93 |
94 | #### logListenedSql() - 记录被监听到的 sql
95 |
96 | ```php
97 | User::query()->where('id', 1)->logListenedSql()->first();
98 | User::query()->where('id', 2)->first();
99 | ```
100 |
101 | ```shell
102 | # 日志中
103 | [Laravel] [39.97ms] select * from `xb_users` where `id` = '1' limit 1 | GET: /
104 | [Laravel] [39.93ms] select * from `xb_users` where `id` = '2' limit 1 | GET: /
105 | ```
106 |
107 | #### dumpListenedSql() - 打印被监听到的 sql
108 |
109 | ```php
110 | User::query()->where('id', 1)->dumpListenedSql()->first();
111 | User::query()->where('id', 2)->first();
112 | ```
113 |
114 | ```shell
115 | [Laravel] [39.97ms] select * from `xb_users` where `id` = '1' limit 1 | GET: /
116 | [Laravel] [39.93ms] select * from `xb_users` where `id` = '2' limit 1 | GET: /
117 | ```
118 |
119 | #### ddListenedSql() - 打印被监听到的 sql 并且退出
120 |
121 | ```php
122 | User::query()->where('id', 1)->ddListenedSql()->first();
123 | User::query()->where('id', 2)->first();
124 | ```
125 |
126 | ```shell
127 | [Laravel] [39.97ms] select * from `xb_users` where `id` = '1' limit 1 | GET: /
128 | ```
129 |
130 | ## 安全漏洞
131 |
132 | 请查看[我们的安全政策](../../security/policy)了解如何报告安全漏洞。
133 |
134 | ## 贡献者
135 |
136 | * [guanguans](https://github.com/guanguans)
137 | * [所有贡献者](../../contributors)
138 |
139 | ## 协议
140 |
141 | MIT 许可证(MIT)。有关更多信息,请参见[协议文件](LICENSE)。
142 |
--------------------------------------------------------------------------------
/_ide_helper.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace {
12 | class DB extends Illuminate\Support\Facades\DB
13 | {
14 | }
15 | }
16 |
17 | namespace Illuminate\Database\Query {
18 | /**
19 | * @method string toRawSql()
20 | * @method void dumpSql()
21 | * @method void ddSql()
22 | * @method $this listenedSql(string $target)
23 | * @method $this logListenedSql()
24 | * @method $this dumpListenedSql()
25 | * @method $this ddListenedSql()
26 | *
27 | * @see \Guanguans\LaravelDumpSql\ServiceProvider
28 | * @see Builder
29 | */
30 | class Builder
31 | {
32 | }
33 | }
34 |
35 | namespace Illuminate\Database\Eloquent {
36 | /**
37 | * @method string toRawSql()
38 | * @method void dumpSql()
39 | * @method void ddSql()
40 | * @method $this listenedSql(string $target)
41 | * @method $this logListenedSql()
42 | * @method $this dumpListenedSql()
43 | * @method $this ddListenedSql()
44 | *
45 | * @mixin \Illuminate\Database\Query\Builder
46 | *
47 | * @see \Guanguans\LaravelDumpSql\ServiceProvider
48 | * @see Builder
49 | */
50 | class Builder
51 | {
52 | }
53 | }
54 |
55 | namespace Illuminate\Database\Eloquent\Relations {
56 | /**
57 | * @method string toRawSql()
58 | * @method void dumpSql()
59 | * @method void ddSql()
60 | * @method $this listenedSql(string $target)
61 | * @method $this logListenedSql()
62 | * @method $this dumpListenedSql()
63 | * @method $this ddListenedSql()
64 | *
65 | * @mixin \Illuminate\Database\Eloquent\Builder
66 | *
67 | * @see \Guanguans\LaravelDumpSql\ServiceProvider
68 | * @see Relation
69 | */
70 | class Relation
71 | {
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/composer-updater:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env php
2 |
10 | *
11 | * This source file is subject to the MIT license that is bundled.
12 | */
13 |
14 | use Composer\InstalledVersions;
15 | use SebastianBergmann\Diff\Differ;
16 | use Symfony\Component\Console\Input\ArgvInput;
17 | use Symfony\Component\Console\Input\InputInterface;
18 | use Symfony\Component\Console\Input\InputOption;
19 | use Symfony\Component\Console\Output\ConsoleOutput;
20 | use Symfony\Component\Console\Output\OutputInterface;
21 | use Symfony\Component\Console\SingleCommandApplication;
22 | use Symfony\Component\Console\Style\SymfonyStyle;
23 | use Symfony\Component\Process\ExecutableFinder;
24 | use Symfony\Component\Process\PhpExecutableFinder;
25 | use Symfony\Component\Process\Process;
26 |
27 | require __DIR__.'/vendor/autoload.php';
28 |
29 | /** @noinspection PhpUnhandledExceptionInspection */
30 | $status = (new SingleCommandApplication())
31 | ->setName('Composer Updater')
32 | ->addOption('composer-json-path', null, InputOption::VALUE_OPTIONAL)
33 | ->addOption('highest-php-binary', null, InputOption::VALUE_REQUIRED)
34 | ->addOption('composer-binary', null, InputOption::VALUE_OPTIONAL)
35 | ->addOption('except-packages', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL)
36 | ->addOption('except-dependency-versions', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_OPTIONAL)
37 | ->addOption('dry-run', null, InputOption::VALUE_NONE)
38 | ->setCode(function (InputInterface $input, OutputInterface $output): void {
39 | assert_options(ASSERT_BAIL, 1);
40 | assert($this instanceof SingleCommandApplication);
41 | assert((bool) $input->getOption('highest-php-binary'));
42 |
43 | (new class($input->getOption('composer-json-path') ?: __DIR__.'/composer.json', $input->getOption('highest-php-binary'), $input->getOption('composer-binary'), $input->getOption('except-packages'), $input->getOption('except-dependency-versions'), $input->getOption('dry-run'), new SymfonyStyle($input, $output), new Differ(), ) {
44 | private $composerJsonPath;
45 |
46 | private $composerJsonContents;
47 |
48 | private $highestComposerBinary;
49 |
50 | private $composerBinary;
51 |
52 | private $exceptPackages;
53 |
54 | private $exceptDependencyVersions;
55 |
56 | private $dryRun;
57 |
58 | private $symfonyStyle;
59 |
60 | private $differ;
61 |
62 | /**
63 | * @noinspection ParameterDefaultsNullInspection
64 | */
65 | public function __construct(
66 | string $composerJsonPath,
67 | ?string $highestPhpBinary = null,
68 | ?string $composerBinary = null,
69 | array $exceptPackages = [],
70 | array $exceptDependencyVersions = [],
71 | bool $dryRun = false,
72 | ?SymfonyStyle $symfonyStyle = null,
73 | ?Differ $differ = null
74 | ) {
75 | assert_options(ASSERT_BAIL, 1);
76 | assert((bool) $composerJsonPath);
77 |
78 | $this->composerJsonPath = $composerJsonPath;
79 | $this->composerJsonContents = file_get_contents($composerJsonPath);
80 | $this->highestComposerBinary = $this->getComposerBinary($composerBinary, $highestPhpBinary);
81 | $this->composerBinary = $this->getComposerBinary($composerBinary);
82 | $this->exceptPackages = array_merge([
83 | 'php',
84 | 'ext-*',
85 | ], $exceptPackages);
86 | $this->exceptDependencyVersions = array_merge([
87 | '\*',
88 | '*-*',
89 | '*@*',
90 | // '*|*',
91 | ], $exceptDependencyVersions);
92 | $this->dryRun = $dryRun;
93 | $this->symfonyStyle = $symfonyStyle ?? new SymfonyStyle(new ArgvInput(), new ConsoleOutput());
94 | $this->differ = $differ ?? new Differ();
95 | }
96 |
97 | public function __invoke(): void
98 | {
99 | $this
100 | ->updateComposerPackages()
101 | ->updateOutdatedComposerPackages()
102 | ->updateComposerPackages()
103 | ->updateOutdatedComposerPackages()
104 | ->updateComposerPackages()
105 | ->normalizeComposerJson()
106 | ->success();
107 | }
108 |
109 | private function updateComposerPackages(): self
110 | {
111 | $this->mustRunCommand("$this->composerBinary update -W --ansi");
112 |
113 | return $this;
114 | }
115 |
116 | /**
117 | * @noinspection JsonEncodingApiUsageInspection
118 | *
119 | * @return $this|never-return
120 | */
121 | private function updateOutdatedComposerPackages(): self
122 | {
123 | $outdatedComposerJsonContents = json_encode(
124 | $this->getOutdatedDecodedComposerJson(),
125 | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES
126 | ).PHP_EOL;
127 |
128 | if ($this->dryRun) {
129 | $this->symfonyStyle->writeln($this->formatDiff($this->differ->diff(
130 | $this->composerJsonContents,
131 | $outdatedComposerJsonContents
132 | )));
133 |
134 | exit(0);
135 | }
136 |
137 | file_put_contents($this->composerJsonPath, $outdatedComposerJsonContents);
138 |
139 | return $this;
140 | }
141 |
142 | private function normalizeComposerJson(): self
143 | {
144 | $this->mustRunCommand("$this->composerBinary normalize --diff --ansi");
145 |
146 | return $this;
147 | }
148 |
149 | private function success(): void
150 | {
151 | $this->symfonyStyle->success('Composer packages updated successfully!');
152 | }
153 |
154 | /**
155 | * @noinspection JsonEncodingApiUsageInspection
156 | */
157 | private function getOutdatedDecodedComposerJson(): array
158 | {
159 | $outdatedComposerPackages = $this->getOutdatedComposerPackages();
160 | $decodedComposerJson = json_decode(file_get_contents($this->composerJsonPath), true);
161 | (function () {
162 | return self::reload(null);
163 | })->call(new InstalledVersions());
164 |
165 | foreach ($decodedComposerJson as $name => &$value) {
166 | if (! in_array($name, ['require', 'require-dev'], true)) {
167 | continue;
168 | }
169 |
170 | foreach ($value as $package => &$dependencyVersion) {
171 | if (
172 | $this->strIs($this->exceptPackages, $package)
173 | || $this->strIs($this->exceptDependencyVersions, $dependencyVersion)
174 | ) {
175 | continue;
176 | }
177 |
178 | if ($version = InstalledVersions::getVersion($package)) {
179 | $dependencyVersion = $this->toDependencyVersion($version);
180 | }
181 |
182 | if (isset($outdatedComposerPackages[$package])) {
183 | $dependencyVersion = $outdatedComposerPackages[$package]['dependency_version'];
184 | }
185 | }
186 | }
187 |
188 | return $decodedComposerJson;
189 | }
190 |
191 | /**
192 | * @noinspection JsonEncodingApiUsageInspection
193 | */
194 | private function getOutdatedComposerPackages(): array
195 | {
196 | return array_reduce(
197 | json_decode(
198 | $this
199 | ->mustRunCommand("$this->highestComposerBinary outdated --format=json --direct --ansi")
200 | ->getOutput(),
201 | true
202 | )['installed'],
203 | function (array $carry, array $package): array {
204 | $lowestArrayVersion = $this->toArrayVersion($package['version']);
205 | $highestArrayVersion = $this->toArrayVersion($package['latest']);
206 | $dependencyVersions = [$this->toDependencyVersion($package['version'])];
207 |
208 | if ($lowestArrayVersion[0] !== $highestArrayVersion[0]) {
209 | $dependencyVersions = array_merge($dependencyVersions, array_map(
210 | static function (string $major): string {
211 | return "^$major.0";
212 | },
213 | range($lowestArrayVersion[0] + 1, $highestArrayVersion[0])
214 | ));
215 | }
216 |
217 | $package['dependency_version'] = implode(' || ', $dependencyVersions);
218 | $carry[$package['name']] = $package;
219 |
220 | return $carry;
221 | },
222 | []
223 | );
224 | }
225 |
226 | private function getComposerBinary(?string $composerBinary = null, ?string $phpBinary = null): string
227 | {
228 | return sprintf(
229 | '%s %s',
230 | $phpBinary ?? (new PhpExecutableFinder())->find(),
231 | $composerBinary ?? (new ExecutableFinder())->find('composer')
232 | );
233 | }
234 |
235 | /**
236 | * @param array|string $command
237 | * @param mixed $input The input as stream resource, scalar or \Traversable, or null for no input
238 | *
239 | * @noinspection MissingParameterTypeDeclarationInspection
240 | * @noinspection PhpSameParameterValueInspection
241 | */
242 | private function mustRunCommand(
243 | $command,
244 | ?string $cwd = null,
245 | ?array $env = null,
246 | $input = null,
247 | ?float $timeout = 300
248 | ): Process {
249 | $process = is_string($command)
250 | ? Process::fromShellCommandline($command, $cwd, $env, $input, $timeout)
251 | : new Process($command, $cwd, $env, $input, $timeout);
252 |
253 | $this->symfonyStyle->warning($process->getCommandLine());
254 |
255 | return $process
256 | ->setWorkingDirectory(dirname($this->composerJsonPath))
257 | ->setEnv(['COMPOSER_MEMORY_LIMIT' => -1])
258 | ->mustRun(function (string $type, string $buffer): void {
259 | $this->symfonyStyle->isVerbose() and $this->symfonyStyle->write($buffer);
260 | });
261 | }
262 |
263 | private function toDependencyVersion(string $version): string
264 | {
265 | return '^'.implode('.', array_slice($this->toArrayVersion($version), 0, 2));
266 | }
267 |
268 | private function toArrayVersion(string $version): array
269 | {
270 | return explode('.', ltrim($version, 'v'));
271 | }
272 |
273 | /**
274 | * @param array|string $pattern
275 | *
276 | * @noinspection SuspiciousLoopInspection
277 | * @noinspection ComparisonScalarOrderInspection
278 | * @noinspection MissingParameterTypeDeclarationInspection
279 | */
280 | private function strIs($pattern, string $value): bool
281 | {
282 | $patterns = (array) $pattern;
283 | if (empty($patterns)) {
284 | return false;
285 | }
286 |
287 | foreach ($patterns as $pattern) {
288 | $pattern = (string) $pattern;
289 | if ($pattern === $value) {
290 | return true;
291 | }
292 |
293 | $pattern = preg_quote($pattern, '#');
294 | $pattern = str_replace('\*', '.*', $pattern);
295 | if (1 === preg_match('#^'.$pattern.'\z#u', $value)) {
296 | return true;
297 | }
298 | }
299 |
300 | return false;
301 | }
302 |
303 | private function formatDiff(string $diff): string
304 | {
305 | $lines = explode(
306 | "\n",
307 | $diff,
308 | );
309 |
310 | $formatted = array_map(static function (string $line): string {
311 | return preg_replace(
312 | [
313 | '/^(\+.*)$/',
314 | '/^(-.*)$/',
315 | ],
316 | [
317 | '$1>',
318 | '$1>',
319 | ],
320 | $line,
321 | );
322 | }, $lines);
323 |
324 | return implode(
325 | "\n",
326 | $formatted,
327 | );
328 | }
329 | })();
330 | })
331 | ->run();
332 |
333 | exit($status);
334 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "guanguans/laravel-dump-sql",
3 | "description": "laravel 中轻松容易的输出完整的 SQL 语句。 - Easy output of complete SQL statements for laravel framework.",
4 | "license": "MIT",
5 | "type": "laravel",
6 | "keywords": [
7 | "sql",
8 | "mysql",
9 | "dump",
10 | "dd",
11 | "debug",
12 | "laravel"
13 | ],
14 | "authors": [
15 | {
16 | "name": "guanguans",
17 | "email": "ityaozm@gmail.com"
18 | }
19 | ],
20 | "support": {
21 | "issues": "https://github.com/guanguans/laravel-dump-sql/issues",
22 | "source": "https://github.com/guanguans/laravel-dump-sql"
23 | },
24 | "require": {
25 | "php": ">=7.3",
26 | "illuminate/console": "^7.0 || ^8.0 || ^9.0 || ^10.0 || ^11.0",
27 | "illuminate/database": "^7.0 || ^8.0 || ^9.0 || ^10.0 || ^11.0",
28 | "illuminate/http": "^7.0 || ^8.0 || ^9.0 || ^10.0 || ^11.0",
29 | "illuminate/log": "^7.0 || ^8.0 || ^9.0 || ^10.0 || ^11.0",
30 | "illuminate/support": "^7.0 || ^8.0 || ^9.0 || ^10.0 || ^11.0",
31 | "symfony/var-dumper": "^5.4 || ^6.0 || ^7.0"
32 | },
33 | "require-dev": {
34 | "brainmaestro/composer-git-hooks": "^3.0",
35 | "ergebnis/composer-normalize": "^2.20",
36 | "friendsofphp/php-cs-fixer": "^3.4",
37 | "guanguans/ai-commit": "dev-main",
38 | "guanguans/monorepo-builder-worker": "^1.4",
39 | "laravel/legacy-factories": "^1.4",
40 | "mockery/mockery": "^1.6",
41 | "orchestra/testbench": "^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.0",
42 | "phpunit/phpunit": "^9.6 || ^10.0 || ^11.0",
43 | "rector/rector": "^1.0",
44 | "vimeo/psalm": "^4.30 || ^5.0"
45 | },
46 | "minimum-stability": "stable",
47 | "prefer-stable": true,
48 | "autoload": {
49 | "psr-4": {
50 | "Guanguans\\LaravelDumpSql\\": "src"
51 | },
52 | "files": [
53 | "src/helpers.php"
54 | ]
55 | },
56 | "autoload-dev": {
57 | "psr-4": {
58 | "Guanguans\\LaravelDumpSqlTests\\": "tests"
59 | }
60 | },
61 | "config": {
62 | "allow-plugins": {
63 | "ergebnis/composer-normalize": true
64 | },
65 | "sort-packages": true
66 | },
67 | "extra": {
68 | "hooks": {
69 | "pre-commit": [
70 | "composer test",
71 | "composer style-lint"
72 | ],
73 | "pre-push": [
74 | "composer test",
75 | "composer style-lint"
76 | ]
77 | },
78 | "laravel": {
79 | "providers": [
80 | "Guanguans\\LaravelDumpSql\\ServiceProvider"
81 | ]
82 | }
83 | },
84 | "scripts": {
85 | "post-install-cmd": [
86 | "cghooks add --ignore-lock",
87 | "cghooks update"
88 | ],
89 | "post-update-cmd": [
90 | "cghooks update"
91 | ],
92 | "ai-commit": "@php ./vendor/bin/ai-commit commit --generator=bito_cli --ansi",
93 | "ai-commit-no-verify": "@ai-commit --no-verify",
94 | "benchmark": "@php ./vendor/bin/phpbench run --warmup=1 --retry-threshold=1 --iterations=3 --revs=5 --ansi -v",
95 | "cghooks": "@php ./vendor/bin/cghooks --ansi -v",
96 | "checks": [
97 | "@composer-normalize",
98 | "@composer-validate",
99 | "@md-lint",
100 | "@lint",
101 | "@style-lint",
102 | "@test",
103 | "@psalm",
104 | "@rector-dry-run"
105 | ],
106 | "composer-bin-all-update": "@composer bin all update --ansi -v",
107 | "composer-check-platform-reqs": "@composer check-platform-reqs --lock --ansi -v",
108 | "composer-normalize": "@composer normalize --dry-run --diff --ansi -v",
109 | "composer-parallel": "@composer parallel --ansi -v",
110 | "composer-parallel-checks": "@composer-parallel composer-validate md-lint lint style-lint test psalm",
111 | "composer-require-checker": "@php ./vendor/bin/composer-require-checker check --config-file=composer-require-checker.json composer.json --ansi -v",
112 | "composer-unused": "@php ./vendor/bin/composer-unused --ansi -v",
113 | "composer-unused-checker": "@php ./vendor/bin/composer-unused --ansi -v",
114 | "composer-updater": "@php ./composer-updater --highest-php-binary=/opt/homebrew/opt/php@8.3/bin/php --except-packages=laravel/lumen-framework --except-packages=orchestra/testbench --except-packages=pestphp/pest-plugin-laravel --ansi",
115 | "composer-updater-dry-run": "@composer-updater --dry-run",
116 | "composer-validate": "@composer validate --check-lock --strict --ansi -v",
117 | "facade-lint": "@facade-update --lint",
118 | "facade-update": "/opt/homebrew/opt/php@8.1/bin/php -f ./facade.php -- Guanguans\\\\LaravelExceptionNotify\\\\Facades\\\\ExceptionNotify",
119 | "lint": [
120 | "for DIR in .; do find $DIR -maxdepth 1 -type f -name '*.php' -type f ! -name 'xxx.php' -exec /opt/homebrew/opt/php@7.4/bin/php -l {} \\; 2>&1 | (! grep -v '^No syntax errors detected'); done",
121 | "for DIR in ./config ./src ./tests; do find $DIR -type f -name '*.php' -type f ! -name 'xxx.php' -exec /opt/homebrew/opt/php@7.4/bin/php -l {} \\; 2>&1 | (! grep -v '^No syntax errors detected'); done"
122 | ],
123 | "mark-finish": "printf '\\n!\\n!\\t\\033[0;32m%s\\033[0m\\n!\\n\\n' \"Finished\"",
124 | "mark-separate": "printf '\\n!\\n!\\t\\033[0;33m%s\\033[0m\\n!\\n\\n' \"----------------\"",
125 | "mark-start": "printf '\\n!\\n!\\t\\033[0;36m%s\\033[0m\\n!\\n\\n' \"Started\"",
126 | "md-fix": "@md-lint --fix",
127 | "md-lint": "lint-md --config .lintmdrc ./*.md ./.github/ ./docs/",
128 | "pest": "@php ./vendor/bin/pest --coverage",
129 | "pest-coverage": "@pest --coverage-html=./build/phpunit/ --coverage-clover=./clover.xml --coverage",
130 | "pest-migrate-configuration": "@pest --migrate-configuration",
131 | "phpstan": "@php ./vendor/bin/phpstan analyse --ansi -v",
132 | "phpstan-baseline": "@phpstan --generate-baseline --allow-empty-baseline",
133 | "post-merge": [
134 | "composer install --ansi -v"
135 | ],
136 | "psalm": "@php ./vendor/bin/psalm",
137 | "psalm-baseline": "@psalm --update-baseline",
138 | "rector": "@php ./vendor/bin/rector --ansi -v",
139 | "rector-dry-run": "@rector --dry-run",
140 | "release": "@php ./vendor/bin/monorepo-builder release --ansi -v",
141 | "release-major": "@release major",
142 | "release-major-dry-run": "@release-major --dry-run",
143 | "release-minor": "@release minor",
144 | "release-minor-dry-run": "@release-minor --dry-run",
145 | "release-patch": "@release patch",
146 | "release-patch-dry-run": "@release-patch --dry-run",
147 | "style-fix": "@php ./vendor/bin/php-cs-fixer fix --config=.php-cs-fixer.php --show-progress=dots --diff --ansi -v",
148 | "style-lint": "@style-fix --diff --dry-run",
149 | "test": "./vendor/bin/phpunit --coverage-text --colors=always --cache-result-file=./build/.phpunit.result.cache -v",
150 | "test-coverage": "./vendor/bin/phpunit --coverage-html=./build/coverage/ --coverage-clover=./build/clover.xml --color=always --cache-result-file=./build/.phpunit.result.cache -v"
151 | }
152 | }
153 |
--------------------------------------------------------------------------------
/config/dump-sql.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | return [
12 | /*
13 | * The host to use when listening for debug server connections.
14 | */
15 | 'host' => env('LISTEN_SQL_SERVER_HOST', 'tcp://127.0.0.1:9913'),
16 | ];
17 |
--------------------------------------------------------------------------------
/docs/dd.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guanguans/laravel-dump-sql/fba3f38c8c0562bb25ae88893a778a8ce0168328/docs/dd.png
--------------------------------------------------------------------------------
/docs/ddSql.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guanguans/laravel-dump-sql/fba3f38c8c0562bb25ae88893a778a8ce0168328/docs/ddSql.png
--------------------------------------------------------------------------------
/docs/dump-server.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guanguans/laravel-dump-sql/fba3f38c8c0562bb25ae88893a778a8ce0168328/docs/dump-server.gif
--------------------------------------------------------------------------------
/docs/dump-server.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guanguans/laravel-dump-sql/fba3f38c8c0562bb25ae88893a778a8ce0168328/docs/dump-server.png
--------------------------------------------------------------------------------
/docs/usage.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/guanguans/laravel-dump-sql/fba3f38c8c0562bb25ae88893a778a8ce0168328/docs/usage.png
--------------------------------------------------------------------------------
/monorepo-builder.php:
--------------------------------------------------------------------------------
1 |
9 | *
10 | * This source file is subject to the MIT license that is bundled.
11 | */
12 |
13 | use Guanguans\MonorepoBuilderWorker\CreateGithubReleaseReleaseWorker;
14 | use Guanguans\MonorepoBuilderWorker\Support\EnvironmentChecker;
15 | use Guanguans\MonorepoBuilderWorker\UpdateChangelogViaGoReleaseWorker;
16 | use Symplify\MonorepoBuilder\Config\MBConfig;
17 | use Symplify\MonorepoBuilder\Release\ReleaseWorker\AddTagToChangelogReleaseWorker;
18 | use Symplify\MonorepoBuilder\Release\ReleaseWorker\PushNextDevReleaseWorker;
19 | use Symplify\MonorepoBuilder\Release\ReleaseWorker\PushTagReleaseWorker;
20 | use Symplify\MonorepoBuilder\Release\ReleaseWorker\SetCurrentMutualDependenciesReleaseWorker;
21 | use Symplify\MonorepoBuilder\Release\ReleaseWorker\SetNextMutualDependenciesReleaseWorker;
22 | use Symplify\MonorepoBuilder\Release\ReleaseWorker\TagVersionReleaseWorker;
23 | use Symplify\MonorepoBuilder\Release\ReleaseWorker\UpdateBranchAliasReleaseWorker;
24 | use Symplify\MonorepoBuilder\Release\ReleaseWorker\UpdateReplaceReleaseWorker;
25 |
26 | return static function (MBConfig $mbConfig): void {
27 | require __DIR__.'/vendor/autoload.php';
28 | $mbConfig->defaultBranch('master');
29 |
30 | /*
31 | * release workers - in order to execute
32 | *
33 | * @see https://github.com/symplify/monorepo-builder#6-release-flow
34 | */
35 | $mbConfig->workers($workers = [
36 | // UpdateReplaceReleaseWorker::class,
37 | // SetCurrentMutualDependenciesReleaseWorker::class,
38 | // AddTagToChangelogReleaseWorker::class,
39 | TagVersionReleaseWorker::class,
40 | PushTagReleaseWorker::class,
41 | UpdateChangelogViaGoReleaseWorker::class,
42 | // UpdateChangelogViaNodeReleaseWorker::class,
43 | // UpdateChangelogViaPhpReleaseWorker::class,
44 | CreateGithubReleaseReleaseWorker::class,
45 | // SetNextMutualDependenciesReleaseWorker::class,
46 | // UpdateBranchAliasReleaseWorker::class,
47 | // PushNextDevReleaseWorker::class,
48 | ]);
49 |
50 | EnvironmentChecker::checks($workers);
51 | };
52 |
--------------------------------------------------------------------------------
/psalm-baseline.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/psalm.xml.dist:
--------------------------------------------------------------------------------
1 |
2 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
--------------------------------------------------------------------------------
/rector.php:
--------------------------------------------------------------------------------
1 |
9 | *
10 | * This source file is subject to the MIT license that is bundled.
11 | */
12 |
13 | use Rector\Caching\ValueObject\Storage\FileCacheStorage;
14 | use Rector\CodeQuality\Rector\Array_\CallableThisArrayToAnonymousFunctionRector;
15 | use Rector\CodeQuality\Rector\Class_\InlineConstructorDefaultToPropertyRector;
16 | use Rector\CodeQuality\Rector\Identical\SimplifyBoolIdenticalTrueRector;
17 | use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector;
18 | use Rector\CodeQuality\Rector\LogicalAnd\LogicalToBooleanRector;
19 | use Rector\CodingStyle\Rector\ArrowFunction\StaticArrowFunctionRector;
20 | use Rector\CodingStyle\Rector\Closure\StaticClosureRector;
21 | use Rector\CodingStyle\Rector\Encapsed\EncapsedStringsToSprintfRector;
22 | use Rector\CodingStyle\Rector\Encapsed\WrapEncapsedVariableInCurlyBracesRector;
23 | use Rector\Config\RectorConfig;
24 | use Rector\Configuration\Option;
25 | use Rector\DeadCode\Rector\Assign\RemoveUnusedVariableAssignRector;
26 | use Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector;
27 | use Rector\EarlyReturn\Rector\If_\ChangeAndIfToEarlyReturnRector;
28 | use Rector\EarlyReturn\Rector\Return_\ReturnBinaryOrToEarlyReturnRector;
29 | use Rector\EarlyReturn\Rector\StmtsAwareInterface\ReturnEarlyIfVariableRector;
30 | use Rector\Naming\Rector\Assign\RenameVariableToMatchMethodCallReturnTypeRector;
31 | use Rector\Naming\Rector\ClassMethod\RenameParamToMatchTypeRector;
32 | use Rector\Naming\Rector\Foreach_\RenameForeachValueVariableToMatchExprVariableRector;
33 | use Rector\Php71\Rector\FuncCall\RemoveExtraParametersRector;
34 | use Rector\PHPUnit\Set\PHPUnitSetList;
35 | use Rector\Renaming\Rector\FuncCall\RenameFunctionRector;
36 | use Rector\Set\ValueObject\DowngradeLevelSetList;
37 | use Rector\Set\ValueObject\LevelSetList;
38 | use Rector\Set\ValueObject\SetList;
39 | use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector;
40 | use Rector\ValueObject\PhpVersion;
41 |
42 | return static function (RectorConfig $rectorConfig): void {
43 | define('MHASH_XXH3', 2 << 0);
44 | define('MHASH_XXH32', 2 << 1);
45 | define('MHASH_XXH64', 2 << 2);
46 | define('MHASH_XXH128', 2 << 3);
47 | $rectorConfig->importNames(false, false);
48 | $rectorConfig->importShortClasses(false);
49 | // $rectorConfig->disableParallel();
50 | $rectorConfig->parallel(300);
51 | // $rectorConfig->phpstanConfig(__DIR__.'/phpstan.neon');
52 | $rectorConfig->phpVersion(PhpVersion::PHP_73);
53 | // $rectorConfig->cacheClass(FileCacheStorage::class);
54 | // $rectorConfig->cacheDirectory(__DIR__.'/build/rector');
55 | // $rectorConfig->containerCacheDirectory(__DIR__.'/build/rector');
56 | // $rectorConfig->disableParallel();
57 | // $rectorConfig->fileExtensions(['php']);
58 | // $rectorConfig->indent(' ', 4);
59 | // $rectorConfig->memoryLimit('2G');
60 | // $rectorConfig->nestedChainMethodCallLimit(3);
61 | // $rectorConfig->noDiffs();
62 | // $rectorConfig->parameters()->set(Option::APPLY_AUTO_IMPORT_NAMES_ON_CHANGED_FILES_ONLY, true);
63 | // $rectorConfig->removeUnusedImports();
64 |
65 | $rectorConfig->bootstrapFiles([
66 | // __DIR__.'/vendor/autoload.php',
67 | ]);
68 |
69 | $rectorConfig->autoloadPaths([
70 | // __DIR__.'/vendor/autoload.php',
71 | ]);
72 |
73 | $rectorConfig->paths([
74 | __DIR__.'/config',
75 | __DIR__.'/src',
76 | __DIR__.'/tests',
77 | __DIR__.'/.*.php',
78 | __DIR__.'/*.php',
79 | __DIR__.'/composer-updater',
80 | ]);
81 |
82 | $rectorConfig->skip([
83 | // rules
84 | // CallableThisArrayToAnonymousFunctionRector::class,
85 | // ChangeAndIfToEarlyReturnRector::class,
86 | // ExplicitBoolCompareRector::class,
87 | // RemoveEmptyClassMethodRector::class,
88 | // RemoveUnusedVariableAssignRector::class,
89 | // ReturnBinaryOrToEarlyReturnRector::class,
90 | // SimplifyBoolIdenticalTrueRector::class,
91 | // StaticClosureRector::class,
92 |
93 | EncapsedStringsToSprintfRector::class,
94 | LogicalToBooleanRector::class,
95 | WrapEncapsedVariableInCurlyBracesRector::class,
96 | RenameParamToMatchTypeRector::class,
97 | RenameVariableToMatchMethodCallReturnTypeRector::class,
98 |
99 | DisallowedEmptyRuleFixerRector::class => [
100 | // __DIR__.'/src/Support/QueryAnalyzer.php',
101 | ],
102 | RemoveExtraParametersRector::class,
103 | ExplicitBoolCompareRector::class => [
104 | // __DIR__.'/src/JavascriptRenderer.php',
105 | ],
106 | RenameForeachValueVariableToMatchExprVariableRector::class => [
107 | // __DIR__.'/src/OutputManager.php',
108 | ],
109 | StaticClosureRector::class => [
110 | __DIR__.'/tests',
111 | ],
112 | StaticArrowFunctionRector::class => [
113 | __DIR__.'/tests/ExceptionNotifyManagerTest.php',
114 | ],
115 | // ReturnEarlyIfVariableRector::class => [
116 | // __DIR__.'/src/Support/EscapeArg.php',
117 | // ],
118 |
119 | // paths
120 | __DIR__.'/tests/AspectMock',
121 | '**/Fixture*',
122 | '**/Fixture/*',
123 | '**/Fixtures*',
124 | '**/Fixtures/*',
125 | '**/Stub*',
126 | '**/Stub/*',
127 | '**/Stubs*',
128 | '**/Stubs/*',
129 | '**/Source*',
130 | '**/Source/*',
131 | '**/Expected/*',
132 | '**/Expected*',
133 | '**/__snapshots__/*',
134 | '**/__snapshots__*',
135 | ]);
136 |
137 | $rectorConfig->sets([
138 | DowngradeLevelSetList::DOWN_TO_PHP_73,
139 | LevelSetList::UP_TO_PHP_73,
140 | // SetList::CODE_QUALITY,
141 | // SetList::CODING_STYLE,
142 | // SetList::DEAD_CODE,
143 | // // SetList::STRICT_BOOLEANS,
144 | // // SetList::GMAGICK_TO_IMAGICK,
145 | // // SetList::MYSQL_TO_MYSQLI,
146 | // SetList::NAMING,
147 | // // SetList::PRIVATIZATION,
148 | // SetList::TYPE_DECLARATION,
149 | // SetList::EARLY_RETURN,
150 | // SetList::INSTANCEOF,
151 | //
152 | // PHPUnitSetList::PHPUNIT_90,
153 | // PHPUnitSetList::PHPUNIT_CODE_QUALITY,
154 | // PHPUnitSetList::ANNOTATIONS_TO_ATTRIBUTES,
155 | ]);
156 |
157 | // $rectorConfig->rules([
158 | // InlineConstructorDefaultToPropertyRector::class,
159 | // ]);
160 | //
161 | // $rectorConfig->ruleWithConfiguration(RenameFunctionRector::class, [
162 | // 'test' => 'it',
163 | // ]);
164 | };
165 |
--------------------------------------------------------------------------------
/src/CliDescriptor.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace Guanguans\LaravelDumpSql;
12 |
13 | use Guanguans\LaravelDumpSql\Handlers\SetVarDumperHandler;
14 | use Symfony\Component\Console\Formatter\OutputFormatterStyle;
15 | use Symfony\Component\Console\Input\ArrayInput;
16 | use Symfony\Component\Console\Output\OutputInterface;
17 | use Symfony\Component\Console\Style\SymfonyStyle;
18 | use Symfony\Component\VarDumper\Cloner\Data;
19 | use Symfony\Component\VarDumper\Command\Descriptor\DumpDescriptorInterface;
20 | use Symfony\Component\VarDumper\Dumper\CliDumper;
21 |
22 | class CliDescriptor implements DumpDescriptorInterface
23 | {
24 | private $dumper;
25 |
26 | private $lastIdentifier;
27 |
28 | private $supportsHref;
29 |
30 | public function __construct(CliDumper $dumper)
31 | {
32 | $this->dumper = $dumper;
33 | $this->supportsHref = method_exists(OutputFormatterStyle::class, 'setHref');
34 | }
35 |
36 | public function describe(OutputInterface $output, Data $data, array $context, int $clientId): void
37 | {
38 | if ($this->shouldntDescribe($data)) {
39 | return;
40 | }
41 |
42 | $io = $output instanceof SymfonyStyle ? $output : new SymfonyStyle(new ArrayInput([]), $output);
43 | $this->dumper->setColors($output->isDecorated());
44 |
45 | $lastIdentifier = $this->lastIdentifier;
46 | $this->lastIdentifier = $clientId;
47 |
48 | $section = "Received from client #$clientId";
49 | if (isset($context['request'])) {
50 | $request = $context['request'];
51 | $this->lastIdentifier = $request['identifier'];
52 | $section = sprintf('[%s] [%s] [%s]', date('Y-m-d H:i:s', (int) $context['timestamp']), $request['method'], $request['uri']);
53 | }
54 |
55 | if ($this->lastIdentifier !== $lastIdentifier) {
56 | $io->success($section);
57 | }
58 |
59 | $this->dumper->dump($data);
60 | $io->newLine();
61 | }
62 |
63 | protected function shouldntDescribe(Data $data): bool
64 | {
65 | return SetVarDumperHandler::CONNECTION_FLAG === $data->getValue();
66 | }
67 |
68 | protected function shouldDescribe(Data $data): bool
69 | {
70 | return ! $this->shouldntDescribe($data);
71 | }
72 | }
73 |
--------------------------------------------------------------------------------
/src/Commands/DumpSqlServerCommand.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace Guanguans\LaravelDumpSql\Commands;
12 |
13 | use Guanguans\LaravelDumpSql\CliDescriptor;
14 | use Illuminate\Console\Command;
15 | use Symfony\Component\Console\Style\SymfonyStyle;
16 | use Symfony\Component\VarDumper\Cloner\Data;
17 | use Symfony\Component\VarDumper\Dumper\CliDumper;
18 | use Symfony\Component\VarDumper\Server\DumpServer;
19 |
20 | /**
21 | * This file is modified from `beyondcode/laravel-dump-server`.
22 | */
23 | class DumpSqlServerCommand extends Command
24 | {
25 | /**
26 | * The console command name.
27 | *
28 | * @var string
29 | */
30 | protected $signature = 'server:dump-sql';
31 |
32 | /**
33 | * The console command description.
34 | *
35 | * @var string
36 | */
37 | protected $description = 'Start the dump sql server to collect sql information.';
38 |
39 | /**
40 | * The Dump server.
41 | *
42 | * @var DumpServer
43 | */
44 | protected $server;
45 |
46 | /**
47 | * DumpServerCommand constructor.
48 | *
49 | * @return void
50 | */
51 | public function __construct(DumpServer $server)
52 | {
53 | $this->server = $server;
54 |
55 | parent::__construct();
56 | }
57 |
58 | /**
59 | * Handle the command.
60 | *
61 | * @return void
62 | */
63 | public function handle()
64 | {
65 | $descriptor = new CliDescriptor(new CliDumper());
66 |
67 | $io = new SymfonyStyle($this->input, $this->output);
68 |
69 | $errorIo = $io->getErrorStyle();
70 | $errorIo->title('Laravel Dump Sql Server');
71 |
72 | $this->server->start();
73 |
74 | $errorIo->success(sprintf('Server listening on %s', $this->server->getHost()));
75 | $errorIo->comment('Quit the server with CONTROL-C.');
76 |
77 | $this->server->listen(function (Data $data, array $context, int $clientId) use ($descriptor, $io) {
78 | $descriptor->describe($io, $data, $context, $clientId);
79 | });
80 | }
81 | }
82 |
--------------------------------------------------------------------------------
/src/ContextProviders/RequestContextProvider.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace Guanguans\LaravelDumpSql\ContextProviders;
12 |
13 | use Illuminate\Http\Request;
14 | use Symfony\Component\VarDumper\Cloner\VarCloner;
15 | use Symfony\Component\VarDumper\Dumper\ContextProvider\ContextProviderInterface;
16 |
17 | /**
18 | * This file is modified from `beyondcode/laravel-dump-server`.
19 | */
20 | class RequestContextProvider implements ContextProviderInterface
21 | {
22 | /**
23 | * The current request.
24 | *
25 | * @var Request|null
26 | */
27 | private $currentRequest;
28 |
29 | /**
30 | * The variable cloner.
31 | *
32 | * @var VarCloner
33 | */
34 | private $cloner;
35 |
36 | /**
37 | * RequestContextProvider constructor.
38 | *
39 | * @return void
40 | */
41 | public function __construct(?Request $currentRequest = null)
42 | {
43 | $this->currentRequest = $currentRequest;
44 | $this->cloner = new VarCloner();
45 | $this->cloner->setMaxItems(0);
46 | }
47 |
48 | /**
49 | * Get the context.
50 | */
51 | public function getContext(): ?array
52 | {
53 | if (null === $this->currentRequest) {
54 | return null;
55 | }
56 |
57 | return [
58 | 'uri' => $this->currentRequest->getUri(),
59 | 'method' => $this->currentRequest->getMethod(),
60 | 'identifier' => spl_object_hash($this->currentRequest),
61 | ];
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/Dumper.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace Guanguans\LaravelDumpSql;
12 |
13 | use Symfony\Component\VarDumper\Cloner\VarCloner;
14 | use Symfony\Component\VarDumper\Dumper\CliDumper;
15 | use Symfony\Component\VarDumper\Server\Connection;
16 |
17 | /**
18 | * This file is modified from `beyondcode/laravel-dump-server`.
19 | */
20 | class Dumper
21 | {
22 | /**
23 | * The connection.
24 | *
25 | * @var Connection|null
26 | */
27 | private $connection;
28 |
29 | /**
30 | * Dumper constructor.
31 | *
32 | * @return void
33 | */
34 | public function __construct(?Connection $connection = null)
35 | {
36 | $this->connection = $connection;
37 | }
38 |
39 | /**
40 | * Dump a value with elegance.
41 | *
42 | * @return void
43 | */
44 | public function dump($value)
45 | {
46 | if (class_exists(CliDumper::class)) {
47 | $data = $this->createVarCloner()->cloneVar($value);
48 |
49 | if (null === $this->connection || false === $this->connection->write($data)) {
50 | $dumper = new CliDumper();
51 | $dumper->dump($data);
52 | }
53 | } else {
54 | var_dump($value);
55 | }
56 | }
57 |
58 | protected function createVarCloner(): VarCloner
59 | {
60 | return new VarCloner();
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/Handlers/ListenedSqlHandler.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace Guanguans\LaravelDumpSql\Handlers;
12 |
13 | use Guanguans\LaravelDumpSql\Traits\FetchesStackTrace;
14 | use Illuminate\Container\Container;
15 | use Illuminate\Database\Events\QueryExecuted;
16 | use Illuminate\Support\Facades\DB;
17 | use Illuminate\Support\Facades\Log;
18 |
19 | class ListenedSqlHandler
20 | {
21 | use FetchesStackTrace;
22 |
23 | /**
24 | * @var bool
25 | */
26 | protected $enabled = false;
27 |
28 | /**
29 | * @var Container
30 | */
31 | protected $app;
32 |
33 | public function __construct(Container $app)
34 | {
35 | $this->app = $app;
36 | }
37 |
38 | public function __invoke(string $target): void
39 | {
40 | if (! in_array($target, ['log', 'dump', 'dd'])) {
41 | throw new \InvalidArgumentException('Invalid target argument.');
42 | }
43 |
44 | DB::listen(function (QueryExecuted $queryExecutedEvent) use ($target) {
45 | if (! $this->enabled()) {
46 | return;
47 | }
48 |
49 | $stackTrace = $this->getCallerFromStackTrace();
50 |
51 | $formatSql = $this->formatSqlInfo([
52 | 'connection' => $queryExecutedEvent->connectionName,
53 | 'file' => $stackTrace['file'],
54 | 'line' => $stackTrace['line'],
55 | 'time' => $this->formatQueryExecutedTime($queryExecutedEvent->time),
56 | 'sql' => $this->getRealSql($queryExecutedEvent),
57 | ]);
58 |
59 | switch ($target) {
60 | case 'log':
61 | Log::channel($this->app['config']->get('logging.default'))->debug($formatSql);
62 | break;
63 | case 'dump':
64 | dump($formatSql);
65 | break;
66 | case 'dd':
67 | dd($formatSql);
68 | }
69 | });
70 | }
71 |
72 | public function enabled(): bool
73 | {
74 | return $this->enabled;
75 | }
76 |
77 | public function enable(): self
78 | {
79 | $this->enabled = true;
80 |
81 | return $this;
82 | }
83 |
84 | public function disable(): self
85 | {
86 | $this->enabled = false;
87 |
88 | return $this;
89 | }
90 |
91 | /**
92 | * @return string
93 | */
94 | protected function getRealSql(QueryExecuted $queryExecutedEvent)
95 | {
96 | $sqlWithPlaceholders = str_replace(['%', '?', '%s%s'], ['%%', '%s', '?'], $queryExecutedEvent->sql);
97 |
98 | $bindings = $queryExecutedEvent->connection->prepareBindings($queryExecutedEvent->bindings);
99 | if (0 === count($bindings)) {
100 | return $sqlWithPlaceholders;
101 | }
102 |
103 | $pdo = $queryExecutedEvent->connection->getPdo();
104 |
105 | return vsprintf($sqlWithPlaceholders, array_map([$pdo, 'quote'], $bindings));
106 | }
107 |
108 | /**
109 | * @return string
110 | */
111 | protected function formatQueryExecutedTime($milliseconds)
112 | {
113 | if ($milliseconds < 1) {
114 | return round($milliseconds * 1000).'μs';
115 | }
116 |
117 | if ($milliseconds < 1000) {
118 | return round($milliseconds, 2).'ms';
119 | }
120 |
121 | return round($milliseconds / 1000, 2).'s';
122 | }
123 |
124 | /**
125 | * @psalm-suppress InvalidArgument
126 | *
127 | * @return string
128 | */
129 | protected function formatSqlInfo(array $sqlInfo)
130 | {
131 | $formatSql = array_reduces($sqlInfo, function ($carry, $val, $name) {
132 | return $carry.sprintf('[%s: %s] ', $name, $val);
133 | }, '');
134 |
135 | return trim($formatSql);
136 | }
137 | }
138 |
--------------------------------------------------------------------------------
/src/Handlers/SetVarDumperHandler.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace Guanguans\LaravelDumpSql\Handlers;
12 |
13 | use Guanguans\LaravelDumpSql\ContextProviders\RequestContextProvider;
14 | use Guanguans\LaravelDumpSql\Dumper;
15 | use Illuminate\Container\Container;
16 | use Symfony\Component\VarDumper\Cloner\VarCloner;
17 | use Symfony\Component\VarDumper\Server\Connection;
18 | use Symfony\Component\VarDumper\Server\DumpServer;
19 | use Symfony\Component\VarDumper\VarDumper;
20 |
21 | class SetVarDumperHandler
22 | {
23 | public const CONNECTION_FLAG = 'laravel-dump-sql';
24 |
25 | /**
26 | * @var Container
27 | */
28 | protected $app;
29 |
30 | public function __construct(Container $app)
31 | {
32 | $this->app = $app;
33 | }
34 |
35 | public function __invoke()
36 | {
37 | $this->app->when(DumpServer::class)->needs('$host')->give($host = $this->app['config']->get('dump-sql.host'));
38 |
39 | $connection = new Connection($host, [
40 | 'request' => new RequestContextProvider($this->app['request']),
41 | ]);
42 |
43 | if (! $this->canWrited($connection)) {
44 | return;
45 | }
46 |
47 | VarDumper::setHandler(function ($var) use ($connection) {
48 | $this->app->make(Dumper::class, ['connection' => $connection])->dump($var);
49 | });
50 |
51 | enable_dump_listened_sql();
52 | }
53 |
54 | protected function canWrited(Connection $connection)
55 | {
56 | $data = (new VarCloner())->cloneVar(self::CONNECTION_FLAG);
57 |
58 | return $connection->write($data);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/Macros/QueryBuilderMacro.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace Guanguans\LaravelDumpSql\Macros;
12 |
13 | class QueryBuilderMacro
14 | {
15 | /**
16 | * @psalm-suppress UndefinedMethod
17 | */
18 | public function toRawSql()
19 | {
20 | return function () {
21 | /* @var \Illuminate\Database\Query\Builder $this */
22 | return array_reduce($this->getBindings(), function ($sql, $binding) {
23 | return preg_replace('/\?/', is_numeric($binding) ? $binding : "'".$binding."'", $sql, 1);
24 | }, $this->toSql());
25 | };
26 | }
27 |
28 | public function dumpSql()
29 | {
30 | return function () {
31 | /* @var \Illuminate\Database\Query\Builder $this */
32 | dump($this->toRawSql());
33 | };
34 | }
35 |
36 | public function ddSql()
37 | {
38 | return function () {
39 | /* @var \Illuminate\Database\Query\Builder $this */
40 | dd($this->toRawSql());
41 | };
42 | }
43 |
44 | public function listenedSql()
45 | {
46 | return function ($target) {
47 | /* @var \Illuminate\Database\Query\Builder $this */
48 | return tap($this, function () use ($target) {
49 | enable_listen_sql($target);
50 | });
51 | };
52 | }
53 |
54 | public function logListenedSql()
55 | {
56 | return function () {
57 | /* @var \Illuminate\Database\Query\Builder $this */
58 | return $this->listenedSql('log');
59 | };
60 | }
61 |
62 | public function dumpListenedSql()
63 | {
64 | return function () {
65 | /* @var \Illuminate\Database\Query\Builder $this */
66 | return $this->listenedSql('dump');
67 | };
68 | }
69 |
70 | public function ddListenedSql()
71 | {
72 | return function () {
73 | /* @var \Illuminate\Database\Query\Builder $this */
74 | return $this->listenedSql('dump');
75 | };
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/ServiceProvider.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace Guanguans\LaravelDumpSql;
12 |
13 | use Guanguans\LaravelDumpSql\Commands\DumpSqlServerCommand;
14 | use Guanguans\LaravelDumpSql\Handlers\ListenedSqlHandler;
15 | use Guanguans\LaravelDumpSql\Handlers\SetVarDumperHandler;
16 | use Guanguans\LaravelDumpSql\Macros\QueryBuilderMacro;
17 | use Guanguans\LaravelDumpSql\Traits\RegisterDatabaseBuilderMethodAble;
18 | use Illuminate\Database\ConnectionInterface;
19 | use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
20 | use Illuminate\Database\Eloquent\Relations\Relation as RelationBuilder;
21 | use Illuminate\Database\Query\Builder as QueryBuilder;
22 | use Illuminate\Foundation\Application as LaravelApplication;
23 | use Laravel\Lumen\Application as LumenApplication;
24 |
25 | class ServiceProvider extends \Illuminate\Support\ServiceProvider
26 | {
27 | use RegisterDatabaseBuilderMethodAble;
28 |
29 | /**
30 | * Register the application services.
31 | *
32 | * @return void
33 | */
34 | public function register()
35 | {
36 | $this->setupConfig();
37 |
38 | QueryBuilder::mixin($queryBuilderMacro = $this->app->make(QueryBuilderMacro::class));
39 | EloquentBuilder::mixin($queryBuilderMacro);
40 | RelationBuilder::mixin($queryBuilderMacro);
41 |
42 | $this->app->singleton(ListenedSqlHandler::class);
43 | $this->commands(DumpSqlServerCommand::class);
44 | call_user_func($this->app->make(SetVarDumperHandler::class));
45 | }
46 |
47 | /**
48 | * @psalm-suppress UndefinedClass
49 | * @psalm-suppress UndefinedInterfaceMethod
50 | * Setup the config.
51 | */
52 | protected function setupConfig()
53 | {
54 | $source = realpath($raw = __DIR__.'/../config/dump-sql.php') ?: $raw;
55 |
56 | if ($this->app instanceof LaravelApplication && $this->app->runningInConsole()) {
57 | $this->publishes([$source => config_path('dump-sql.php')], 'laravel-dump-sql');
58 | } elseif ($this->app instanceof LumenApplication) {
59 | $this->app->configure('dump-sql');
60 |
61 | $this->app->bindIf(ConnectionInterface::class, function ($app) {
62 | return $app['db']->connection();
63 | });
64 | }
65 |
66 | $this->mergeConfigFrom($source, 'dump-sql');
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/src/Traits/FetchesStackTrace.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace Guanguans\LaravelDumpSql\Traits;
12 |
13 | use Illuminate\Support\Str;
14 |
15 | /**
16 | * This file is modified from `laravel/telescope`.
17 | */
18 | trait FetchesStackTrace
19 | {
20 | /**
21 | * Find the first frame in the stack trace outside of Laravel.
22 | *
23 | * @param array-key|array $forgetLines
24 | *
25 | * @return array|null
26 | */
27 | protected function getCallerFromStackTrace($forgetLines = 0)
28 | {
29 | $trace = collect(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS))->forget($forgetLines);
30 |
31 | return $trace->first(function ($frame) {
32 | if (! isset($frame['file'])) {
33 | return false;
34 | }
35 |
36 | return ! Str::contains($frame['file'],
37 | base_path('vendor'.DIRECTORY_SEPARATOR.$this->ignoredVendorPath())
38 | );
39 | });
40 | }
41 |
42 | /**
43 | * Choose the frame outside of either Laravel or all packages.
44 | *
45 | * @return string|null
46 | */
47 | protected function ignoredVendorPath()
48 | {
49 | if (! ($this->options['ignore_packages'] ?? true)) {
50 | return 'laravel';
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/Traits/RegisterDatabaseBuilderMethodAble.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | namespace Guanguans\LaravelDumpSql\Traits;
12 |
13 | use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
14 | use Illuminate\Database\Eloquent\Relations\Relation;
15 | use Illuminate\Database\Query\Builder as QueryBuilder;
16 |
17 | /**
18 | * @mixin \Illuminate\Database\Eloquent\Builder
19 | * @mixin \Illuminate\Database\Query\Builder
20 | * @mixin \Illuminate\Database\Eloquent\Relations\Relation
21 | */
22 | trait RegisterDatabaseBuilderMethodAble
23 | {
24 | /**
25 | * @throws \InvalidArgumentException|\ReflectionException
26 | */
27 | public function registerDatabaseBuilderMethod(string $methodName, \Closure $closure)
28 | {
29 | if (
30 | method_exists(QueryBuilder::class, $methodName)
31 | || method_exists(EloquentBuilder::class, $methodName)
32 | || method_exists(Relation::class, $methodName)
33 | ) {
34 | throw new \InvalidArgumentException(sprintf('`%s` or `%s` or `%s` already exists method.:%s', QueryBuilder::class, EloquentBuilder::class, Relation::class, $methodName));
35 | }
36 |
37 | QueryBuilder::macro($methodName, $closure);
38 | EloquentBuilder::macro($methodName, $closure);
39 | Relation::macro($methodName, $closure);
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/src/helpers.php:
--------------------------------------------------------------------------------
1 |
7 | *
8 | * This source file is subject to the MIT license that is bundled.
9 | */
10 |
11 | use Guanguans\LaravelDumpSql\Handlers\ListenedSqlHandler;
12 |
13 | if (! function_exists('array_reduces')) {
14 | /**
15 | * @param null $carry
16 | *
17 | * @return mixed|null
18 | */
19 | function array_reduces(array $array, callable $callback, $carry = null)
20 | {
21 | foreach ($array as $key => $value) {
22 | $carry = call_user_func($callback, $carry, $value, $key);
23 | }
24 |
25 | return $carry;
26 | }
27 | }
28 |
29 | if (! function_exists('enable_listen_sql')) {
30 | function enable_listen_sql($target)
31 | {
32 | return call_user_func(
33 | tap(app(ListenedSqlHandler::class), function (ListenedSqlHandler $listenedSqlHandler) {
34 | $listenedSqlHandler->enable();
35 | }),
36 | $target
37 | );
38 | }
39 | }
40 |
41 | if (! function_exists('enable_log_listened_sql')) {
42 | function enable_log_listened_sql()
43 | {
44 | return enable_listen_sql('log');
45 | }
46 | }
47 |
48 | if (! function_exists('enable_dump_listened_sql')) {
49 | function enable_dump_listened_sql()
50 | {
51 | return enable_listen_sql('dump');
52 | }
53 | }
54 |
55 | if (! function_exists('enable_dd_listened_sql')) {
56 | function enable_dd_listened_sql()
57 | {
58 | return enable_listen_sql('dd');
59 | }
60 | }
61 |
62 | if (! function_exists('disable_listened_sql')) {
63 | function disable_listened_sql()
64 | {
65 | app(ListenedSqlHandler::class)->disable();
66 | }
67 | }
68 |
--------------------------------------------------------------------------------