├── .github └── workflows │ ├── dependency-review.yml │ ├── fix-php-code-style-issues.yml │ └── phpunit.yml ├── .gitignore ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE.md ├── README.md ├── composer.json ├── composer.lock ├── config └── querywatcher.php ├── content ├── discord_notification_console.png ├── discord_notification_request.png ├── logo.png ├── slack_notification_console.png └── slack_notification_request.png ├── docker-compose.yml ├── phpunit.xml ├── routes ├── BroadcastAuthRoute.php └── QueryChannel.php ├── src ├── Broadcasting │ └── QueryEventBroadcast.php ├── Events │ └── QueryEvent.php ├── Listeners │ └── QueryListener.php ├── Models │ └── QueryModel.php ├── QueryWatcher.php ├── QueryWatcherServiceProvider.php ├── Services │ ├── BroadcastAuthService.php │ └── ChannelService.php ├── Strategies │ └── NotificationStrategy │ │ ├── Channels │ │ ├── Discord.php │ │ └── Slack.php │ │ ├── NotificationChannelInterface.php │ │ └── NotificationStrategy.php └── Transformers │ ├── AuthTransformer.php │ ├── QueryTransformer.php │ └── TriggerTransformer.php └── tests ├── Feature └── CaptureQueryTest.php ├── Integration ├── Services │ └── ChannelServiceTest.php └── Strategies │ └── NotificationStrategyTest.php ├── TestCase.php ├── Unit ├── Strategies │ ├── Channels │ │ ├── DiscordTest.php │ │ └── SlackTest.php │ └── NotificationStrategyTest.php └── Transformers │ ├── AuthTransformerTest.php │ ├── QueryTransformerTest.php │ └── TriggerTransformerTest.php └── Utility ├── Factories └── DemoOwnerFactory.php ├── Migrations ├── 2022_08_07_193744_create_demo_owner_table.php └── 2022_08_07_193744_create_test_table.php ├── Models ├── DemoOwner.php └── Test.php ├── TestBroadcast.php ├── TestBroadcasterServiceProvider.php ├── TestQueryWatcherServiceProvider.php └── Traits ├── BroadcastAssertions.php ├── NonPublishableHasFactory.php └── QueryAssertions.php /.github/workflows/dependency-review.yml: -------------------------------------------------------------------------------- 1 | # Dependency Review Action 2 | # 3 | # This Action will scan dependency manifest files that change as part of a Pull Request, surfacing known-vulnerable versions of the packages declared or updated in the PR. Once installed, if the workflow run is marked as required, PRs introducing known-vulnerable packages will be blocked from merging. 4 | # 5 | # Source repository: https://github.com/actions/dependency-review-action 6 | # Public documentation: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/about-dependency-review#dependency-review-enforcement 7 | name: 'Dependency Review' 8 | on: [pull_request] 9 | 10 | permissions: 11 | contents: read 12 | 13 | jobs: 14 | dependency-review: 15 | runs-on: ubuntu-latest 16 | steps: 17 | - name: 'Checkout Repository' 18 | uses: actions/checkout@v3 19 | - name: 'Dependency Review' 20 | uses: actions/dependency-review-action@v2 21 | -------------------------------------------------------------------------------- /.github/workflows/fix-php-code-style-issues.yml: -------------------------------------------------------------------------------- 1 | name: Linter 2 | 3 | on: [push] 4 | 5 | jobs: 6 | php-code-styling: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - name: Checkout code 11 | uses: actions/checkout@v3 12 | with: 13 | ref: ${{ github.head_ref }} 14 | 15 | - name: Fix PHP code style issues 16 | uses: aglipanci/laravel-pint-action@0.1.0 17 | 18 | - name: Commit changes 19 | uses: stefanzweifel/git-auto-commit-action@v4 20 | with: 21 | commit_message: Fix styling 22 | -------------------------------------------------------------------------------- /.github/workflows/phpunit.yml: -------------------------------------------------------------------------------- 1 | name: phpunit 2 | 3 | on: 4 | push: 5 | pull_request: 6 | 7 | jobs: 8 | run-tests: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | fail-fast: false 12 | matrix: 13 | php: [8.0, 8.1] 14 | laravel: [8.*, 9.*] 15 | include: 16 | - laravel: 9.* 17 | testbench: 7.* 18 | - laravel: 8.* 19 | testbench: 6.* 20 | 21 | name: PHP${{ matrix.php }} - Laravel ${{ matrix.laravel }} 22 | 23 | steps: 24 | - name: Update apt 25 | run: sudo apt-get update --fix-missing 26 | 27 | - name: Checkout code 28 | uses: actions/checkout@v2 29 | 30 | - name: Setup PHP 31 | uses: shivammathur/setup-php@v2 32 | with: 33 | php-version: ${{ matrix.php }} 34 | coverage: none 35 | 36 | - name: Setup Problem Matches 37 | run: | 38 | echo "::add-matcher::${{ runner.tool_cache }}/php.json" 39 | echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" 40 | - name: Install dependencies 41 | run: | 42 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 43 | composer update --prefer-dist --no-interaction --no-suggest 44 | - name: Execute tests 45 | run: vendor/bin/phpunit 46 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.phpunit.result.cache 2 | /vendor 3 | -------------------------------------------------------------------------------- /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-12 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-12-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](http://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](http://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](http://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM php:8-fpm 2 | 3 | RUN apt-get update \ 4 | && apt-get -y install libzip-dev zlib1g-dev git zip unzip libicu-dev g++ libbz2-dev libmemcached-dev \ 5 | && apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/* \ 6 | 7 | RUN docker-php-ext-configure zip && docker-php-ext-install pdo pdo_mysql zip bz2 intl 8 | 9 | # Get latest Composer 10 | COPY --from=composer:latest /usr/bin/composer /usr/bin/composer 11 | 12 | # Set working directory 13 | WORKDIR /var/www 14 | 15 | RUN chown -R www-data:www-data /var/www 16 | 17 | # Expose port 9000 and start php-fpm server 18 | EXPOSE 9000 19 | CMD ["php-fpm"] 20 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 YorCreative 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 |
2 |
3 | 4 |
5 | 6 | Logo 7 | 8 |
9 | 10 |

Laravel Query Watcher

11 | 12 |
13 | GitHub stars 14 | GitHub issues 15 | GitHub forks 16 | PHPUnit 17 |
18 | 19 |
20 | 21 | 22 | A Laravel package that provides configurable application query capturing & monitoring. 23 | 24 | ## Installation 25 | 26 | install the package via composer: 27 | 28 | ```bash 29 | composer require YorCreative/Laravel-Query-Watcher 30 | ``` 31 | 32 | Publish the packages assets. 33 | 34 | ```bash 35 | php artisan vendor:publish --provider="YorCreative\QueryWatcher\QueryWatcherServiceProvider" 36 | ``` 37 | 38 | ## Usage 39 | 40 | ### Configuration 41 | 42 | Adjust the configuration file to suite your application. 43 | 44 | ```php 45 | [ 46 | // Do you want to capture queries? 47 | 'enabled' => env('QUERY_WATCH_ENABLED', true), 48 | 49 | // Token used for Authenticating Private Broadcast Channel 50 | 'token' => env('QUERY_WATCH_TOKEN', 'change_me'), 51 | 'scope' => [ 52 | 'time_exceeds_ms' => [ 53 | // Do you want to capture everything or only slow queries? 54 | 'enabled' => env('QUERY_WATCH_SCOPE_TIME_ENABLED', true), 55 | 56 | // The number of milliseconds it took to execute the query. 57 | 'threshold' => env('QUERY_WATCH_SCOPE_TIME_THRESHOLD', 500), 58 | ], 59 | 'context' => [ 60 | 'auth_user' => [ 61 | // Do you want to know context of the authenticated user when query is captured? 62 | 'enabled' => env('QUERY_WATCH_SCOPE_CONTEXT_AUTH_ENABLED', true), 63 | 64 | // How long do you want the session_id/authenticated user cached for? 65 | // without this cache, your application will infinite loop because it will capture 66 | // the user query and loop. 67 | // See closed Issue #1 for context. 68 | 'ttl' => env('QUERY_WATCH_SCOPE_CONTEXT_AUTH_TTL', 300), 69 | ], 70 | 'trigger' => [ 71 | // Do you want to know what triggered the query? 72 | // i.e Console command or Request 73 | 'enabled' => env('QUERY_WATCH_SCOPE_TRIGGER_ENABLED', true), 74 | ], 75 | ], 76 | 'ignorable_tables' => [ 77 | // Do you want to capture queries on specific tables? 78 | // If you are utilizing the database queue driver, you need to 79 | // ignore the jobs table, or you'll potentially get infinite capture loops. 80 | 'jobs', 81 | 'failed_jobs' 82 | ], 83 | 'ignorable_statements' => [ 84 | // Do you want to ignore specific SQL statements? 85 | 'create' 86 | ] 87 | ], 88 | 'listener' => [ 89 | // Channel notifications are queued 90 | // Define what connection to use. 91 | 'connection' => 'sync', 92 | 93 | // Define what queue to use 94 | 'queue' => 'default', 95 | 96 | // Do you want to delay the notifications at all? 97 | 'delay' => null, 98 | ], 99 | 'channels' => [ // Where to send notifications? 100 | 'discord' => [ 101 | // Do you want discord webhook notifications? 102 | 'enabled' => env('QUERY_WATCH_CHANNEL_DISCORD_ENABLED', false), 103 | 104 | // Discord Web-hook URL 105 | 'hook' => env('DISCORD_HOOK', 'please_fill_me_in'), 106 | ], 107 | 'slack' => [ 108 | // Do you want Slack webhook notifications? 109 | 'enabled' => env('QUERY_WATCH_CHANNEL_SLACK_ENABLED', false), 110 | 111 | // Slack Web-hook URL 112 | 'hook' => env('SLACK_HOOK', 'please_fill_me_in'), 113 | ], 114 | ] 115 | ] 116 | ``` 117 | 118 | ### Broadcasting 119 | 120 | All captured queries will broadcast on a private channel as the primary monitoring method. The QueryEvent that is 121 | broadcasting is using your 122 | applications [broadcast configuration](https://laravel.com/docs/9.x/broadcasting#configuration). 123 | 124 | ```php 125 | /** 126 | * Get the channels the event should broadcast on. 127 | * 128 | * @return PrivateChannel 129 | */ 130 | public function broadcastOn(): PrivateChannel 131 | { 132 | return new PrivateChannel('query.event.'. config('querywatcher.token')); 133 | } 134 | 135 | /** 136 | * @return string 137 | */ 138 | public function broadcastAs(): string 139 | { 140 | return 'query.event'; 141 | } 142 | ``` 143 | 144 | ### Slack Notification Channel 145 | 146 | To utilize Slack Notifications, you will need to [create a webhook](https://api.slack.com/messaging/webhooks#create_a_webhook) for one of your Slack Channels. Once you have your 147 | webhook url, add the following variable to your .env file. 148 | 149 | ```dotenv 150 | SLACK_HOOK= 151 | ``` 152 | 153 | Once you have done this, you can enable Slack Notifications in the configuration file. 154 | 155 | ### Discord Notification Channel 156 | 157 | Get a webhook URL from discord in the channel you want to receive your notifications in by 158 | reading [Discords Introduction to Webhook Article](https://support.discord.com/hc/en-us/articles/228383668-Intro-to-Webhooks) 159 | . Once you have your webhook url, add the following variable to your `.env` file. 160 | 161 | ```dotenv 162 | DISCORD_HOOK= 163 | ``` 164 | 165 | Once you have done this, you can enable Discord Notifications in the configuration file. 166 | 167 | ### Wiki Documentation 168 | 169 | - [Notification Channels Wiki](https://github.com/YorCreative/Laravel-Query-Watcher/wiki/Notification-Channels) 170 | - [Screenshots](https://github.com/YorCreative/Laravel-Query-Watcher/wiki/Screenshots) 171 | 172 | ## Testing 173 | 174 | ```bash 175 | composer test 176 | ``` 177 | 178 | ## Credits 179 | 180 | - [Yorda](https://github.com/yordadev) 181 | - [All Contributors](../../contributors) 182 | 183 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "yorcreative/laravel-query-watcher", 3 | "description": "A Laravel package that provides configurable application query capturing & monitoring.", 4 | "type": "library", 5 | "license": "MIT", 6 | "keywords": [ 7 | "laravel", 8 | "framework", 9 | "queries", 10 | "sql monitoring", 11 | "capture queries", 12 | "query capture", 13 | "query monitoring", 14 | "query watcher", 15 | "slow query monitoring" 16 | ], 17 | "minimum-stability": "dev", 18 | "require": { 19 | "php": "^8.0", 20 | "illuminate/contracts": "^8.0|^9.0", 21 | "guzzlehttp/guzzle": "^7.4.5", 22 | "pusher/pusher-php-server": "^7.1@beta" 23 | }, 24 | "require-dev": { 25 | "ext-pdo_sqlite": "*", 26 | "laravel/pint": "^1.0", 27 | "orchestra/testbench": "^7.0", 28 | "phpunit/phpunit": "^9.5" 29 | }, 30 | "autoload": { 31 | "psr-4": { 32 | "YorCreative\\QueryWatcher\\": "src/" 33 | } 34 | }, 35 | "autoload-dev": { 36 | "psr-4": { 37 | "YorCreative\\QueryWatcher\\Tests\\": "tests" 38 | } 39 | }, 40 | "scripts": { 41 | "test": "vendor/bin/phpunit", 42 | "lint": "vendor/bin/pint" 43 | }, 44 | "extra": { 45 | "laravel": { 46 | "providers": [ 47 | "YorCreative\\QueryWatcher\\QueryWatcherServiceProvider" 48 | ] 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /config/querywatcher.php: -------------------------------------------------------------------------------- 1 | env('QUERY_WATCH_ENABLED', true), 5 | 'token' => env('QUERY_WATCH_TOKEN', 'change_me'), 6 | 'scope' => [ 7 | 'time_exceeds_ms' => [ 8 | 'enabled' => env('QUERY_WATCH_SCOPE_TIME_ENABLED', false), 9 | 'threshold' => env('QUERY_WATCH_SCOPE_TIME_THRESHOLD', 500), 10 | ], 11 | 'context' => [ 12 | 'auth_user' => [ 13 | 'enabled' => env('QUERY_WATCH_SCOPE_CONTEXT_AUTH_ENABLED', true), 14 | 'ttl' => env('QUERY_WATCH_SCOPE_CONTEXT_AUTH_TTL', 300), 15 | ], 16 | 'trigger' => [ 17 | 'enabled' => env('QUERY_WATCH_SCOPE_TRIGGER_ENABLED', true), 18 | ], 19 | ], 20 | 'ignorable_tables' => [ 21 | 'jobs', 22 | 'failed_jobs', 23 | ], 24 | 'ignorable_statements' => [ 25 | 'create', 26 | ], 27 | ], 28 | 'listener' => [ 29 | 'connection' => 'sync', 30 | 'queue' => 'default', 31 | 'delay' => null, 32 | ], 33 | 'channels' => [ 34 | 'discord' => [ 35 | 'enabled' => env('QUERY_WATCH_CHANNEL_DISCORD_ENABLED', false), 36 | 'hook' => env('DISCORD_HOOK', 'placeholder'), 37 | ], 38 | 'slack' => [ 39 | 'enabled' => env('QUERY_WATCH_CHANNEL_SLACK_ENABLED', false), 40 | 'hook' => env('SLACK_HOOK', 'placeholder'), 41 | ], 42 | ], 43 | ]; 44 | -------------------------------------------------------------------------------- /content/discord_notification_console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YorCreative/Laravel-Query-Watcher/389606fb2b6720813f2b79e37076b273f7517674/content/discord_notification_console.png -------------------------------------------------------------------------------- /content/discord_notification_request.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YorCreative/Laravel-Query-Watcher/389606fb2b6720813f2b79e37076b273f7517674/content/discord_notification_request.png -------------------------------------------------------------------------------- /content/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YorCreative/Laravel-Query-Watcher/389606fb2b6720813f2b79e37076b273f7517674/content/logo.png -------------------------------------------------------------------------------- /content/slack_notification_console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YorCreative/Laravel-Query-Watcher/389606fb2b6720813f2b79e37076b273f7517674/content/slack_notification_console.png -------------------------------------------------------------------------------- /content/slack_notification_request.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YorCreative/Laravel-Query-Watcher/389606fb2b6720813f2b79e37076b273f7517674/content/slack_notification_request.png -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | 3 | services: 4 | #PHP Service 5 | query-watcher: 6 | build: 7 | context: "" 8 | dockerfile: Dockerfile 9 | container_name: query-watcher 10 | tty: true 11 | environment: 12 | SERVICE_NAME: query-watcher 13 | SERVICE_TAGS: dev 14 | working_dir: /var/www 15 | volumes: 16 | - .:/var/www 17 | networks: 18 | - yorcreative 19 | 20 | networks: 21 | yorcreative: 22 | driver: bridge 23 | 24 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | ./tests/Unit 10 | 11 | 12 | ./tests/Integration 13 | 14 | 15 | ./tests/Feature 16 | 17 | 18 | 19 | 20 | ./src 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /routes/BroadcastAuthRoute.php: -------------------------------------------------------------------------------- 1 | BroadcastAuthService::pusher($request), 10 | default => response([], 401), 11 | }; 12 | })->name('broadcasting.pusher.auth'); 13 | -------------------------------------------------------------------------------- /routes/QueryChannel.php: -------------------------------------------------------------------------------- 1 | queryModel = (new QueryModel(QueryTransformer::transform($query))); 25 | } 26 | 27 | /** 28 | * Get the channels the event should broadcast on. 29 | * 30 | * @return PrivateChannel 31 | */ 32 | public function broadcastOn(): PrivateChannel 33 | { 34 | return new PrivateChannel('query.event.'.config('querywatcher.token')); 35 | } 36 | 37 | /** 38 | * @return string 39 | */ 40 | public function broadcastAs(): string 41 | { 42 | return 'query.event'; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/Listeners/QueryListener.php: -------------------------------------------------------------------------------- 1 | connection = config('querywatcher.listener.connection'); 28 | $this->queue = config('querywatcher.listener.queue'); 29 | } 30 | 31 | /** 32 | * @param QueryEvent $event 33 | */ 34 | public function handle(QueryEvent $event) 35 | { 36 | ChannelService::notify($event->queryModel); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/Models/QueryModel.php: -------------------------------------------------------------------------------- 1 | 'string', 20 | 'bindings' => 'array', 21 | 'time' => 'float', 22 | 'connection' => 'string', 23 | 'trigger' => 'array', 24 | 'auth' => 'array', 25 | ]; 26 | 27 | public function getBindings() 28 | { 29 | return $this->bindings; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/QueryWatcher.php: -------------------------------------------------------------------------------- 1 | time 22 | || ! $time_exceeds_ms_enabled 23 | && ! self::ignorable($query)) { 24 | // only capture queries if: 25 | // - time_exceeds_ms is not enabled 26 | // - time_exceeds_ms is enabled and query time exceeds the threshold. 27 | // - query isn't on table that is ignorable. 28 | // - query isn't a sql statement that is ignorable 29 | 30 | event(new QueryEvent($query)); 31 | } 32 | }); 33 | } 34 | 35 | public static function isQueryWatcherEnabled() 36 | { 37 | return Config::get('querywatcher.enabled') ?? false; 38 | } 39 | 40 | /** 41 | * @return bool 42 | */ 43 | public static function timeExceedsMsEnabled(): bool 44 | { 45 | return config('querywatcher.scope.time_exceeds_ms.enabled') ?? false; 46 | } 47 | 48 | /** 49 | * @return float|null 50 | */ 51 | public static function getTimeExceedsMs(): ?float 52 | { 53 | return config('querywatcher.scope.time_exceeds_ms.threshold') ?? 0; 54 | } 55 | 56 | /** 57 | * @param QueryExecuted $queryExecuted 58 | * @return bool 59 | */ 60 | public static function ignorable(QueryExecuted $queryExecuted): bool 61 | { 62 | // check if query is on table that is ignorable 63 | foreach (Config::get('querywatcher.scope.ignorable_tables') as $table) { 64 | if (preg_match('~(from "'.$table.'"|update "'.$table.'"|into "'.$table.'")~i', $queryExecuted->sql)) { 65 | return true; 66 | } 67 | } 68 | 69 | // check if query includes ignorable statement 70 | foreach (Config::get('querywatcher.scope.ignorable_statements') as $statement) { 71 | if (str_starts_with(strtolower($queryExecuted->sql), strtolower($statement))) { 72 | return true; 73 | } 74 | } 75 | 76 | return false; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/QueryWatcherServiceProvider.php: -------------------------------------------------------------------------------- 1 | [ 16 | QueryListener::class, 17 | ], 18 | ]; 19 | 20 | public function register() 21 | { 22 | $this->mergeConfigFrom(dirname(__DIR__, 1).'/config/querywatcher.php', 'querywatcher'); 23 | 24 | $this->loadRoutesFrom(dirname(__DIR__, 1).'/routes/BroadcastAuthRoute.php'); 25 | 26 | $this->publishes([ 27 | dirname(__DIR__, 1).'/config' => base_path('config'), 28 | ]); 29 | 30 | QueryWatcher::listen(); 31 | 32 | $this->registerEventListeners(); 33 | } 34 | 35 | public function registerEventListeners() 36 | { 37 | $listeners = $this->getEventListeners(); 38 | foreach ($listeners as $listenerKey => $listenerValues) { 39 | foreach ($listenerValues as $listenerValue) { 40 | Event::listen( 41 | $listenerKey, 42 | $listenerValue 43 | ); 44 | } 45 | } 46 | } 47 | 48 | public function getEventListeners(): array 49 | { 50 | return $this->listeners; 51 | } 52 | 53 | public function boot() 54 | { 55 | require dirname(__DIR__, 1).'/routes/QueryChannel.php'; 56 | 57 | $this->app->singleton(Pusher::class, function () { 58 | return new Pusher( 59 | Config::get('broadcasting.connections.pusher.key'), 60 | Config::get('broadcasting.connections.pusher.secret'), 61 | Config::get('broadcasting.connections.pusher.app_id') 62 | ); 63 | }); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Services/BroadcastAuthService.php: -------------------------------------------------------------------------------- 1 | authorizeChannel( 25 | $request->input('channel_name'), 26 | $request->input('socket_id') 27 | ); 28 | 29 | return response($auth, 200); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/Services/ChannelService.php: -------------------------------------------------------------------------------- 1 | each(function ($channel) use (&$notificationStrategy) { 21 | if ($channel->isEnabled()) { 22 | $notificationStrategy->setChannel($channel); 23 | } 24 | }); 25 | 26 | $notificationStrategy->notify($model); 27 | } 28 | 29 | /** 30 | * @return Collection 31 | */ 32 | protected static function getChannels(): Collection 33 | { 34 | return new Collection([ 35 | new Discord(), 36 | new Slack(), 37 | ]); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Strategies/NotificationStrategy/Channels/Discord.php: -------------------------------------------------------------------------------- 1 | 'Bindings', 'value' => json_encode($model->getBindings())], 30 | ['name' => 'Execution Time', 'value' => json_encode($model->time).' ms'], 31 | ['name' => 'Connection', 'value' => $model->connection], 32 | ]); 33 | 34 | if ($model->trigger['action'] == 'Console') { 35 | $fields = array_merge($fields, [ 36 | ['name' => 'Trigger', 'value' => $model->trigger['action']], 37 | ]); 38 | } else { 39 | $fields = array_merge($fields, [ 40 | ['name' => 'Trigger', 'value' => $model->trigger['action'], 'inline' => true], 41 | ['name' => 'Method', 'value' => $model->trigger['context']['method'], 'inline' => true], 42 | ['name' => 'URL', 'value' => (string) $model->trigger['context']['url'], 'inline' => true], 43 | ]); 44 | 45 | $fields = array_merge($fields, [ 46 | ['name' => 'Input', 'value' => json_encode($model->trigger['context']['input'])], 47 | ]); 48 | } 49 | 50 | Http::post(config('querywatcher.channels.discord.hook'), [ 51 | 'embeds' => [ 52 | [ 53 | 'title' => 'Captured SQL Query', 54 | 'description' => $model->sql, 55 | 'color' => '7506394', 56 | 'fields' => $fields, 57 | 'footer' => [ 58 | 'text' => 'YorCreative/Laravel-QueryWatcher', 59 | ], 60 | ], 61 | ], 62 | ]); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/Strategies/NotificationStrategy/Channels/Slack.php: -------------------------------------------------------------------------------- 1 | buildCoreBaseEnrichment($model); 28 | 29 | // Contextual Information 30 | if ($model->trigger['action'] == 'Console') { 31 | $payload['blocks'] = $this->buildConsoleEnrichment($payload['blocks']); 32 | } else { 33 | $payload['blocks'] = $this->buildRequestEnrichment($payload['blocks'], $model); 34 | } 35 | 36 | // Fire off hook 37 | Http::retry(3)->contentType('application/json')->post(config('querywatcher.channels.slack.hook'), $payload); 38 | } 39 | 40 | /** 41 | * @note Slack Block Builder Reference 42 | * https://app.slack.com/block-kit-builder 43 | * 44 | * If you would like to improve your Slack message, see the block kit builder. 45 | */ 46 | 47 | /** 48 | * @param QueryModel $model 49 | * @return \array[][] 50 | */ 51 | protected function buildCoreBaseEnrichment(QueryModel $model): array 52 | { 53 | return [ 54 | 'blocks' => [ 55 | [ 56 | 'type' => 'divider', 57 | ], 58 | [ 59 | 'type' => 'header', 60 | 'text' => [ 61 | 'type' => 'plain_text', 62 | 'text' => 'Captured Query', 63 | ], 64 | ], 65 | [ 66 | 'type' => 'section', 67 | 'text' => [ 68 | 'type' => 'plain_text', 69 | 'text' => $model->sql, 70 | ], 71 | ], 72 | [ 73 | 'type' => 'header', 74 | 'text' => [ 75 | 'type' => 'plain_text', 76 | 'text' => 'Query Bindings', 77 | ], 78 | ], 79 | [ 80 | 'type' => 'section', 81 | 'text' => [ 82 | 'type' => 'plain_text', 83 | 'text' => json_encode($model->getBindings()), 84 | ], 85 | ], 86 | [ 87 | 'type' => 'header', 88 | 'text' => [ 89 | 'type' => 'plain_text', 90 | 'text' => 'Execution Time', 91 | ], 92 | ], 93 | [ 94 | 'type' => 'section', 95 | 'text' => [ 96 | 'type' => 'plain_text', 97 | 'text' => json_encode($model->time).' ms', 98 | ], 99 | ], 100 | [ 101 | 'type' => 'header', 102 | 'text' => [ 103 | 'type' => 'plain_text', 104 | 'text' => 'Connection', 105 | ], 106 | ], 107 | [ 108 | 'type' => 'section', 109 | 'text' => [ 110 | 'type' => 'plain_text', 111 | 'text' => $model->connection, 112 | ], 113 | ], 114 | ], 115 | ]; 116 | } 117 | 118 | /** 119 | * @param array $payload 120 | * @return array 121 | */ 122 | protected function buildConsoleEnrichment(array $payload): array 123 | { 124 | return array_merge($payload, [ 125 | [ 126 | 'type' => 'header', 127 | 'text' => [ 128 | 'type' => 'plain_text', 129 | 'text' => 'Contextual Information', 130 | ], 131 | ], 132 | [ 133 | 'type' => 'context', 134 | 'elements' => [ 135 | [ 136 | 'type' => 'mrkdwn', 137 | 'text' => '*Trigger:* Console', 138 | ], 139 | ], 140 | ], 141 | ]); 142 | } 143 | 144 | /** 145 | * @param array $payload 146 | * @param QueryModel $model 147 | * @return array 148 | */ 149 | protected function buildRequestEnrichment(array $payload, QueryModel $model): array 150 | { 151 | return array_merge($payload, [ 152 | [ 153 | 'type' => 'header', 154 | 'text' => [ 155 | 'type' => 'plain_text', 156 | 'text' => 'Contextual Information', 157 | ], 158 | ], 159 | [ 160 | 'type' => 'context', 161 | 'elements' => [ 162 | [ 163 | 'type' => 'mrkdwn', 164 | 'text' => '*Trigger:* '.$model->trigger['action'], 165 | ], 166 | ], 167 | ], 168 | [ 169 | 'type' => 'context', 170 | 'elements' => [ 171 | [ 172 | 'type' => 'mrkdwn', 173 | 'text' => '*Method:* '.$model->trigger['context']['method'], 174 | ], 175 | ], 176 | ], 177 | [ 178 | 'type' => 'context', 179 | 'elements' => [ 180 | [ 181 | 'type' => 'mrkdwn', 182 | 'text' => '*URL:* '.$model->trigger['context']['url'], 183 | ], 184 | ], 185 | ], 186 | [ 187 | 'type' => 'context', 188 | 'elements' => [ 189 | 0 => [ 190 | 'type' => 'mrkdwn', 191 | 'text' => '*Request Input:*', 192 | ], 193 | ], 194 | ], 195 | [ 196 | 'type' => 'section', 197 | 'text' => [ 198 | 'type' => 'mrkdwn', 199 | 'text' => json_encode($model->trigger['context']['input']), 200 | ], 201 | ], 202 | ]); 203 | } 204 | } 205 | -------------------------------------------------------------------------------- /src/Strategies/NotificationStrategy/NotificationChannelInterface.php: -------------------------------------------------------------------------------- 1 | channels = new Collection(); 18 | } 19 | 20 | /** 21 | * @param NotificationChannelInterface $channel 22 | */ 23 | public function setChannel(NotificationChannelInterface $channel): void 24 | { 25 | $this->channels->add($channel); 26 | } 27 | 28 | public function notify(QueryModel $model): void 29 | { 30 | $this->getChannels()->each(function ($channel) use ($model) { 31 | $channel->notify($model); 32 | }); 33 | } 34 | 35 | /** 36 | * @return Collection 37 | */ 38 | public function getChannels(): Collection 39 | { 40 | return $this->channels; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/Transformers/AuthTransformer.php: -------------------------------------------------------------------------------- 1 | Auth::check(), 22 | 'id' => Auth::check() ? Auth::user()->getAuthIdentifier() : null, 23 | 'model' => Auth::check() ? Auth::user()->getMorphClass() : null, 24 | ]; 25 | }); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/Transformers/QueryTransformer.php: -------------------------------------------------------------------------------- 1 | $query->sql, 20 | 'bindings' => $query->bindings, 21 | 'time' => $query->time, 22 | 'connection' => $query->connectionName, 23 | ]; 24 | 25 | if (Config::get('querywatcher.scope.context.trigger.enabled')) { 26 | $context = array_merge($context, [ 27 | 'trigger' => TriggerTransformer::transform(), 28 | ]); 29 | } 30 | 31 | if (Config::get('querywatcher.scope.context.auth_user.enabled')) { 32 | $context = array_merge($context, [ 33 | 'auth' => AuthTransformer::transform(), 34 | ]); 35 | } 36 | 37 | return $context; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Transformers/TriggerTransformer.php: -------------------------------------------------------------------------------- 1 | runningInConsole() ? 'Console' : 'Request'; 10 | 11 | $context = app()->runningInConsole() ? [ 12 | 'url' => null, 13 | 'input' => null, 14 | ] : [ 15 | 'url' => request()->url(), 16 | 'method' => request()->getMethod(), 17 | 'input' => request()->all(), 18 | ]; 19 | 20 | return [ 21 | 'action' => $action, 22 | 'context' => $context, 23 | ]; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/Feature/CaptureQueryTest.php: -------------------------------------------------------------------------------- 1 | newQuery() 41 | ->create([ 42 | 'field' => 'testing', 43 | ]); 44 | 45 | (new Test()) 46 | ->newQuery() 47 | ->get(); 48 | 49 | (new Test()) 50 | ->newQuery() 51 | ->where('field', 'testing') 52 | ->update([ 53 | 'field' => 'okay', 54 | ]); 55 | 56 | Event::assertNotDispatched(QueryEvent::class); 57 | 58 | $this->assertQueryCountMatches(3); 59 | } 60 | 61 | /** 62 | * @test 63 | * @group Feature 64 | */ 65 | public function it_can_ignore_a_query_by_ignorable_statement_scope() 66 | { 67 | HTTP::fake(); 68 | 69 | Config::set('querywatcher.scope.ignorable_statements', [ 70 | 'delete', 71 | ]); 72 | 73 | (new Test()) 74 | ->newQuery() 75 | ->create([ 76 | 'field' => 'testing', 77 | ]); 78 | 79 | $tests = (new Test()) 80 | ->newQuery() 81 | ->get(); 82 | 83 | $tests->first()->delete(); 84 | 85 | $this->assertEventBroadcasted( 86 | 'query.event', 87 | null, 88 | 2 89 | ); 90 | 91 | $this->assertQueryCountMatches(3); 92 | } 93 | 94 | /** 95 | * @test 96 | * @group Feature 97 | */ 98 | public function it_can_capture_a_query_without_auth_user() 99 | { 100 | HTTP::fake(); 101 | 102 | (new Test()) 103 | ->newQuery() 104 | ->get(); 105 | 106 | $this->assertEventBroadcasted( 107 | 'query.event' 108 | ); 109 | 110 | $this->assertQueryCountMatches(1); 111 | } 112 | 113 | /** 114 | * @test 115 | * @group Feature 116 | */ 117 | public function it_can_capture_a_query_with_auth_user() 118 | { 119 | HTTP::fake(); 120 | 121 | $user = DemoOwner::factory()->create(); 122 | 123 | Auth::login($user); 124 | 125 | (new Test()) 126 | ->newQuery() 127 | ->get(); 128 | 129 | $this->assertEventBroadcasted( 130 | 'query.event' 131 | ); 132 | 133 | $this->assertQueryCountMatches(2); 134 | } 135 | 136 | /** 137 | * @test 138 | * @group Feature 139 | */ 140 | public function it_is_listening_for_query_event() 141 | { 142 | Event::fake(); 143 | 144 | Event::assertListening(QueryEvent::class, QueryListener::class); 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /tests/Integration/Services/ChannelServiceTest.php: -------------------------------------------------------------------------------- 1 | getMethod('getChannels'); 22 | $protectedMethod->setAccessible(true); 23 | 24 | $channels = $protectedMethod->invokeArgs(new ChannelService(), []); 25 | 26 | $this->assertCount(2, $channels); 27 | 28 | $channels->each(function ($channel) { 29 | $this->assertTrue(in_array($channel, [ 30 | new Discord(), 31 | new Slack(), 32 | ])); 33 | }); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /tests/Integration/Strategies/NotificationStrategyTest.php: -------------------------------------------------------------------------------- 1 | setChannel($aChannel); 30 | 31 | $notificationStrategy->notify(new QueryModel(QueryTransformer::transform($this->queryEvent))); 32 | 33 | Log::shouldReceive('notify'); 34 | } 35 | } 36 | 37 | class Channel implements NotificationChannelInterface 38 | { 39 | public function isEnabled(): bool 40 | { 41 | return true; 42 | } 43 | 44 | public function notify(QueryModel $model): void 45 | { 46 | Log::info('notify'); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /tests/TestCase.php: -------------------------------------------------------------------------------- 1 | each(function ($file) { 39 | $file = pathinfo($file); 40 | $migration = include $file['dirname'].'/'.$file['basename']; 41 | $migration->up(); 42 | }); 43 | 44 | $connection = DB::connection('testbench'); 45 | $this->sql = 'select * from "Tests"'; 46 | $this->time = 0.50; 47 | $this->bindings = []; 48 | $this->queryEvent = new QueryExecuted($this->sql, $this->bindings, $this->time, $connection); 49 | 50 | $this->queryModel = new QueryModel(QueryTransformer::transform($this->queryEvent)); 51 | } 52 | 53 | /** 54 | * @param Application $app 55 | * @return string[] 56 | */ 57 | protected function getPackageProviders($app): array 58 | { 59 | return [ 60 | TestQueryWatcherServiceProvider::class, 61 | TestBroadcasterServiceProvider::class, 62 | ]; 63 | } 64 | 65 | /** 66 | * Define environment setup. 67 | * 68 | * @param Application $app 69 | * @return void 70 | */ 71 | protected function defineEnvironment($app) 72 | { 73 | // Setup default database to use sqlite :memory: 74 | $app['config']->set('database.default', 'testbench'); 75 | $app['config']->set('database.connections.testbench', [ 76 | 'driver' => 'sqlite', 77 | 'database' => ':memory:', 78 | 'prefix' => '', 79 | ]); 80 | 81 | $app['config']->set('broadcasting.default', 'test'); 82 | $app['config']->set('broadcasting.connections.test', ['driver' => 'test']); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /tests/Unit/Strategies/Channels/DiscordTest.php: -------------------------------------------------------------------------------- 1 | discordChannel = new Discord(); 18 | } 19 | 20 | /** 21 | * @test 22 | * @group Unit 23 | * @group Channels 24 | * @group Strategies 25 | */ 26 | public function it_can_send_http_request_to_discord() 27 | { 28 | Http::fake(); 29 | 30 | $this->discordChannel->notify($this->queryModel); 31 | 32 | Http::assertSentCount(1); 33 | } 34 | 35 | /** 36 | * @test 37 | * @group Unit 38 | * @group Channels 39 | * @group Strategies 40 | */ 41 | public function it_can_determine_that_discord_channel_is_enabled() 42 | { 43 | app()['config']->set('querywatcher.channels.discord.enabled', true); 44 | $this->assertTrue($this->discordChannel->isEnabled()); 45 | } 46 | 47 | /** 48 | * @test 49 | * @group Unit 50 | * @group Channels 51 | * @group Strategies 52 | */ 53 | public function it_can_determine_that_discord_channel_is_not_enabled() 54 | { 55 | app()['config']->set('querywatcher.channels.discord.enabled', false); 56 | $this->assertFalse($this->discordChannel->isEnabled()); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /tests/Unit/Strategies/Channels/SlackTest.php: -------------------------------------------------------------------------------- 1 | slackChannel = new Slack(); 18 | } 19 | 20 | /** 21 | * @test 22 | * @group Unit 23 | * @group Channels 24 | * @group Strategies 25 | */ 26 | public function it_can_send_http_request_to_slack() 27 | { 28 | Http::fake(); 29 | 30 | $this->slackChannel->notify($this->queryModel); 31 | 32 | Http::assertSentCount(1); 33 | } 34 | 35 | /** 36 | * @test 37 | * @group Unit 38 | * @group Channels 39 | * @group Strategies 40 | */ 41 | public function it_can_determine_that_slack_channel_is_enabled() 42 | { 43 | app()['config']->set('querywatcher.channels.slack.enabled', true); 44 | $this->assertTrue($this->slackChannel->isEnabled()); 45 | } 46 | 47 | /** 48 | * @test 49 | * @group Unit 50 | * @group Channels 51 | * @group Strategies 52 | */ 53 | public function it_can_determine_that_slack_channel_is_not_enabled() 54 | { 55 | app()['config']->set('querywatcher.channels.slack.enabled', false); 56 | $this->assertFalse($this->slackChannel->isEnabled()); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /tests/Unit/Strategies/NotificationStrategyTest.php: -------------------------------------------------------------------------------- 1 | setChannel($aChannel); 24 | 25 | $this->assertCount(1, $notificationStrategy->getChannels()); 26 | } 27 | } 28 | 29 | class Channel implements NotificationChannelInterface 30 | { 31 | public function isEnabled(): bool 32 | { 33 | return true; 34 | } 35 | 36 | public function notify(QueryModel $model): void 37 | { 38 | Log::info('notify'); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /tests/Unit/Transformers/AuthTransformerTest.php: -------------------------------------------------------------------------------- 1 | create(); 31 | Auth::login($owner); 32 | 33 | $this->assertEquals( 34 | [ 35 | 'check' => true, 36 | 'id' => $owner->id, 37 | 'model' => $owner->getMorphClass(), 38 | ], 39 | AuthTransformer::transform() 40 | ); 41 | 42 | $this->assertQueryCountMatches(1); 43 | } 44 | 45 | /** 46 | * @test 47 | * @group Transformers 48 | * @group Unit 49 | */ 50 | public function it_can_transform_unauthenticated_user_into_array() 51 | { 52 | $this->assertEquals( 53 | [ 54 | 'check' => false, 55 | 'id' => null, 56 | 'model' => null, 57 | ], 58 | AuthTransformer::transform() 59 | ); 60 | 61 | $this->assertNoQueriesExecuted(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /tests/Unit/Transformers/QueryTransformerTest.php: -------------------------------------------------------------------------------- 1 | assertEquals( 40 | [ 41 | 'sql' => $sql, 42 | 'bindings' => $bindings, 43 | 'time' => $time, 44 | 'connection' => 'testbench', 45 | 'trigger' => [ 46 | 'action' => 'Console', 47 | 'context' => [ 48 | 'url' => null, 49 | 'input' => null, 50 | ], 51 | ], 52 | 'auth' => [ 53 | 'check' => false, 54 | 'id' => null, 55 | 'model' => null, 56 | ], 57 | ], 58 | QueryTransformer::transform($queryEvent) 59 | ); 60 | 61 | $this->assertNoQueriesExecuted(); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /tests/Unit/Transformers/TriggerTransformerTest.php: -------------------------------------------------------------------------------- 1 | assertEquals( 27 | [ 28 | 'action' => 'Console', 29 | 'context' => [ 30 | 'url' => null, 31 | 'input' => null, 32 | ], 33 | ], 34 | TriggerTransformer::transform() 35 | ); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /tests/Utility/Factories/DemoOwnerFactory.php: -------------------------------------------------------------------------------- 1 | 19 | */ 20 | public function definition() 21 | { 22 | return [ 23 | 'email' => $this->faker->email, 24 | 'name' => $this->faker->name, 25 | ]; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /tests/Utility/Migrations/2022_08_07_193744_create_demo_owner_table.php: -------------------------------------------------------------------------------- 1 | id(); 18 | $table->string('email')->unique(); 19 | $table->string('name'); 20 | $table->timestamps(); 21 | }); 22 | } 23 | 24 | /** 25 | * Reverse the migrations. 26 | * 27 | * @return void 28 | */ 29 | public function down() 30 | { 31 | Schema::dropIfExists('demo_owners'); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /tests/Utility/Migrations/2022_08_07_193744_create_test_table.php: -------------------------------------------------------------------------------- 1 | id(); 18 | $table->string('field')->default('hello world.'); 19 | $table->timestamps(); 20 | }); 21 | } 22 | 23 | /** 24 | * Reverse the migrations. 25 | * 26 | * @return void 27 | */ 28 | public function down() 29 | { 30 | Schema::dropIfExists('tests'); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /tests/Utility/Models/DemoOwner.php: -------------------------------------------------------------------------------- 1 | broadcasts)) { 18 | $this->broadcasts[$event] = collect([]); 19 | } 20 | 21 | $this->broadcasts[$event][] = [ 22 | 'channels' => $channels, 23 | 'event' => $event, 24 | 'payload' => $payload, 25 | ]; 26 | } 27 | 28 | public function getBroadcasts(): array 29 | { 30 | return $this->broadcasts; 31 | } 32 | 33 | /** 34 | * {@inheritdoc} 35 | */ 36 | public function auth($request) 37 | { 38 | } 39 | 40 | /** 41 | * {@inheritdoc} 42 | */ 43 | public function validAuthenticationResponse($request, $result) 44 | { 45 | } 46 | 47 | /** 48 | * Authenticate the incoming request for a given channel. 49 | * 50 | * @param Request $request 51 | * @return mixed 52 | */ 53 | 54 | /** 55 | * Return if the broadcaster contains event. 56 | * 57 | * @param string $event 58 | * @param null $channels 59 | * @param null $count 60 | * @param array|null $payload 61 | * @return bool 62 | */ 63 | public function contains(string $event, $channels = null, $count = null, array $payload = null): bool 64 | { 65 | if (is_int($channels)) { 66 | $count = $channels; 67 | $channels = null; 68 | } 69 | 70 | if (! array_key_exists($event, $this->broadcasts)) { 71 | return false; 72 | } 73 | 74 | $eventBroadcasts = $this->broadcasts[$event]; 75 | 76 | if ($count != null && count($eventBroadcasts) != $count) { 77 | return false; 78 | } 79 | 80 | if ($channels != null) { 81 | $last = $eventBroadcasts->last(); 82 | 83 | if (! $this->broadcastContainsAllChannels($last, $channels)) { 84 | return false; 85 | } 86 | } 87 | 88 | //@TODO: Allow to test for payload 89 | 90 | return true; 91 | } 92 | 93 | private function broadcastContainsAllChannels(array $broadcast, $channels): bool 94 | { 95 | if (! is_array($channels)) { 96 | return $this->broadcastContainsChannel($broadcast, $channels); 97 | } 98 | 99 | foreach ($channels as $channel) { 100 | if (! $this->broadcastContainsChannel($broadcast, $channel)) { 101 | return false; 102 | } 103 | } 104 | 105 | return true; 106 | } 107 | 108 | private function broadcastContainsChannel(array $broadcast, string $channel): bool 109 | { 110 | return in_array($channel, $broadcast['channels']); 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /tests/Utility/TestBroadcasterServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->singleton(TestBroadcast::class, function () { 19 | return new TestBroadcast(); 20 | }); 21 | } 22 | 23 | /** 24 | * Bootstrap services. 25 | * 26 | * @param BroadcastManager $broadcastManager 27 | */ 28 | public function boot(BroadcastManager $broadcastManager) 29 | { 30 | $broadcastManager->extend('test', function (Application $app, array $config) { 31 | return $app->make(TestBroadcast::class); 32 | }); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /tests/Utility/TestQueryWatcherServiceProvider.php: -------------------------------------------------------------------------------- 1 | loadMigrationsFrom(__DIR__.'/Migrations'); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /tests/Utility/Traits/BroadcastAssertions.php: -------------------------------------------------------------------------------- 1 | getBroadcasts(); 40 | $broadcastCount = count($broadcasts); 41 | $evtStr = Str::plural('event', $broadcastCount); 42 | $message .= "\n$broadcastCount $evtStr was broadcasted: ".json_encode($broadcasts); 43 | 44 | $this->assertTrue($broadcaster->contains($event, $channels, $count), $message); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tests/Utility/Traits/NonPublishableHasFactory.php: -------------------------------------------------------------------------------- 1 | assertQueryCountMatches(0); 19 | 20 | if ($closure) { 21 | DB::flushQueryLog(); 22 | } 23 | } 24 | 25 | public static function trackQueries(): void 26 | { 27 | DB::enableQueryLog(); 28 | } 29 | 30 | public function assertQueryCountMatches(int $count, Closure $closure = null): void 31 | { 32 | if ($closure) { 33 | self::trackQueries(); 34 | 35 | $closure(); 36 | } 37 | 38 | $this->assertEquals($count, self::getQueryCount()); 39 | 40 | if ($closure) { 41 | DB::flushQueryLog(); 42 | } 43 | } 44 | 45 | public static function getQueryCount(): int 46 | { 47 | return count(self::getQueriesExecuted()); 48 | } 49 | 50 | public static function getQueriesExecuted(): array 51 | { 52 | return DB::getQueryLog(); 53 | } 54 | 55 | public function assertQueryCountLessThan(int $count, Closure $closure = null): void 56 | { 57 | if ($closure) { 58 | self::trackQueries(); 59 | 60 | $closure(); 61 | } 62 | 63 | $this->assertLessThan($count, self::getQueryCount()); 64 | 65 | if ($closure) { 66 | DB::flushQueryLog(); 67 | } 68 | } 69 | 70 | public function assertQueryCountGreaterThan(int $count, Closure $closure = null): void 71 | { 72 | if ($closure) { 73 | self::trackQueries(); 74 | 75 | $closure(); 76 | } 77 | 78 | $this->assertGreaterThan($count, self::getQueryCount()); 79 | 80 | if ($closure) { 81 | DB::flushQueryLog(); 82 | } 83 | } 84 | } 85 | --------------------------------------------------------------------------------