feat: add runningInConsole() method to Application
#341
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Implements Laravel-compatible
app()->runningInConsole()detection for Hypervel, using coroutine-local Context to correctly distinguish between CLI commands and HTTP/queue contextsProblem
In traditional Laravel,
app()->runningInConsole()checksPHP_SAPI === 'cli'. This doesn't work in Swoole/Hypervel because both HTTP servers and console commands run via CLI.Common use cases that need this detection:
Solution
Uses
Hyperf\Context\Contextto store a coroutine-local flag that tracks whether code is executing within a console command context.How it works
Kernel::handle()(the CLI entry point, e.g.,php artisan foo) callsmarkAsRunningInConsole()before executing any commandKernel::call()(programmatic command execution) does NOT set the flag - it inherits whatever context already existsCommand::execute()propagates the flag across coroutine boundaries when commands spawn new coroutinesBehavior matrix
runningInConsole()php artisan migratetruetrueArtisan::call()from CLItrueschedule:run)truefalseArtisan::call()from HTTP controllerfalsefalseChanges
Application.php- AddedrunningInConsole()andmarkAsRunningInConsole()methods using ContextApplication.php(Contract) - Added method signatures to interfaceKernel.php- CallsmarkAsRunningInConsole()inhandle()(CLI entry point only)Command.php- Propagates console context across coroutine boundariesApp.php(Facade) - Regenerated docblocks to include new methodsTests
10 tests covering:
falsemarkAsRunningInConsole()sets state totrueKernel::handle()sets the flagArtisan::call()alone doesn't set the flagtrueKernel::call()without priorhandle()seesfalseapp()helper reflects stateschedule:run