diff --git a/.travis.yml b/.travis.yml index 8b7faf44..15df5365 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,4 +37,4 @@ script: - vendor/bin/phpunit --coverage-clover build/logs/clover.xml after_success: - - vendor/bin/coveralls -v + - vendor/bin/php-coveralls -v diff --git a/composer.json b/composer.json index b45c7ab5..4f593481 100644 --- a/composer.json +++ b/composer.json @@ -26,13 +26,17 @@ "illuminate/contracts": "~5.3", "illuminate/http": "~5.3", "illuminate/support": "~5.3", - "predis/predis": "^1.1" + "predis/predis": "^1.1", + "ext-json": "*", + "ext-fileinfo": "*", + "ext-pdo": "*", + "ext-pcntl": "*" }, "require-dev": { "laravel/lumen-framework": "~5.3", - "phpunit/phpunit": "^6.1", - "phpunit/php-code-coverage": "^5.2", - "satooshi/php-coveralls": "^1.0", + "phpunit/phpunit": "^7.5", + "phpunit/php-code-coverage": "^6.1", + "php-coveralls/php-coveralls": "^2.1", "mockery/mockery": "~1.0", "codedungeon/phpunit-result-printer": "^0.14.0", "php-mock/php-mock": "^2.0" diff --git a/config/swoole_http.php b/config/swoole_http.php index a49fcb6b..6825c532 100644 --- a/config/swoole_http.php +++ b/config/swoole_http.php @@ -15,7 +15,7 @@ 'public_path' => base_path('public'), // Determine if to use swoole to respond request for static files 'handle_static_files' => env('SWOOLE_HANDLE_STATIC', true), - 'log' => env('SWOOLE_HTTP_LOG', true), + 'access_log' => env('SWOOLE_HTTP_ACCESS_LOG', true), // You must add --enable-openssl while compiling Swoole // Put `SWOOLE_SOCK_TCP | SWOOLE_SSL` if you want to enable SSL 'socket_type' => SWOOLE_SOCK_TCP, @@ -59,11 +59,11 @@ |-------------------------------------------------------------------------- */ 'hot_reload' => [ - 'enabled' => env('SWOOLE_HOT_RELOAD_ENABLE', true), - 'level' => env('SWOOLE_HOT_RELOAD_DEEP_LEVEL', 10), + 'enabled' => env('SWOOLE_HOT_RELOAD_ENABLE', false), + 'recursively' => env('SWOOLE_HOT_RELOAD_RECURSIVELY', true), 'directory' => env('SWOOLE_HOT_RELOAD_DIRECTORY', base_path()), 'log' => env('SWOOLE_HOT_RELOAD_LOG', true), - 'files' => ['*.php'], + 'filter' => env('SWOOLE_HOT_RELOAD_FILTER', '.php'), ], /* diff --git a/src/Commands/HttpServerCommand.php b/src/Commands/HttpServerCommand.php index 1bbe7582..4422866f 100644 --- a/src/Commands/HttpServerCommand.php +++ b/src/Commands/HttpServerCommand.php @@ -3,8 +3,19 @@ namespace SwooleTW\Http\Commands; use Illuminate\Console\Command; +use Illuminate\Console\OutputStyle; +use Illuminate\Contracts\Container\Container; use Illuminate\Support\Arr; use Swoole\Process; +use SwooleTW\Http\Helpers\Alias; +use SwooleTW\Http\HotReload\FSEvent; +use SwooleTW\Http\HotReload\FSOutput; +use SwooleTW\Http\HotReload\FSProcess; +use SwooleTW\Http\Middlewares\AccessLog; +use SwooleTW\Http\Server\AccessOutput; +use SwooleTW\Http\Server\Facades\Server; +use SwooleTW\Http\Server\Manager; +use Symfony\Component\Console\Output\ConsoleOutput; use Throwable; /** @@ -66,7 +77,7 @@ public function handle() */ protected function loadConfigs() { - $this->config = $this->laravel->make('config')->get('swoole_http'); + $this->config = $this->laravel->make(Alias::CONFIG)->get('swoole_http'); } /** @@ -90,17 +101,30 @@ protected function start() $host = Arr::get($this->config, 'server.host'); $port = Arr::get($this->config, 'server.port'); + $hotReloadEnabled = Arr::get($this->config, 'hot_reload.enabled'); + $accessLogEnabled = Arr::get($this->config, 'server.access_log'); $this->info('Starting swoole http server...'); $this->info("Swoole http server started: "); if ($this->isDaemon()) { $this->info( - '> (You can run this command to ensure the '. + '> (You can run this command to ensure the ' . 'swoole_http_server process is running: ps aux|grep "swoole")' ); } - $this->laravel->make('swoole.manager')->run(); + $manager = $this->laravel->make(Manager::class); + $server = $this->laravel->make(Server::class); + + if ($accessLogEnabled) { + $this->registerAccessLog(); + } + + if ($hotReloadEnabled) { + $manager->addProcess($this->getHotReloadProcess($server)); + } + + $manager->run(); } /** @@ -230,6 +254,26 @@ protected function initAction() } } + /** + * @param \SwooleTW\Http\Server\Facades\Server $server + * + * @return \Swoole\Process + */ + protected function getHotReloadProcess($server) + { + $recursively = Arr::get($this->config, 'hot_reload.recursively'); + $directory = Arr::get($this->config, 'hot_reload.directory'); + $filter = Arr::get($this->config, 'hot_reload.filter'); + $log = Arr::get($this->config, 'hot_reload.log'); + + $cb = function (FSEvent $event) use ($server, $log) { + $log ? $this->info(FSOutput::format($event)) : null; + $server->reload(); + }; + + return (new FSProcess($filter, $recursively, $directory))->make($cb); + } + /** * If Swoole process is running. * @@ -292,7 +336,7 @@ protected function getCurrentPid() $path = $this->getPidPath(); return $this->currentPid = file_exists($path) - ? (int)file_get_contents($path) ?? $this->removePidFile() + ? (int) file_get_contents($path) ?? $this->removePidFile() : null; } @@ -332,19 +376,37 @@ protected function checkEnvironment() if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $this->error("Swoole extension doesn't support Windows OS yet."); - return; - } else { - if (! extension_loaded('swoole')) { - $this->error("Can't detect Swoole extension installed."); + exit(1); + } - return; - } else { - if (! version_compare(swoole_version(), '4.0.0', 'ge')) { - $this->error("Your Swoole version must be higher than 4.0 to use coroutine."); + if (! extension_loaded('swoole')) { + $this->error("Can't detect Swoole extension installed."); - return; - } - } + exit(1); } + + if (! version_compare(swoole_version(), '4.0.0', 'ge')) { + $this->error("Your Swoole version must be higher than 4.0 to use coroutine."); + + exit(1); + } + } + + /** + * Register access log services. + */ + protected function registerAccessLog() + { + $this->laravel->singleton(OutputStyle::class, function () { + return new OutputStyle($this->input, $this->output); + }); + + $this->laravel->singleton(AccessOutput::class, function () { + return new AccessOutput(new ConsoleOutput); + }); + + $this->laravel->singleton(AccessLog::class, function (Container $container) { + return new AccessLog($container->make(AccessOutput::class)); + }); } } diff --git a/src/Concerns/InteractsWithWebsocket.php b/src/Concerns/InteractsWithWebsocket.php index 81aa724c..3521bc53 100644 --- a/src/Concerns/InteractsWithWebsocket.php +++ b/src/Concerns/InteractsWithWebsocket.php @@ -6,7 +6,9 @@ use Illuminate\Pipeline\Pipeline; use Illuminate\Support\Arr; use SwooleTW\Http\Exceptions\WebsocketNotSetInConfigException; -use SwooleTW\Http\Helpers\Service; +use SwooleTW\Http\Helpers\Alias; +use SwooleTW\Http\Server\Facades\Server; +use SwooleTW\Http\Server\Sandbox; use SwooleTW\Http\Transformers\Request; use SwooleTW\Http\Websocket\HandlerContract; use SwooleTW\Http\Websocket\Parser; @@ -54,8 +56,8 @@ trait InteractsWithWebsocket public function onOpen($swooleRequest) { $illuminateRequest = Request::make($swooleRequest)->toIlluminate(); - $websocket = $this->app->make(Service::WEBSOCKET_ALIAS); - $sandbox = $this->app->make(Service::SANDBOX_ALIAS); + $websocket = $this->app->make(Websocket::class); + $sandbox = $this->app->make(Sandbox::class); try { $websocket->reset(true)->setSender($swooleRequest->fd); @@ -94,8 +96,8 @@ public function onMessage($server, $frame) return; } - $websocket = $this->app->make(Service::WEBSOCKET_ALIAS); - $sandbox = $this->app->make(Service::SANDBOX_ALIAS); + $websocket = $this->app->make(Websocket::class); + $sandbox = $this->app->make(Sandbox::class); try { // decode raw message via parser @@ -132,7 +134,7 @@ public function onClose($server, $fd, $reactorId) return; } - $websocket = $this->app->make(Service::WEBSOCKET_ALIAS); + $websocket = $this->app->make(Websocket::class); try { $websocket->reset(true)->setSender($fd); @@ -172,7 +174,7 @@ public function pushMessage($server, array $data) // push message to designated fds foreach ($push->getDescriptors() as $descriptor) { - if ($server->exist($descriptor) || ! $push->isBroadcastToDescriptor((int)$descriptor)) { + if ($server->exist($descriptor) || ! $push->isBroadcastToDescriptor((int) $descriptor)) { $server->push($descriptor, $payload, $push->getOpcode()); } } @@ -205,7 +207,7 @@ public function getPayloadParser() */ protected function prepareWebsocket() { - $config = $this->container->make(Service::CONFIG_ALIAS); + $config = $this->container->make(Alias::CONFIG); $isWebsocket = $config->get('swoole_http.websocket.enabled'); $parser = $config->get('swoole_websocket.parser'); @@ -225,7 +227,7 @@ protected function prepareWebsocket() */ protected function isServerWebsocket(int $fd): bool { - $info = $this->container->make(Service::SERVER_ALIAS)->connection_info($fd); + $info = $this->container->make(Server::class)->connection_info($fd); return Arr::has($info, 'websocket_status') && Arr::get($info, 'websocket_status'); } @@ -253,7 +255,7 @@ protected function filterWebsocket(array $descriptors): array */ protected function prepareWebsocketHandler() { - $handlerClass = $this->container->make(Service::CONFIG_ALIAS)->get('swoole_websocket.handler'); + $handlerClass = $this->container->make(Alias::CONFIG)->get('swoole_websocket.handler'); if (! $handlerClass) { throw new WebsocketNotSetInConfigException; @@ -303,7 +305,7 @@ protected function createRoom(string $class, array $settings): RoomContract protected function bindRoom(): void { $this->app->singleton(RoomContract::class, function (Container $container) { - $config = $container->make(Service::CONFIG_ALIAS); + $config = $container->make(Alias::CONFIG); $driver = $config->get('swoole_websocket.default'); $settings = $config->get("swoole_websocket.settings.{$driver}"); $className = $config->get("swoole_websocket.drivers.{$driver}"); @@ -311,7 +313,7 @@ protected function bindRoom(): void return $this->createRoom($className, $settings); }); - $this->app->alias(RoomContract::class, 'swoole.room'); + $this->app->alias(RoomContract::class, Alias::ROOM); } /** @@ -320,10 +322,10 @@ protected function bindRoom(): void protected function bindWebsocket() { $this->app->singleton(Websocket::class, function (Container $app) { - return new Websocket($app->make(Service::ROOM_ALIAS), new Pipeline($app)); + return new Websocket($app->make(RoomContract::class), new Pipeline($app)); }); - $this->app->alias(Websocket::class, Service::WEBSOCKET_ALIAS); + $this->app->alias(Websocket::class, 'swoole.websocket'); } /** @@ -331,10 +333,10 @@ protected function bindWebsocket() */ protected function loadWebsocketRoutes() { - $routePath = $this->container->make(Service::CONFIG_ALIAS)->get('swoole_websocket.route_file'); + $routePath = $this->container->make(Alias::CONFIG)->get('swoole_websocket.route_file'); if (! file_exists($routePath)) { - $routePath = __DIR__.'/../../routes/websocket.php'; + $routePath = __DIR__ . '/../../routes/websocket.php'; } return require $routePath; diff --git a/src/Concerns/ResetApplication.php b/src/Concerns/ResetApplication.php index a6c96c01..d6a49593 100644 --- a/src/Concerns/ResetApplication.php +++ b/src/Concerns/ResetApplication.php @@ -2,6 +2,7 @@ namespace SwooleTW\Http\Concerns; +use Illuminate\Contracts\Config\Repository; use Illuminate\Contracts\Container\Container; use SwooleTW\Http\Exceptions\SandboxException; use SwooleTW\Http\Server\Resetters\ResetterContract; @@ -28,7 +29,7 @@ trait ResetApplication */ protected function setInitialConfig() { - $this->config = clone $this->getBaseApp()->make('config'); + $this->config = clone $this->getBaseApp()->make(Repository::class); } /** @@ -74,7 +75,7 @@ protected function setInitialResetters() foreach ($resetters as $resetter) { $resetterClass = $app->make($resetter); if (! $resetterClass instanceof ResetterContract) { - throw new SandboxException("{$resetter} must implement ".ResetterContract::class); + throw new SandboxException("{$resetter} must implement " . ResetterContract::class); } $this->resetters[$resetter] = $resetterClass; } diff --git a/src/Concerns/WithApplication.php b/src/Concerns/WithApplication.php index 8aa54ec4..3c56512d 100644 --- a/src/Concerns/WithApplication.php +++ b/src/Concerns/WithApplication.php @@ -6,7 +6,7 @@ use Illuminate\Contracts\Http\Kernel; use Illuminate\Support\Facades\Facade; use SwooleTW\Http\Exceptions\FrameworkNotSupportException; -use SwooleTW\Http\Helpers\Service; +use SwooleTW\Http\Helpers\Alias; /** * Trait WithApplication @@ -149,7 +149,7 @@ public function getBasePath() */ protected function preResolveInstances() { - $resolves = $this->container->make(Service::CONFIG_ALIAS)->get('swoole_http.pre_resolved', []); + $resolves = $this->container->make(Alias::CONFIG)->get('swoole_http.pre_resolved', []); foreach ($resolves as $abstract) { if ($this->getApplication()->offsetExists($abstract)) { diff --git a/src/Controllers/SocketIOController.php b/src/Controllers/SocketIOController.php index 321aed94..159adfd8 100644 --- a/src/Controllers/SocketIOController.php +++ b/src/Controllers/SocketIOController.php @@ -34,7 +34,7 @@ public function upgrade(Request $request) ] ); - return '97:0'.$payload.'2:40'; + return '97:0' . $payload . '2:40'; } public function reject() diff --git a/src/Coroutine/Connectors/ConnectorFactory.php b/src/Coroutine/Connectors/ConnectorFactory.php index 32f6e437..fd402338 100644 --- a/src/Coroutine/Connectors/ConnectorFactory.php +++ b/src/Coroutine/Connectors/ConnectorFactory.php @@ -29,7 +29,7 @@ class ConnectorFactory * * @const string */ - public const CONNECTOR_CLASS_PATH = __DIR__.'/MySqlConnector.php'; + public const CONNECTOR_CLASS_PATH = __DIR__ . '/MySqlConnector.php'; /** * @param string $version @@ -41,7 +41,7 @@ public static function make(string $version): MySqlConnector $isMatch = static::isFileVersionMatch($version); $class = static::copy(static::stub($version), ! $isMatch); - return new $class(); + return new $class; } /** @@ -52,8 +52,8 @@ public static function make(string $version): MySqlConnector public static function stub(string $version): string { return static::hasBreakingChanges($version) - ? __DIR__.'/../../../stubs/5.6/MySqlConnector.stub' - : __DIR__.'/../../../stubs/5.5/MySqlConnector.stub'; + ? __DIR__ . '/../../../stubs/5.6/MySqlConnector.stub' + : __DIR__ . '/../../../stubs/5.5/MySqlConnector.stub'; } /** diff --git a/src/Coroutine/Connectors/MySqlConnector.php b/src/Coroutine/Connectors/MySqlConnector.php index 2efa720a..7082d761 100644 --- a/src/Coroutine/Connectors/MySqlConnector.php +++ b/src/Coroutine/Connectors/MySqlConnector.php @@ -2,6 +2,7 @@ namespace SwooleTW\Http\Coroutine\Connectors; + use Illuminate\Database\Connectors\MySqlConnector as BaseConnector; use Illuminate\Support\Str; use SwooleTW\Http\Coroutine\PDO as SwoolePDO; diff --git a/src/Coroutine/PDO.php b/src/Coroutine/PDO.php index 54e44972..bf51a519 100644 --- a/src/Coroutine/PDO.php +++ b/src/Coroutine/PDO.php @@ -61,7 +61,7 @@ public function __construct(string $dsn, string $username = '', string $password */ protected function setClient($client = null) { - $this->client = $client ?: new \Swoole\Coroutine\Mysql(); + $this->client = $client ?: new \Swoole\Coroutine\Mysql; } /** diff --git a/src/Coroutine/PDOStatement.php b/src/Coroutine/PDOStatement.php index 62a32d48..fcd605ab 100644 --- a/src/Coroutine/PDOStatement.php +++ b/src/Coroutine/PDOStatement.php @@ -74,7 +74,7 @@ public function bindValue($parameter, $variable, $type = null) if (! method_exists($variable, '__toString')) { return false; } else { - $variable = (string)$variable; + $variable = (string) $variable; } } @@ -154,7 +154,8 @@ private function transStyle( $fetchStyle = null, $fetchArgument = null, $ctorArgs = null - ) { + ) + { if (! is_array($rawData)) { return false; } @@ -178,7 +179,7 @@ private function transStyle( break; case PDO::FETCH_OBJ: foreach ($rawData as $row) { - $resultSet[] = (object)$row; + $resultSet[] = (object) $row; } break; case PDO::FETCH_NUM: @@ -199,11 +200,12 @@ public function fetch( $cursorOrientation = null, $cursorOffset = null, $fetchArgument = null - ) { + ) + { $this->__executeWhenStringQueryEmpty(); $cursorOrientation = is_null($cursorOrientation) ? PDO::FETCH_ORI_NEXT : $cursorOrientation; - $cursorOffset = is_null($cursorOffset) ? 0 : (int)$cursorOffset; + $cursorOffset = is_null($cursorOffset) ? 0 : (int) $cursorOffset; switch ($cursorOrientation) { case PDO::FETCH_ORI_ABS: @@ -234,7 +236,8 @@ public function fetch( /** * Returns a single column from the next row of a result set or FALSE if there are no more rows. * - * @param int $column_number + * @param int|null $columnNumber + * * 0-indexed number of the column you wish to retrieve from the row. * If no value is supplied, PDOStatement::fetchColumn() fetches the first column. * diff --git a/src/Helpers/Alias.php b/src/Helpers/Alias.php new file mode 100644 index 00000000..96e53256 --- /dev/null +++ b/src/Helpers/Alias.php @@ -0,0 +1,17 @@ +when = $when; + $this->path = $path; + $this->types = $types; + } + + /** + * @return \Carbon\Carbon + */ + public function getWhen(): Carbon + { + return $this->when; + } + + /** + * @return string + */ + public function getPath(): string + { + return $this->path; + } + + /** + * @return array + */ + public function getTypes(): array + { + return $this->types; + } + + /** + * @return string + */ + public function getType(): string + { + return Arr::first($this->types); + } + + /** + * Checks if event types has needed type(s). + * + * @param string ...$types + * + * @return bool + */ + public function isType(string ...$types): bool + { + return count(array_intersect($this->types, $types)) > 0; + } + + /** + * Get possible event types. + * + * @return array + */ + public static function getPossibleTypes(): array + { + return self::$possibleTypes; + } +} \ No newline at end of file diff --git a/src/HotReload/FSEventParser.php b/src/HotReload/FSEventParser.php new file mode 100644 index 00000000..c0c35ef6 --- /dev/null +++ b/src/HotReload/FSEventParser.php @@ -0,0 +1,37 @@ +getPath()) ? 'Directory' : 'File'; + $events = implode(', ', $event->getTypes()); + $time = $event->getWhen()->format('Y.m.d H:i:s'); + + return sprintf('%s: %s %s at %s', $item, $event->getPath(), $events, $time); + } +} \ No newline at end of file diff --git a/src/HotReload/FSProcess.php b/src/HotReload/FSProcess.php new file mode 100644 index 00000000..4747d07b --- /dev/null +++ b/src/HotReload/FSProcess.php @@ -0,0 +1,96 @@ +filter = $filter; + $this->recursively = $recursively; + $this->directory = $directory; + $this->locked = false; + } + + /** + * Make swoole process. + * + * @param callable|null $callback + * + * @return \Swoole\Process + */ + public function make(?callable $callback = null) + { + $mcb = function ($type, $buffer) use ($callback) { + if (! $this->locked && AppProcess::OUT === $type && $event = FSEventParser::toEvent($buffer)) { + $this->locked = true; + ($callback) ? $callback($event) : null; + $this->locked = false; + unset($event); + } + }; + + return new SwooleProcess(function () use ($mcb) { + (new AppProcess($this->configure()))->setTimeout(0)->run($mcb); + }, false, false); + } + + /** + * Configure process. + * + * @return array + */ + protected function configure(): array + { + return [ + 'fswatch', + $this->recursively ? '-rtx' : '-tx', + '-e', + '.*', + '-i', + "\\{$this->filter}$", + $this->directory, + ]; + } +} diff --git a/src/HttpServiceProvider.php b/src/HttpServiceProvider.php index 071291ca..af26c57e 100644 --- a/src/HttpServiceProvider.php +++ b/src/HttpServiceProvider.php @@ -2,15 +2,19 @@ namespace SwooleTW\Http; -use Illuminate\Queue\Capsule\Manager; +use Illuminate\Contracts\Http\Kernel; +use Illuminate\Database\DatabaseManager; +use Illuminate\Queue\QueueManager; +use Illuminate\Support\Arr; use Illuminate\Support\ServiceProvider; use Swoole\Http\Server as HttpServer; use Swoole\Websocket\Server as WebsocketServer; use SwooleTW\Http\Commands\HttpServerCommand; use SwooleTW\Http\Coroutine\Connectors\ConnectorFactory; use SwooleTW\Http\Coroutine\MySqlConnection; +use SwooleTW\Http\Helpers\Alias; use SwooleTW\Http\Helpers\FW; -use SwooleTW\Http\Helpers\Service; +use SwooleTW\Http\Middlewares\AccessLog; use SwooleTW\Http\Server\Facades\Server; use SwooleTW\Http\Task\Connectors\SwooleTaskConnector; @@ -73,18 +77,22 @@ abstract protected function bootRoutes(); */ public function boot() { - $this->publishes( - [ - __DIR__.'/../config/swoole_http.php' => base_path('config/swoole_http.php'), - __DIR__.'/../config/swoole_websocket.php' => base_path('config/swoole_websocket.php'), - __DIR__.'/../routes/websocket.php' => base_path('routes/websocket.php'), - ], - 'laravel-swoole' - ); - - if ($this->app->make(Service::CONFIG_ALIAS)->get('swoole_http.websocket.enabled')) { + $this->publishes([ + __DIR__ . '/../config/swoole_http.php' => base_path('config/swoole_http.php'), + __DIR__ . '/../config/swoole_websocket.php' => base_path('config/swoole_websocket.php'), + __DIR__ . '/../routes/websocket.php' => base_path('routes/websocket.php'), + ], 'laravel-swoole'); + + $config = $this->app->make(Alias::CONFIG); + + if ($config->get('swoole_http.websocket.enabled')) { $this->bootRoutes(); } + + if ($config->get('swoole_http.server.access_log')) { + $this->app->make(Kernel::class)->pushMiddleware(AccessLog::class); +// dd($this->app->make(Kernel::class)); + } } /** @@ -92,8 +100,8 @@ public function boot() */ protected function mergeConfigs() { - $this->mergeConfigFrom(__DIR__.'/../config/swoole_http.php', 'swoole_http'); - $this->mergeConfigFrom(__DIR__.'/../config/swoole_websocket.php', 'swoole_websocket'); + $this->mergeConfigFrom(__DIR__ . '/../config/swoole_http.php', 'swoole_http'); + $this->mergeConfigFrom(__DIR__ . '/../config/swoole_websocket.php', 'swoole_websocket'); } /** @@ -101,7 +109,7 @@ protected function mergeConfigs() */ protected function setIsWebsocket() { - $this->isWebsocket = $this->app->make(Service::CONFIG_ALIAS)->get('swoole_http.websocket.enabled'); + $this->isWebsocket = $this->app->make(Alias::CONFIG)->get('swoole_http.websocket.enabled'); } /** @@ -109,11 +117,9 @@ protected function setIsWebsocket() */ protected function registerCommands() { - $this->commands( - [ - HttpServerCommand::class, - ] - ); + $this->commands([ + HttpServerCommand::class, + ]); } /** @@ -122,7 +128,7 @@ protected function registerCommands() protected function createSwooleServer() { $server = $this->isWebsocket ? WebsocketServer::class : HttpServer::class; - $config = $this->app->make(Service::CONFIG_ALIAS); + $config = $this->app->make(Alias::CONFIG); $host = $config->get('swoole_http.server.host'); $port = $config->get('swoole_http.server.port'); $socketType = $config->get('swoole_http.server.socket_type', SWOOLE_SOCK_TCP); @@ -136,7 +142,7 @@ protected function createSwooleServer() */ protected function configureSwooleServer() { - $config = $this->app->make(Service::CONFIG_ALIAS); + $config = $this->app->make(Alias::CONFIG); $options = $config->get('swoole_http.server.options'); // only enable task worker in websocket mode and for queue driver @@ -162,8 +168,7 @@ protected function registerServer() return static::$server; }); - - $this->app->alias(Server::class, Service::SERVER_ALIAS); + $this->app->alias(Server::class, Alias::SERVER); } /** @@ -171,18 +176,18 @@ protected function registerServer() */ protected function registerDatabaseDriver() { - $this->app->extend('db', function ($db) { + $this->app->extend(DatabaseManager::class, function (DatabaseManager $db) { $db->extend('mysql-coroutine', function ($config, $name) { $config = $this->getMergedDatabaseConfig($config, $name); $connection = new MySqlConnection( $this->getNewMySqlConnection($config), - $config['database'], - $config['prefix'], + Arr::get($config, 'database'), + Arr::get($config, 'prefix'), $config ); - if (isset($config['read'])) { + if (Arr::has($config, 'read')) { $connection->setReadPdo($this->getNewMySqlConnection($config)); } @@ -203,16 +208,12 @@ protected function registerDatabaseDriver() */ protected function getMergedDatabaseConfig(array $config, string $name) { - $config['name'] = $name; - - if (isset($config['read'])) { - $config = array_merge($config, $config['read']); - } - if (isset($config['write'])) { - $config = array_merge($config, $config['write']); - } + $newConfig = $config; + $newConfig = Arr::add($newConfig, 'name', $name); + $newConfig = array_merge($newConfig, Arr::get($newConfig, 'read', [])); + $newConfig = array_merge($newConfig, Arr::get($newConfig, 'write', [])); - return $config; + return $newConfig; } /** @@ -232,7 +233,7 @@ protected function getNewMySqlConnection(array $config) */ protected function registerSwooleQueueDriver() { - $this->app->afterResolving('queue', function (Manager $manager) { + $this->app->afterResolving(Alias::QUEUE, function (QueueManager $manager) { $manager->addConnector('swoole', function () { return new SwooleTaskConnector($this->app->make(Server::class)); }); diff --git a/src/LaravelServiceProvider.php b/src/LaravelServiceProvider.php index 5cf86a30..711ead56 100644 --- a/src/LaravelServiceProvider.php +++ b/src/LaravelServiceProvider.php @@ -2,6 +2,7 @@ namespace SwooleTW\Http; +use SwooleTW\Http\Helpers\Alias; use SwooleTW\Http\Server\Manager; /** @@ -16,9 +17,11 @@ class LaravelServiceProvider extends HttpServiceProvider */ protected function registerManager() { - $this->app->singleton('swoole.manager', function ($app) { + $this->app->singleton(Manager::class, function ($app) { return new Manager($app, 'laravel'); }); + + $this->app->alias(Manager::class, Alias::MANAGER); } /** @@ -28,6 +31,6 @@ protected function registerManager() */ protected function bootRoutes() { - require __DIR__.'/../routes/laravel_routes.php'; + require __DIR__ . '/../routes/laravel_routes.php'; } } diff --git a/src/LumenServiceProvider.php b/src/LumenServiceProvider.php index 40f218b4..499af4bc 100644 --- a/src/LumenServiceProvider.php +++ b/src/LumenServiceProvider.php @@ -2,6 +2,7 @@ namespace SwooleTW\Http; +use SwooleTW\Http\Helpers\Alias; use SwooleTW\Http\Server\Manager; /** @@ -16,9 +17,11 @@ class LumenServiceProvider extends HttpServiceProvider */ protected function registerManager() { - $this->app->singleton('swoole.manager', function ($app) { + $this->app->singleton(Manager::class, function ($app) { return new Manager($app, 'lumen'); }); + + $this->app->alias(Manager::class, Alias::MANAGER); } /** @@ -32,11 +35,11 @@ protected function bootRoutes() if (property_exists($app, 'router')) { $app->router->group(['namespace' => 'SwooleTW\Http\Controllers'], function ($app) { - require __DIR__.'/../routes/lumen_routes.php'; + require __DIR__ . '/../routes/lumen_routes.php'; }); } else { $app->group(['namespace' => 'App\Http\Controllers'], function ($app) { - require __DIR__.'/../routes/lumen_routes.php'; + require __DIR__ . '/../routes/lumen_routes.php'; }); } } diff --git a/src/Middlewares/AccessLog.php b/src/Middlewares/AccessLog.php new file mode 100644 index 00000000..5cc0a4fa --- /dev/null +++ b/src/Middlewares/AccessLog.php @@ -0,0 +1,55 @@ +output = $output; + } + + /** + * Handle the incoming request. + * + * @param \Illuminate\Http\Request $request + * @param \Closure $next + * + * @return mixed + */ + public function handle($request, Closure $next) + { + return $next($request); + } + + /** + * Handle the outgoing request and response. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Response $response + */ + public function terminate(Request $request, Response $response) + { + $this->output->log($request, $response); + } +} \ No newline at end of file diff --git a/src/Server/AccessOutput.php b/src/Server/AccessOutput.php new file mode 100644 index 00000000..c93ef64b --- /dev/null +++ b/src/Server/AccessOutput.php @@ -0,0 +1,71 @@ +output = $output; + } + + /** + * Access log. + * + * @param \Illuminate\Http\Request $request + * @param \Illuminate\Http\Response $response + */ + public function log(Request $request, Response $response): void + { + $host = $request->url(); + $method = $request->method(); + $agent = $request->userAgent(); + $date = $this->date($response->getDate()); + $status = $response->status(); + $style = $this->style($status); + + $this->output->writeln( + sprintf("%s %s %s <$style>%d %s", $host, $date, $method, $status, $agent) + ); + } + + /** + * @param \DateTimeInterface $date + * + * @return string + */ + protected function date(DateTimeInterface $date): string + { + return $date->format('Y-m-d H:i:s'); + } + + /** + * @param int $status + * + * @return string + */ + protected function style(int $status): string + { + return $status !== Response::HTTP_OK ? 'error' : 'info'; + } +} \ No newline at end of file diff --git a/src/Server/Facades/Sandbox.php b/src/Server/Facades/Sandbox.php index 8c468254..8cee44dd 100644 --- a/src/Server/Facades/Sandbox.php +++ b/src/Server/Facades/Sandbox.php @@ -3,6 +3,7 @@ namespace SwooleTW\Http\Server\Facades; use Illuminate\Support\Facades\Facade; +use SwooleTW\Http\Helpers\Alias; class Sandbox extends Facade { @@ -13,6 +14,6 @@ class Sandbox extends Facade */ protected static function getFacadeAccessor() { - return 'swoole.sandbox'; + return Alias::SANDBOX; } } \ No newline at end of file diff --git a/src/Server/Facades/Server.php b/src/Server/Facades/Server.php index 7a34102a..4dd8195a 100644 --- a/src/Server/Facades/Server.php +++ b/src/Server/Facades/Server.php @@ -3,7 +3,13 @@ namespace SwooleTW\Http\Server\Facades; use Illuminate\Support\Facades\Facade; +use SwooleTW\Http\Helpers\Alias; +/** + * Class Server + * + * @mixin \Swoole\Http\Server + */ class Server extends Facade { /** @@ -13,6 +19,6 @@ class Server extends Facade */ protected static function getFacadeAccessor() { - return 'swoole.server'; + return Alias::SERVER; } } \ No newline at end of file diff --git a/src/Server/Manager.php b/src/Server/Manager.php index 3eb47bb1..7d82e8ef 100644 --- a/src/Server/Manager.php +++ b/src/Server/Manager.php @@ -5,12 +5,15 @@ use Exception; use Illuminate\Contracts\Container\Container; use Illuminate\Contracts\Debug\ExceptionHandler; +use Illuminate\Events\Dispatcher; use Illuminate\Support\Facades\Facade; use Illuminate\Support\Str; +use Swoole\Process; use SwooleTW\Http\Concerns\InteractsWithSwooleTable; use SwooleTW\Http\Concerns\InteractsWithWebsocket; use SwooleTW\Http\Concerns\WithApplication; use SwooleTW\Http\Helpers\OS; +use SwooleTW\Http\Server\Facades\Server; use SwooleTW\Http\Task\SwooleTaskJob; use SwooleTW\Http\Transformers\Request; use SwooleTW\Http\Transformers\Response; @@ -88,7 +91,7 @@ public function __construct(Container $container, $framework, $basePath = null) */ public function run() { - $this->container->make('swoole.server')->start(); + $this->container->make(Server::class)->start(); } /** @@ -96,7 +99,7 @@ public function run() */ public function stop() { - $this->container->make('swoole.server')->shutdown(); + $this->container->make(Server::class)->shutdown(); } /** @@ -120,7 +123,7 @@ protected function setSwooleServerListeners() $this->container->make('events')->fire("swoole.$event", func_get_args()); }; - $this->container->make('swoole.server')->on($event, $callback); + $this->container->make(Server::class)->on($event, $callback); } } @@ -143,7 +146,7 @@ public function onStart() public function onManagerStart() { $this->setProcessName('manager process'); - $this->container->make('events')->fire('swoole.managerStart', func_get_args()); + $this->container->make(Dispatcher::class)->fire('swoole.managerStart', func_get_args()); } /** @@ -194,6 +197,7 @@ public function onRequest($swooleRequest, $swooleResponse) $this->app->make('events')->fire('swoole.request'); $this->resetOnRequest(); + $sandbox = $this->app->make(Sandbox::class);; $handleStatic = $this->container->make('config')->get('swoole_http.handle_static_files', true); $publicPath = $this->container->make('config')->get('swoole_http.server.public_path', base_path('public')); @@ -206,25 +210,26 @@ public function onRequest($swooleRequest, $swooleResponse) $illuminateRequest = Request::make($swooleRequest)->toIlluminate(); // set current request to sandbox - $this->app->make('swoole.sandbox')->setRequest($illuminateRequest); + $sandbox->setRequest($illuminateRequest); + // enable sandbox - $this->app->make('swoole.sandbox')->enable(); + $sandbox->enable(); // handle request via laravel/lumen's dispatcher - $illuminateResponse = $this->app->make('swoole.sandbox')->run($illuminateRequest); - $response = Response::make($illuminateResponse, $swooleResponse); - $response->send(); + $illuminateResponse = $sandbox->run($illuminateRequest); + + // send response + Response::make($illuminateResponse, $swooleResponse)->send(); } catch (Throwable $e) { try { $exceptionResponse = $this->app->make(ExceptionHandler::class)->render(null, $e); - $response = Response::make($exceptionResponse, $swooleResponse); - $response->send(); + Response::make($exceptionResponse, $swooleResponse)->send(); } catch (Throwable $e) { $this->logServerError($e); } } finally { // disable and recycle sandbox resource - $this->app->make('swoole.sandbox')->disable(); + $sandbox->disable(); } } @@ -235,7 +240,7 @@ protected function resetOnRequest() { // Reset websocket data if ($this->isServerWebsocket) { - $this->app->make('swoole.websocket')->reset(true); + $this->app->make(Websocket::class)->reset(true); } } @@ -339,7 +344,7 @@ protected function getPidFile() protected function createPidFile() { $pidFile = $this->getPidFile(); - $pid = $this->container['swoole.server']->master_pid; + $pid = $this->container->make(Server::class)->master_pid; file_put_contents($pidFile, $pid); } @@ -391,6 +396,16 @@ protected function setProcessName($process) swoole_set_process_name($name); } + /** + * Add process to http server + * + * @param \Swoole\Process $process + */ + public function addProcess(Process $process): void + { + $this->container->make(Server::class)->addProcess($process); + } + /** * Indicates if it's in phpunit environment. * diff --git a/src/Server/Sandbox.php b/src/Server/Sandbox.php index ccf0f74c..29c50bb1 100644 --- a/src/Server/Sandbox.php +++ b/src/Server/Sandbox.php @@ -31,6 +31,11 @@ class Sandbox /** * Constructor + * + * @param null $app + * @param null $framework + * + * @throws \SwooleTW\Http\Exceptions\SandboxException */ public function __construct($app = null, $framework = null) { @@ -45,6 +50,10 @@ public function __construct($app = null, $framework = null) /** * Set framework type. + * + * @param string $framework + * + * @return \SwooleTW\Http\Server\Sandbox */ public function setFramework(string $framework) { @@ -65,6 +74,8 @@ public function getFramework() * Set a base application. * * @param \Illuminate\Container\Container + * + * @return \SwooleTW\Http\Server\Sandbox */ public function setBaseApp(Container $app) { @@ -77,6 +88,8 @@ public function setBaseApp(Container $app) * Set current request. * * @param \Illuminate\Http\Request + * + * @return \SwooleTW\Http\Server\Sandbox */ public function setRequest(Request $request) { @@ -89,6 +102,8 @@ public function setRequest(Request $request) * Set current snapshot. * * @param \Illuminate\Container\Container + * + * @return \SwooleTW\Http\Server\Sandbox */ public function setSnapshot(Container $snapshot) { @@ -99,6 +114,8 @@ public function setSnapshot(Container $snapshot) /** * Initialize based on base app. + * + * @throws \SwooleTW\Http\Exceptions\SandboxException */ public function initialize() { @@ -147,6 +164,8 @@ public function getApplication() * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response + * @throws \SwooleTW\Http\Exceptions\SandboxException + * @throws \ReflectionException */ public function run(Request $request) { @@ -169,6 +188,7 @@ public function run(Request $request) * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response + * @throws \ReflectionException */ protected function prepareResponse(Request $request) { @@ -187,6 +207,7 @@ protected function prepareResponse(Request $request) * @param \Illuminate\Http\Request $request * * @return \Illuminate\Http\Response + * @throws \ReflectionException */ protected function prepareObResponse(Request $request) { @@ -203,7 +224,7 @@ protected function prepareObResponse(Request $request) } elseif ($response instanceof SymfonyResponse) { $content = $response->getContent(); } elseif (! $isFile = $response instanceof BinaryFileResponse) { - $content = (string)$response; + $content = (string) $response; } // process terminating logics @@ -214,7 +235,7 @@ protected function prepareObResponse(Request $request) if ($isStream) { $response->output = ob_get_contents(); } else { - $response->setContent(ob_get_contents().$content); + $response->setContent(ob_get_contents() . $content); } } @@ -258,29 +279,35 @@ public function isLaravel() /** * @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Response $response + * + * @throws \ReflectionException */ public function terminate(Request $request, $response) { if ($this->isLaravel()) { $this->getKernel()->terminate($request, $response); - } else { - $app = $this->getApplication(); - $reflection = new \ReflectionObject($app); - $middleware = $reflection->getProperty('middleware'); - $middleware->setAccessible(true); + return; + } - $callTerminableMiddleware = $reflection->getMethod('callTerminableMiddleware'); - $callTerminableMiddleware->setAccessible(true); + $app = $this->getApplication(); + $reflection = new \ReflectionObject($app); - if (count($middleware->getValue($app)) > 0) { - $callTerminableMiddleware->invoke($app, $response); - } + $middleware = $reflection->getProperty('middleware'); + $middleware->setAccessible(true); + + $callTerminableMiddleware = $reflection->getMethod('callTerminableMiddleware'); + $callTerminableMiddleware->setAccessible(true); + + if (count($middleware->getValue($app)) > 0) { + $callTerminableMiddleware->invoke($app, $response); } } /** * Set laravel snapshot to container and facade. + * + * @throws \SwooleTW\Http\Exceptions\SandboxException */ public function enable() { @@ -303,6 +330,8 @@ public function disable() /** * Replace app's self bindings. + * + * @param \Illuminate\Container\Container $app */ public function setInstance(Container $app) { diff --git a/src/Task/QueueFactory.php b/src/Task/QueueFactory.php index 72cdee8c..4610827c 100644 --- a/src/Task/QueueFactory.php +++ b/src/Task/QueueFactory.php @@ -30,7 +30,7 @@ class QueueFactory * * @const string */ - public const QUEUE_CLASS_PATH = __DIR__.'/SwooleTaskQueue.php'; + public const QUEUE_CLASS_PATH = __DIR__ . '/SwooleTaskQueue.php'; /** * @param \Swoole\Http\Server $server @@ -54,8 +54,8 @@ public static function make($server, string $version): Queue public static function stub(string $version): string { return static::hasBreakingChanges($version) - ? __DIR__.'/../../stubs/5.7/SwooleTaskQueue.stub' - : __DIR__.'/../../stubs/5.6/SwooleTaskQueue.stub'; + ? __DIR__ . '/../../stubs/5.7/SwooleTaskQueue.stub' + : __DIR__ . '/../../stubs/5.6/SwooleTaskQueue.stub'; } /** diff --git a/src/Task/SwooleTaskQueue.php b/src/Task/SwooleTaskQueue.php index 760b9345..6d2fb32c 100644 --- a/src/Task/SwooleTaskQueue.php +++ b/src/Task/SwooleTaskQueue.php @@ -54,7 +54,7 @@ public function push($job, $data = '', $queue = null) */ public function pushRaw($payload, $queue = null, array $options = []) { - return $this->swoole->task($payload, ! is_numeric($queue) ? 1 : (int)$queue); + return $this->swoole->task($payload, ! is_numeric($queue) ? 1 : (int) $queue); } /** diff --git a/src/Transformers/Request.php b/src/Transformers/Request.php index 2b48c6e1..eefd2bdf 100644 --- a/src/Transformers/Request.php +++ b/src/Transformers/Request.php @@ -3,6 +3,7 @@ namespace SwooleTW\Http\Transformers; use Illuminate\Http\Request as IlluminateRequest; +use Illuminate\Http\Response as IlluminateResponse; use Swoole\Http\Request as SwooleRequest; use Symfony\Component\HttpFoundation\ParameterBag; use Symfony\Component\HttpFoundation\Request as SymfonyRequest; @@ -12,7 +13,17 @@ */ class Request { - private const BLACK_LIST = ['php', 'htaccess', 'config']; + /** + * Blacklisted extensions + * + * @const array + */ + protected const EXTENSION_BLACKLIST = ['php', 'htaccess', 'config']; + + /** + * Extension mime types + */ + protected const EXTENSION_MIMES = ['js' => 'text/javascript', 'css' => 'text/css']; /** * @var \Illuminate\Http\Request @@ -28,29 +39,17 @@ class Request */ public static function make(SwooleRequest $swooleRequest) { - list( - $get, $post, $cookie, $files, $server, $content - ) - = static::toIlluminateParameters($swooleRequest); - - return new static($get, $post, $cookie, $files, $server, $content); + return new static(...static::toIlluminateParameters($swooleRequest)); } /** * Request constructor. * - * @param array $get - * @param array $post - * @param array $cookie - * @param array $files - * @param array $server - * @param string $content - * - * @throws \LogicException + * @param array $params provides GET, POST, COOKIE, FILES, SERVER, CONTENT */ - public function __construct(array $get, array $post, array $cookie, array $files, array $server, $content = null) + public function __construct(...$params) { - $this->createIlluminateRequest($get, $post, $cookie, $files, $server, $content); + $this->createIlluminateRequest(...$params); } /** @@ -126,12 +125,12 @@ public function getIlluminateRequest() */ protected static function toIlluminateParameters(SwooleRequest $request) { - $get = isset($request->get) ? $request->get : []; - $post = isset($request->post) ? $request->post : []; - $cookie = isset($request->cookie) ? $request->cookie : []; - $files = isset($request->files) ? $request->files : []; - $header = isset($request->header) ? $request->header : []; - $server = isset($request->server) ? $request->server : []; + $get = $request->get ?? []; + $post = $request->post ?? []; + $cookie = $request->cookie ?? []; + $files = $request->files ?? []; + $header = $request->header ?? []; + $server = $request->server ?? []; $server = static::transformServerParameters($server, $header); $content = $request->rawContent(); @@ -160,7 +159,7 @@ protected static function transformServerParameters(array $server, array $header $key = strtoupper($key); if (! in_array($key, ['REMOTE_ADDR', 'SERVER_PORT', 'HTTPS'])) { - $key = 'HTTP_'.$key; + $key = 'HTTP_' . $key; } $__SERVER[$key] = $value; @@ -176,32 +175,27 @@ protected static function transformServerParameters(array $server, array $header * @param \Swoole\Http\Response $swooleResponse * @param string $publicPath * - * @return boolean|null + * @return boolean */ public static function handleStatic($swooleRequest, $swooleResponse, string $publicPath) { $uri = $swooleRequest->server['request_uri'] ?? ''; - $extension = substr(strrchr($uri, '.'), 1); - if ($extension && in_array($extension, static::BLACK_LIST)) { - return null; - } + $extension = pathinfo($uri, PATHINFO_EXTENSION); + $fileName = $publicPath . $uri; - $filename = $publicPath.$uri; - if (! is_file($filename) || filesize($filename) === 0) { - return null; + if ($extension && in_array($extension, static::EXTENSION_BLACKLIST)) { + return false; } - $swooleResponse->status(200); - $mime = mime_content_type($filename); - if ($extension === 'js') { - $mime = 'text/javascript'; - } else { - if ($extension === 'css') { - $mime = 'text/css'; - } + if (! is_file($fileName) || ! filesize($fileName)) { + return false; } - $swooleResponse->header('Content-Type', $mime); - $swooleResponse->sendfile($filename); + + $contentType = mime_content_type($fileName); + + $swooleResponse->status(IlluminateResponse::HTTP_OK); + $swooleResponse->header('Content-Type', static::EXTENSION_MIMES[$contentType] ?? $contentType); + $swooleResponse->sendfile($fileName); return true; } diff --git a/src/Transformers/Response.php b/src/Transformers/Response.php index 6d7004e9..1f91e05c 100644 --- a/src/Transformers/Response.php +++ b/src/Transformers/Response.php @@ -158,7 +158,7 @@ public function getSwooleResponse() protected function setIlluminateResponse($illuminateResponse) { if (! $illuminateResponse instanceof SymfonyResponse) { - $content = (string)$illuminateResponse; + $content = (string) $illuminateResponse; $illuminateResponse = new IlluminateResponse($content); } diff --git a/src/Transformers/StreamedResponse.php b/src/Transformers/StreamedResponse.php new file mode 100644 index 00000000..31a5e59b --- /dev/null +++ b/src/Transformers/StreamedResponse.php @@ -0,0 +1,38 @@ +output; + } + + /** + * Set output buffer + * + * @param string $output + */ + public function setOutput(?string $output = null): void + { + $this->output = $output; + } +} \ No newline at end of file diff --git a/src/Websocket/Authenticatable.php b/src/Websocket/Authenticatable.php index 8d07e7bf..92276511 100644 --- a/src/Websocket/Authenticatable.php +++ b/src/Websocket/Authenticatable.php @@ -35,7 +35,7 @@ public function loginUsing(AuthenticatableContract $user) */ public function loginUsingId($userId) { - return $this->join(static::USER_PREFIX.$userId); + return $this->join(static::USER_PREFIX . $userId); } /** @@ -49,7 +49,7 @@ public function logout() return null; } - return $this->leave(static::USER_PREFIX.$userId); + return $this->leave(static::USER_PREFIX . $userId); } /** @@ -84,7 +84,7 @@ public function toUserId($userIds) $userIds = is_string($userIds) || is_integer($userIds) ? func_get_args() : $userIds; foreach ($userIds as $userId) { - $fds = $this->room->getClients(static::USER_PREFIX.$userId); + $fds = $this->room->getClients(static::USER_PREFIX . $userId); $this->to($fds); } @@ -120,7 +120,7 @@ public function getUserId() */ public function isUserIdOnline($userId) { - return ! empty($this->room->getClients(static::USER_PREFIX.$userId)); + return ! empty($this->room->getClients(static::USER_PREFIX . $userId)); } /** @@ -131,7 +131,7 @@ public function isUserIdOnline($userId) protected function checkUser($user) { if (! $user instanceOf AuthenticatableContract) { - throw new InvalidArgumentException('user object must implement '.AuthenticatableContract::class); + throw new InvalidArgumentException('user object must implement ' . AuthenticatableContract::class); } } } diff --git a/src/Websocket/Facades/Room.php b/src/Websocket/Facades/Room.php index 72f3122a..d09d7e82 100644 --- a/src/Websocket/Facades/Room.php +++ b/src/Websocket/Facades/Room.php @@ -3,6 +3,7 @@ namespace SwooleTW\Http\Websocket\Facades; use Illuminate\Support\Facades\Facade; +use SwooleTW\Http\Helpers\Alias; /** * Class Room @@ -16,6 +17,6 @@ class Room extends Facade */ protected static function getFacadeAccessor() { - return 'swoole.room'; + return Alias::ROOM; } } \ No newline at end of file diff --git a/src/Websocket/Middleware/DecryptCookies.php b/src/Websocket/Middleware/DecryptCookies.php index d199a703..2807ea1b 100644 --- a/src/Websocket/Middleware/DecryptCookies.php +++ b/src/Websocket/Middleware/DecryptCookies.php @@ -55,7 +55,7 @@ public function __construct(EncrypterContract $encrypter) */ public function disableFor($name) { - $this->except = array_merge($this->except, (array)$name); + $this->except = array_merge($this->except, (array) $name); } /** diff --git a/src/Websocket/Middleware/StartSession.php b/src/Websocket/Middleware/StartSession.php index 332dfdb0..a487f237 100644 --- a/src/Websocket/Middleware/StartSession.php +++ b/src/Websocket/Middleware/StartSession.php @@ -6,6 +6,7 @@ use Illuminate\Contracts\Session\Session; use Illuminate\Http\Request; use Illuminate\Session\SessionManager; +use Illuminate\Support\Arr; /** * Class StartSession @@ -42,9 +43,7 @@ public function __construct(SessionManager $manager) public function handle($request, Closure $next) { if ($this->sessionConfigured()) { - $request->setLaravelSession( - $session = $this->startSession($request) - ); + $request->setLaravelSession($this->startSession($request)); } return $next($request); @@ -87,6 +86,6 @@ public function getSession(Request $request) */ protected function sessionConfigured() { - return ! is_null($this->manager->getSessionConfig()['driver'] ?? null); + return Arr::get($this->manager->getSessionConfig(), 'session') !== null; } } diff --git a/src/Websocket/Parser.php b/src/Websocket/Parser.php index d1722e22..b61c93c6 100644 --- a/src/Websocket/Parser.php +++ b/src/Websocket/Parser.php @@ -26,7 +26,7 @@ public function execute($server, $frame) foreach ($this->strategies as $strategy) { $result = App::call( - $strategy.'@handle', + $strategy . '@handle', [ 'server' => $server, 'frame' => $frame, diff --git a/src/Websocket/Push.php b/src/Websocket/Push.php index 531a7e3e..50323fc8 100644 --- a/src/Websocket/Push.php +++ b/src/Websocket/Push.php @@ -55,7 +55,7 @@ class Push * @param string $event * @param string|null $message */ - private function __construct( + protected function __construct( int $opcode, int $sender, array $descriptors, @@ -63,7 +63,8 @@ private function __construct( bool $assigned, string $event, string $message = null - ) { + ) + { $this->opcode = $opcode; $this->sender = $sender; $this->descriptors = $descriptors; diff --git a/src/Websocket/Rooms/RedisRoom.php b/src/Websocket/Rooms/RedisRoom.php index 16f28f35..d0d39fd4 100644 --- a/src/Websocket/Rooms/RedisRoom.php +++ b/src/Websocket/Rooms/RedisRoom.php @@ -240,8 +240,7 @@ public function getKey(string $key, string $table) */ protected function cleanRooms(): void { - $keys = $this->redis->keys("{$this->prefix}*"); - if (count($keys)) { + if (count($keys = $this->redis->keys("{$this->prefix}*"))) { $this->redis->del($keys); } } diff --git a/src/Websocket/Rooms/TableRoom.php b/src/Websocket/Rooms/TableRoom.php index a02091e2..4d97d78e 100644 --- a/src/Websocket/Rooms/TableRoom.php +++ b/src/Websocket/Rooms/TableRoom.php @@ -177,12 +177,7 @@ public function setValue($key, array $value, string $table) { $this->checkTable($table); - $this->$table->set( - $key, - [ - 'value' => json_encode($value), - ] - ); + $this->$table->set($key, ['value' => \json_encode($value)]); return $this; } @@ -201,7 +196,7 @@ public function getValue(string $key, string $table) $value = $this->$table->get($key); - return $value ? json_decode($value['value'], true) : []; + return $value ? \json_decode($value['value'], true) : []; } /** diff --git a/src/Websocket/SocketIO/Packet.php b/src/Websocket/SocketIO/Packet.php index 5da3f021..f1f34ae4 100644 --- a/src/Websocket/SocketIO/Packet.php +++ b/src/Websocket/SocketIO/Packet.php @@ -118,7 +118,7 @@ public static function getSocketType(string $packet) return null; } - return (int)$type; + return (int) $type; } /** diff --git a/src/Websocket/SocketIO/SocketIOParser.php b/src/Websocket/SocketIO/SocketIOParser.php index 3c259bcf..53483fb4 100644 --- a/src/Websocket/SocketIO/SocketIOParser.php +++ b/src/Websocket/SocketIO/SocketIOParser.php @@ -27,12 +27,12 @@ class SocketIOParser extends Parser */ public function encode(string $event, $data) { - $packet = Packet::MESSAGE.Packet::EVENT; + $packet = Packet::MESSAGE . Packet::EVENT; $shouldEncode = is_array($data) || is_object($data); $data = $shouldEncode ? json_encode($data) : $data; $format = $shouldEncode ? '["%s",%s]' : '["%s","%s"]'; - return $packet.sprintf($format, $event, $data); + return $packet . sprintf($format, $event, $data); } /** diff --git a/src/Websocket/SocketIO/WebsocketHandler.php b/src/Websocket/SocketIO/WebsocketHandler.php index d76b60af..69319692 100644 --- a/src/Websocket/SocketIO/WebsocketHandler.php +++ b/src/Websocket/SocketIO/WebsocketHandler.php @@ -6,6 +6,7 @@ use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Config; use Swoole\Websocket\Frame; +use SwooleTW\Http\Server\Facades\Server; use SwooleTW\Http\Websocket\HandlerContract; class WebsocketHandler implements HandlerContract @@ -29,11 +30,11 @@ public function onOpen($fd, Request $request) 'pingTimeout' => Config::get('swoole_websocket.ping_timeout'), ] ); - $initPayload = Packet::OPEN.$payload; - $connectPayload = Packet::MESSAGE.Packet::CONNECT; + $initPayload = Packet::OPEN . $payload; + $connectPayload = Packet::MESSAGE . Packet::CONNECT; - App::make('swoole.server')->push($fd, $initPayload); - App::make('swoole.server')->push($fd, $connectPayload); + App::make(Server::class)->push($fd, $initPayload); + App::make(Server::class)->push($fd, $connectPayload); return true; } diff --git a/src/Websocket/Websocket.php b/src/Websocket/Websocket.php index b945d02b..2ef95179 100644 --- a/src/Websocket/Websocket.php +++ b/src/Websocket/Websocket.php @@ -7,8 +7,12 @@ use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Config; use InvalidArgumentException; +use SwooleTW\Http\Server\Facades\Server; use SwooleTW\Http\Websocket\Rooms\RoomContract; +/** + * Class Websocket + */ class Websocket { use Authenticatable; @@ -66,11 +70,18 @@ class Websocket */ protected $room; + /** + * DI Container. + * + * @var \Illuminate\Contracts\Container\Container + */ + protected $container; + /** * Websocket constructor. * - * @var RoomContract $room - * @var PipelineContract $pipeline + * @param \SwooleTW\Http\Websocket\Rooms\RoomContract $room + * @param \Illuminate\Contracts\Pipeline\Pipeline $pipeline */ public function __construct(RoomContract $room, PipelineContract $pipeline) { @@ -161,23 +172,21 @@ public function emit(string $event, $data): bool return false; } - $result = App::make('swoole.server')->task( - [ - 'action' => static::PUSH_ACTION, - 'data' => [ - 'sender' => $this->sender, - 'fds' => $fds, - 'broadcast' => $this->isBroadcast, - 'assigned' => $assigned, - 'event' => $event, - 'message' => $data, - ], - ] - ); + $result = App::make(Server::class)->task([ + 'action' => static::PUSH_ACTION, + 'data' => [ + 'sender' => $this->sender, + 'fds' => $fds, + 'broadcast' => $this->isBroadcast, + 'assigned' => $assigned, + 'event' => $event, + 'message' => $data, + ], + ]); $this->reset(); - return $result === false ? false : true; + return $result !== false; } /** @@ -250,13 +259,10 @@ public function call(string $event, $data = null) $data = $this->setRequestThroughMiddleware($data); } - return App::call( - $this->callbacks[$event], - [ - 'websocket' => $this, - $dataKey => $data, - ] - ); + return App::call($this->callbacks[$event], [ + 'websocket' => $this, + $dataKey => $data, + ]); } /** @@ -268,7 +274,7 @@ public function call(string $event, $data = null) */ public function close(int $fd = null) { - return App::make('swoole.server')->close($fd ?: $this->sender); + return App::make(Server::class)->close($fd ?: $this->sender); } /** diff --git a/tests/Coroutine/ConnectorFactoryTest.php b/tests/Coroutine/ConnectorFactoryTest.php index d47169f4..a18f9d83 100644 --- a/tests/Coroutine/ConnectorFactoryTest.php +++ b/tests/Coroutine/ConnectorFactoryTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Coroutine; - use Illuminate\Support\Str; use SwooleTW\Http\Coroutine\Connectors\ConnectorFactory; use SwooleTW\Http\Helpers\FW; diff --git a/tests/Coroutine/ContextTest.php b/tests/Coroutine/ContextTest.php index d413482e..a9ef6800 100644 --- a/tests/Coroutine/ContextTest.php +++ b/tests/Coroutine/ContextTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Coroutine; - use Illuminate\Container\Container; use Mockery as m; use SwooleTW\Http\Coroutine\Context; diff --git a/tests/HotReload/FSEventParserTest.php b/tests/HotReload/FSEventParserTest.php new file mode 100644 index 00000000..33deea92 --- /dev/null +++ b/tests/HotReload/FSEventParserTest.php @@ -0,0 +1,28 @@ +assertInstanceOf(FSEvent::class, $event); + + $this->assertTrue(array_diff($event->getTypes(), [FSEvent::Renamed, FSEvent::OwnerModified]) === []); + $this->assertTrue((new Carbon('Mon Dec 31 01:18:34 2018'))->eq($event->getWhen())); + $this->assertEquals('/Some/Path/To/File/File.php', $event->getPath()); + $this->assertTrue($event->isType(FSEvent::Renamed)); + $this->assertTrue($event->isType(FSEvent::OwnerModified)); + } +} \ No newline at end of file diff --git a/tests/HotReload/FSEventTest.php b/tests/HotReload/FSEventTest.php new file mode 100644 index 00000000..65fef901 --- /dev/null +++ b/tests/HotReload/FSEventTest.php @@ -0,0 +1,29 @@ +assertTrue(array_diff($event->getTypes(), [FSEvent::Renamed, FSEvent::OwnerModified]) === []); + $this->assertTrue((new Carbon('Mon Dec 31 01:18:34 2018'))->eq($event->getWhen())); + $this->assertEquals('/Some/Path/To/File/File.php', $event->getPath()); + $this->assertTrue($event->isType(FSEvent::Renamed)); + $this->assertTrue($event->isType(FSEvent::OwnerModified)); + } +} \ No newline at end of file diff --git a/tests/HotReload/FSOutputTest.php b/tests/HotReload/FSOutputTest.php new file mode 100644 index 00000000..f89cb4bc --- /dev/null +++ b/tests/HotReload/FSOutputTest.php @@ -0,0 +1,24 @@ +assertEquals( + 'File: /Some/Path/To/File/File.php OwnerModified, Renamed at 2018.12.31 01:18:34', + FSOutput::format($event) + ); + } +} \ No newline at end of file diff --git a/tests/HotReload/FSProcessTest.php b/tests/HotReload/FSProcessTest.php new file mode 100644 index 00000000..c4c7b858 --- /dev/null +++ b/tests/HotReload/FSProcessTest.php @@ -0,0 +1,45 @@ +assertInstanceOf(FSProcess::class, $process); + $this->assertInstanceOf(Process::class, $process->make()); + } + + public function testItCanCreateHotReloadProcessWithNeededConfiguration() + { + $process = new FSProcess('.php', true, __DIR__); + $ref = new \ReflectionClass($process); + $configure = $ref->getMethod('configure'); + $configure->setAccessible(true); + $configuration = $configure->invoke($process); + $sampleConfiguration = [ + 'fswatch', + '-rtx', + '-e', + '.*', + '-i', + "\\.php$", + __DIR__, + ]; + + $this->assertInstanceOf(FSProcess::class, $process); + $this->assertInstanceOf(Process::class, $process->make()); + $this->assertTrue( + array_diff($sampleConfiguration, $configuration) === [] + ); + } +} \ No newline at end of file diff --git a/tests/Server/ManagerTest.php b/tests/Server/ManagerTest.php index 4c9d41b8..0664c861 100644 --- a/tests/Server/ManagerTest.php +++ b/tests/Server/ManagerTest.php @@ -2,8 +2,8 @@ namespace SwooleTW\Http\Tests\Server; - use Illuminate\Container\Container; +use Illuminate\Contracts\Config\Repository; use Illuminate\Contracts\Debug\ExceptionHandler; use Illuminate\Support\Facades\Config; use Laravel\Lumen\Exceptions\Handler; @@ -11,6 +11,8 @@ use Swoole\Http\Request; use Swoole\Http\Response; use Swoole\Table; +use SwooleTW\Http\Helpers\Alias; +use SwooleTW\Http\Server\Facades\Server; use SwooleTW\Http\Server\Manager; use SwooleTW\Http\Server\Sandbox; use SwooleTW\Http\Table\SwooleTable; @@ -136,8 +138,8 @@ public function testOnWorkerStart() }); Config::shouldReceive('get') - ->with('swoole_websocket.middleware', []) - ->once(); + ->with('swoole_websocket.middleware', []) + ->once(); WebsocketFacade::shouldReceive('on')->times(3); $manager = $this->getWebsocketManager($container); @@ -145,10 +147,10 @@ public function testOnWorkerStart() $manager->onWorkerStart($server); $app = $manager->getApplication(); - $this->assertTrue($app->make('swoole.sandbox') instanceof Sandbox); + $this->assertTrue($app->make(Sandbox::class) instanceof Sandbox); $this->assertTrue($app->make('swoole.table') instanceof SwooleTable); $this->assertTrue($app->make('swoole.room') instanceof RoomContract); - $this->assertTrue($app->make('swoole.websocket') instanceof Websocket); + $this->assertTrue($app->make(Websocket::class) instanceof Websocket); } public function testLoadApplication() @@ -192,51 +194,53 @@ public function testOnRequest() $container->singleton('events', function () { return $this->getEvent('swoole.request', false); }); - $container->singleton('swoole.websocket', function () { + $container->singleton(Websocket::class, function () { $websocket = m::mock(Websocket::class); $websocket->shouldReceive('reset') - ->with(true) - ->once(); + ->with(true) + ->once(); return $websocket; }); - $container->singleton('swoole.sandbox', function () { + $container->singleton(Sandbox::class, function () { $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('setRequest') - ->with(m::type('Illuminate\Http\Request')) - ->once(); + ->with(m::type('Illuminate\Http\Request')) + ->once(); $sandbox->shouldReceive('enable') - ->once(); + ->once(); $sandbox->shouldReceive('run') - ->with(m::type('Illuminate\Http\Request')) - ->once(); + ->with(m::type('Illuminate\Http\Request')) + ->once(); $sandbox->shouldReceive('disable') - ->once(); + ->once(); return $sandbox; }); + $container->alias(Sandbox::class, 'swoole.sandbox'); + $this->mockMethod('base_path', function () { return '/'; }); $request = m::mock(Request::class); $request->shouldReceive('rawcontent') - ->once() - ->andReturn([]); + ->once() + ->andReturn([]); $response = m::mock(Response::class); $response->shouldReceive('header') - ->twice() - ->andReturnSelf(); + ->twice() + ->andReturnSelf(); $response->shouldReceive('status') - ->once() - ->andReturnSelf(); + ->once() + ->andReturnSelf(); $response->shouldReceive('write') - ->andReturnSelf(); + ->andReturnSelf(); $response->shouldReceive('end') - ->once() - ->andReturnSelf(); + ->once() + ->andReturnSelf(); $manager = $this->getWebsocketManager(); $manager->setApplication($container); @@ -250,17 +254,20 @@ public function testOnRequestException() $container->singleton('events', function () { return $this->getEvent('swoole.request', false); }); - $container->singleton('swoole.sandbox', function () { + $container->singleton(Sandbox::class, function () { $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('disable') - ->once(); + ->once(); return $sandbox; }); + + $container->alias(Sandbox::class, 'swoole.sandbox'); + $container->singleton(ExceptionHandler::class, function () { $handler = m::mock(ExceptionHandler::class); $handler->shouldReceive('render') - ->once(); + ->once(); return $handler; }); @@ -271,21 +278,21 @@ public function testOnRequestException() $request = m::mock(Request::class); $request->shouldReceive('rawcontent') - ->once() - ->andReturn([]); + ->once() + ->andReturn([]); $response = m::mock(Response::class); $response->shouldReceive('header') - ->twice() - ->andReturnSelf(); + ->twice() + ->andReturnSelf(); $response->shouldReceive('status') - ->once() - ->andReturnSelf(); + ->once() + ->andReturnSelf(); $response->shouldReceive('write') - ->andReturnSelf(); + ->andReturnSelf(); $response->shouldReceive('end') - ->once() - ->andReturnSelf(); + ->once() + ->andReturnSelf(); $manager = $this->getManager($container); $manager->setApplication($container); @@ -346,8 +353,8 @@ public function testLogServerError() $container->singleton(ExceptionHandler::class, function () use ($exception) { $handler = m::mock(ExceptionHandler::class); $handler->shouldReceive('report') - ->with($exception) - ->once(); + ->with($exception) + ->once(); return $handler; }); @@ -360,53 +367,55 @@ public function testOnOpen() { $request = m::mock(Request::class); $request->shouldReceive('rawcontent') - ->once() - ->andReturn([]); + ->once() + ->andReturn([]); $request->fd = 1; $container = $this->getContainer(); - $container->singleton('swoole.websocket', function () { + $container->singleton(Websocket::class, function () { $websocket = m::mock(Websocket::class); $websocket->shouldReceive('reset') - ->with(true) - ->once() - ->andReturnSelf(); + ->with(true) + ->once() + ->andReturnSelf(); $websocket->shouldReceive('setSender') - ->with(1) - ->once(); + ->with(1) + ->once(); $websocket->shouldReceive('eventExists') - ->with('connect') - ->once() - ->andReturn(true); + ->with('connect') + ->once() + ->andReturn(true); $websocket->shouldReceive('setContainer') - ->with(m::type(Container::class)) - ->once(); + ->with(m::type(Container::class)) + ->once(); $websocket->shouldReceive('call') - ->with('connect', m::type('Illuminate\Http\Request')) - ->once(); + ->with('connect', m::type('Illuminate\Http\Request')) + ->once(); return $websocket; }); - $container->singleton('swoole.sandbox', function () { + $container->singleton(Sandbox::class, function () { $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('setRequest') - ->with(m::type('Illuminate\Http\Request')) - ->once(); + ->with(m::type('Illuminate\Http\Request')) + ->once(); $sandbox->shouldReceive('enable') - ->once(); + ->once(); $sandbox->shouldReceive('disable') - ->once(); + ->once(); $sandbox->shouldReceive('getApplication') - ->once() - ->andReturn(m::mock(Container::class)); + ->once() + ->andReturn(m::mock(Container::class)); return $sandbox; }); + $container->alias(Sandbox::class, 'swoole.sandbox'); + $handler = m::mock(HandlerContract::class); $handler->shouldReceive('onOpen') - ->with(1, m::type('Illuminate\Http\Request')) - ->andReturn(true); + ->with(1, m::type('Illuminate\Http\Request')) + ->andReturn(true); $manager = $this->getWebsocketManager(); $manager->setApplication($container); @@ -421,47 +430,49 @@ public function testOnMessage() $parser = m::mock(Parser::class); $parser->shouldReceive('execute') - ->with('server', $frame) - ->once() - ->andReturn(false); + ->with('server', $frame) + ->once() + ->andReturn(false); $parser->shouldReceive('decode') - ->with($frame) - ->once() - ->andReturn($payload = [ - 'event' => 'event', - 'data' => 'data', - ]); + ->with($frame) + ->once() + ->andReturn($payload = [ + 'event' => 'event', + 'data' => 'data', + ]); $container = $this->getContainer(); - $container->singleton('swoole.websocket', function () use ($payload) { + $container->singleton(Websocket::class, function () use ($payload) { $websocket = m::mock(Websocket::class); $websocket->shouldReceive('reset') - ->with(true) - ->once() - ->andReturnSelf(); + ->with(true) + ->once() + ->andReturnSelf(); $websocket->shouldReceive('setSender') - ->with(1) - ->once(); + ->with(1) + ->once(); $websocket->shouldReceive('eventExists') - ->with($payload['event']) - ->once() - ->andReturn(true); + ->with($payload['event']) + ->once() + ->andReturn(true); $websocket->shouldReceive('call') - ->with($payload['event'], $payload['data']) - ->once(); + ->with($payload['event'], $payload['data']) + ->once(); return $websocket; }); - $container->singleton('swoole.sandbox', function () { + $container->singleton(Sandbox::class, function () { $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('enable') - ->once(); + ->once(); $sandbox->shouldReceive('disable') - ->once(); + ->once(); return $sandbox; }); + $container->alias(Sandbox::class, 'swoole.sandbox'); + $manager = $this->getWebsocketManager(); $manager->setApplication($container); $manager->setPayloadParser($parser); @@ -472,24 +483,24 @@ public function testOnClose() { $fd = 1; $app = $this->getContainer(); - $app->singleton('swoole.websocket', function () use ($fd) { + $app->singleton(Websocket::class, function () use ($fd) { $websocket = m::mock(Websocket::class); $websocket->shouldReceive('reset') - ->with(true) - ->once() - ->andReturnSelf(); + ->with(true) + ->once() + ->andReturnSelf(); $websocket->shouldReceive('setSender') - ->with($fd) - ->once(); + ->with($fd) + ->once(); $websocket->shouldReceive('eventExists') - ->with('disconnect') - ->once() - ->andReturn(true); + ->with('disconnect') + ->once() + ->andReturn(true); $websocket->shouldReceive('call') - ->with('disconnect') - ->once(); + ->with('disconnect') + ->once(); $websocket->shouldReceive('leave') - ->once(); + ->once(); return $websocket; }); @@ -498,21 +509,23 @@ public function testOnClose() $server->shouldReceive('on'); $container = $this->getContainer($server); - $container->singleton('swoole.server', function () use ($fd) { + $container->singleton(Server::class, function () use ($fd) { $server = m::mock('server'); $server->shouldReceive('on'); $server->taskworker = false; $server->master_pid = -1; $server->shouldReceive('connection_info') - ->with($fd) - ->once() - ->andReturn([ - 'websocket_status' => true, - ]); + ->with($fd) + ->once() + ->andReturn([ + 'websocket_status' => true, + ]); return $server; }); + $container->alias(Server::class, Alias::SERVER); + $manager = $this->getWebsocketManager($container); $manager->setApplication($app); $manager->onClose('server', $fd, 'reactorId'); @@ -552,16 +565,16 @@ public function testPushMessage() $parser = m::mock(Parser::class); $parser->shouldReceive('encode') - ->with($data['event'], $data['message']) - ->once() - ->andReturn(false); + ->with($data['event'], $data['message']) + ->once() + ->andReturn(false); $server = m::mock('server'); $server->shouldReceive('exist') - ->times(count($data['fds'])) - ->andReturn(true); + ->times(count($data['fds'])) + ->andReturn(true); $server->shouldReceive('push') - ->times(count($data['fds'])); + ->times(count($data['fds'])); $manager = $this->getWebsocketManager(); $manager->setPayloadParser($parser); @@ -584,12 +597,15 @@ protected function getContainer($server = null, $config = null) $config = $config ?? $this->getConfig(); $container = new Container; - $container->singleton('config', function () use ($config) { + $container->singleton(Repository::class, function () use ($config) { return $config; }); - $container->singleton('swoole.server', function () use ($server) { + $container->alias(Repository::class, Alias::CONFIG); + + $container->singleton(Server::class, function () use ($server) { return $server; }); + $container->alias(Server::class, Alias::SERVER); $container->singleton(ExceptionHandler::class, Handler::class); return $container; @@ -607,18 +623,18 @@ protected function getServer() protected function getConfig($websocket = false) { - $config = m::mock('config'); + $config = m::mock(Repository::class); $settings = $websocket ? 'websocketConfig' : 'config'; $callback = function ($key) use ($settings) { return $this->$settings[$key] ?? ''; }; $config->shouldReceive('get') - ->with(m::type('string'), m::any()) - ->andReturnUsing($callback); + ->with(m::type('string'), m::any()) + ->andReturnUsing($callback); $config->shouldReceive('get') - ->with(m::type('string')) - ->andReturnUsing($callback); + ->with(m::type('string')) + ->andReturnUsing($callback); return $config; } @@ -626,9 +642,9 @@ protected function getConfig($websocket = false) protected function getEvent($name, $default = true) { $event = m::mock('event') - ->shouldReceive('fire') - ->with($name, m::any()) - ->once(); + ->shouldReceive('fire') + ->with($name, m::any()) + ->once(); $event = $default ? $event->with($name, m::any()) : $event->with($name); diff --git a/tests/Server/ResettersTest.php b/tests/Server/ResettersTest.php index d2675fcb..e5ef0bcb 100644 --- a/tests/Server/ResettersTest.php +++ b/tests/Server/ResettersTest.php @@ -2,12 +2,13 @@ namespace SwooleTW\Http\Tests\Server; - use Illuminate\Container\Container; +use Illuminate\Contracts\Config\Repository; use Illuminate\Contracts\Http\Kernel; use Illuminate\Http\Request; use Illuminate\Support\ServiceProvider; use Mockery as m; +use SwooleTW\Http\Helpers\Alias; use SwooleTW\Http\Server\Resetters\BindRequest; use SwooleTW\Http\Server\Resetters\ClearInstances; use SwooleTW\Http\Server\Resetters\RebindKernelContainer; @@ -28,8 +29,8 @@ public function testBindRequest() $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('getRequest') - ->once() - ->andReturn($request); + ->once() + ->andReturn($request); $container = new Container; @@ -43,9 +44,9 @@ public function testClearInstance() { $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('getConfig->get') - ->with('swoole_http.instances', []) - ->once() - ->andReturn(['foo']); + ->with('swoole_http.instances', []) + ->once() + ->andReturn(['foo']); $container = new Container; $container->instance('foo', m::mock('foo')); @@ -60,8 +61,8 @@ public function testRebindKernelContainer() { $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('isLaravel') - ->once() - ->andReturn(true); + ->once() + ->andReturn(true); $kernel = m::mock(Kernel::class); @@ -80,11 +81,11 @@ public function testRebindLaravelRouterContainer() $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('isLaravel') - ->once() - ->andReturn(true); + ->once() + ->andReturn(true); $sandbox->shouldReceive('getRequest') - ->once() - ->andReturn($request); + ->once() + ->andReturn($request); $router = m::mock('router'); @@ -94,14 +95,14 @@ public function testRebindLaravelRouterContainer() $route = m::mock('route'); $route->controller = 'controller'; $route->shouldReceive('setContainer') - ->once() - ->with($container); + ->once() + ->with($container); $routes = m::mock('routes'); $routes->shouldReceive('match') - ->once() - ->with($request) - ->andReturn($route); + ->once() + ->with($request) + ->andReturn($route); $router->routes = $routes; @@ -115,19 +116,19 @@ public function testRebindLumenRouterContainer() { $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('isLaravel') - ->once() - ->andReturn(false); + ->once() + ->andReturn(false); $router = m::mock('router'); $container = m::mock(Container::class); $container->shouldReceive('offsetSet') - ->with('router', $router) - ->once() - ->andReturnSelf(); + ->with('router', $router) + ->once() + ->andReturnSelf(); $container->shouldReceive('offsetGet') - ->with('router') - ->andReturn($router); + ->with('router') + ->andReturn($router); $container->router = $router; $this->mockMethod('property_exists', function () { @@ -157,28 +158,28 @@ public function testRebindViewContainer() public function testResetConfig() { - $config = m::mock('config'); + $config = m::mock(Repository::class); $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('getConfig') - ->once() - ->andReturn($config); + ->once() + ->andReturn($config); $container = new Container; $resetter = new ResetConfig; $app = $resetter->handle($container, $sandbox); - $this->assertSame(get_class($config), get_class($app->make('config'))); + $this->assertSame(get_class($config), get_class($app->make(Alias::CONFIG))); } public function testResetCookie() { $cookies = m::mock('cookies'); $cookies->shouldReceive('getQueuedCookies') - ->once() - ->andReturn(['foo']); + ->once() + ->andReturn(['foo']); $cookies->shouldReceive('unqueue') - ->once() - ->with('foo'); + ->once() + ->with('foo'); $sandbox = m::mock(Sandbox::class); @@ -193,9 +194,9 @@ public function testResetSession() { $session = m::mock('session'); $session->shouldReceive('flush') - ->once(); + ->once(); $session->shouldReceive('regenerate') - ->once(); + ->once(); $sandbox = m::mock(Sandbox::class); @@ -210,14 +211,14 @@ public function testResetProviders() { $provider = m::mock(TestProvider::class); $provider->shouldReceive('register') - ->once(); + ->once(); $provider->shouldReceive('boot') - ->once(); + ->once(); $sandbox = m::mock(Sandbox::class); $sandbox->shouldReceive('getProviders') - ->once() - ->andReturn([$provider]); + ->once() + ->andReturn([$provider]); $this->mockMethod('method_exists', function () { return true; diff --git a/tests/Server/SandboxTest.php b/tests/Server/SandboxTest.php index ee4e02cf..876d3bc9 100644 --- a/tests/Server/SandboxTest.php +++ b/tests/Server/SandboxTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Server; - use Illuminate\Config\Repository; use Illuminate\Container\Container; use Illuminate\Contracts\Container\Container as ContainerContract; @@ -53,23 +52,23 @@ public function testInitialize() $config = m::mock(Repository::class); $config->shouldReceive('get') - ->with('swoole_http.providers', []) - ->once() - ->andReturn([$providerName]); + ->with('swoole_http.providers', []) + ->once() + ->andReturn([$providerName]); $config->shouldReceive('get') - ->with('swoole_http.resetters', []) - ->once() - ->andReturn([$resetterName]); + ->with('swoole_http.resetters', []) + ->once() + ->andReturn([$resetterName]); $container = m::mock(Container::class); $container->shouldReceive('make') - ->with('config') - ->once() - ->andReturn($config); + ->with(\Illuminate\Contracts\Config\Repository::class) + ->once() + ->andReturn($config); $container->shouldReceive('make') - ->with($resetterName) - ->once() - ->andReturn($resetter); + ->with($resetterName) + ->once() + ->andReturn($resetter); $sandbox = new Sandbox; $sandbox->setBaseApp($container); @@ -101,9 +100,9 @@ public function testGetCachedSnapshot() $container = m::mock(Container::class); $snapshot = m::mock(Container::class); $snapshot->shouldReceive('offsetGet') - ->with('foo') - ->once() - ->andReturn($result = 'bar'); + ->with('foo') + ->once() + ->andReturn($result = 'bar'); $sandbox = new Sandbox; $sandbox->setBaseApp($container); @@ -154,12 +153,12 @@ protected function getContainer() { $config = m::mock(Illuminate\Config\Repository::class); $config->shouldReceive('get') - ->andReturn([]); + ->andReturn([]); $container = m::mock(Container::class); $container->shouldReceive('offsetGet') - ->andReturn((object)[]); + ->andReturn((object) []); $container->shouldReceive('make') - ->andReturn($config); + ->andReturn($config); return $container; } diff --git a/tests/SocketIO/PacketTest.php b/tests/SocketIO/PacketTest.php index e2b7b20d..b46b1013 100644 --- a/tests/SocketIO/PacketTest.php +++ b/tests/SocketIO/PacketTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\SocketIO; - use SwooleTW\Http\Tests\TestCase; use SwooleTW\Http\Websocket\SocketIO\Packet; diff --git a/tests/SocketIO/ParserTest.php b/tests/SocketIO/ParserTest.php index 346a829c..9b952a99 100644 --- a/tests/SocketIO/ParserTest.php +++ b/tests/SocketIO/ParserTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\SocketIO; - use Illuminate\Support\Facades\App; use Mockery as m; use Swoole\Websocket\Frame; @@ -25,7 +24,7 @@ public function testEncode() $data = ['message' => 'test']; $this->assertSame('42["foo",{"message":"test"}]', $parser->encode($event, $data)); - $data = (object)['message' => 'test']; + $data = (object) ['message' => 'test']; $this->assertSame('42["foo",{"message":"test"}]', $parser->encode($event, $data)); } diff --git a/tests/SocketIO/SocketIOControllerTest.php b/tests/SocketIO/SocketIOControllerTest.php index d9a9f78d..e445e3db 100644 --- a/tests/SocketIO/SocketIOControllerTest.php +++ b/tests/SocketIO/SocketIOControllerTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\SocketIO; - use Illuminate\Http\Request; use Illuminate\Support\Facades\Config; use Mockery as m; @@ -15,18 +14,18 @@ public function testUnknownTransport() { $request = m::mock(Request::class); $request->shouldReceive('input') - ->with('transport') - ->once() - ->andReturn('foo'); + ->with('transport') + ->once() + ->andReturn('foo'); $this->mockMethod('response', function () { $response = m::mock('response'); $response->shouldReceive('json') - ->once() - ->with([ - 'code' => 0, - 'message' => 'Transport unknown', - ], 400); + ->once() + ->with([ + 'code' => 0, + 'message' => 'Transport unknown', + ], 400); return $response; }); @@ -39,13 +38,13 @@ public function testHasSid() { $request = m::mock(Request::class); $request->shouldReceive('input') - ->with('transport') - ->once() - ->andReturn('websocket'); + ->with('transport') + ->once() + ->andReturn('websocket'); $request->shouldReceive('has') - ->with('sid') - ->once() - ->andReturn(true); + ->with('sid') + ->once() + ->andReturn(true); $controller = new SocketIOController; $result = $controller->upgrade($request); @@ -57,13 +56,13 @@ public function testUpgradePayload() { $request = m::mock(Request::class); $request->shouldReceive('input') - ->with('transport') - ->once() - ->andReturn('websocket'); + ->with('transport') + ->once() + ->andReturn('websocket'); $request->shouldReceive('has') - ->with('sid') - ->once() - ->andReturn(false); + ->with('sid') + ->once() + ->andReturn(false); $base64Encode = false; $this->mockMethod('base64_encode', function () use (&$base64Encode) { @@ -73,13 +72,13 @@ public function testUpgradePayload() }); Config::shouldReceive('get') - ->with('swoole_websocket.ping_interval') - ->once() - ->andReturn(1); + ->with('swoole_websocket.ping_interval') + ->once() + ->andReturn(1); Config::shouldReceive('get') - ->with('swoole_websocket.ping_timeout') - ->once() - ->andReturn(1); + ->with('swoole_websocket.ping_timeout') + ->once() + ->andReturn(1); $expectedPayload = json_encode([ 'sid' => 'payload', @@ -101,11 +100,11 @@ public function testReject() $this->mockMethod('response', function () { $response = m::mock('response'); $response->shouldReceive('json') - ->once() - ->with([ - 'code' => 3, - 'message' => 'Bad request', - ], 400); + ->once() + ->with([ + 'code' => 3, + 'message' => 'Bad request', + ], 400); return $response; }); diff --git a/tests/SocketIO/WebsocketHandlerTest.php b/tests/SocketIO/WebsocketHandlerTest.php index 7cd011f8..6db1e612 100644 --- a/tests/SocketIO/WebsocketHandlerTest.php +++ b/tests/SocketIO/WebsocketHandlerTest.php @@ -2,12 +2,12 @@ namespace SwooleTW\Http\Tests\SocketIO; - use Illuminate\Http\Request; use Illuminate\Support\Facades\App; use Illuminate\Support\Facades\Config; use Mockery as m; use Swoole\Websocket\Frame; +use SwooleTW\Http\Server\Facades\Server; use SwooleTW\Http\Tests\TestCase; use SwooleTW\Http\Websocket\SocketIO\WebsocketHandler; @@ -18,16 +18,16 @@ public function testOnOpen() $fd = 1; $request = m::mock(Request::class); $request->shouldReceive('input') - ->with('sid') - ->once() - ->andReturn(false); + ->with('sid') + ->once() + ->andReturn(false); Config::shouldReceive('get') - ->with('swoole_websocket.ping_interval') - ->once(); + ->with('swoole_websocket.ping_interval') + ->once(); Config::shouldReceive('get') - ->with('swoole_websocket.ping_timeout') - ->once(); + ->with('swoole_websocket.ping_timeout') + ->once(); $jsonEncode = false; $this->mockMethod('json_encode', function () use (&$jsonEncode) { @@ -37,15 +37,15 @@ public function testOnOpen() }, 'SwooleTW\Http\Websocket\SocketIO'); App::shouldReceive('make') - ->with('swoole.server') - ->twice() - ->andReturnSelf(); + ->with(Server::class) + ->twice() + ->andReturnSelf(); App::shouldReceive('push') - ->with($fd, '0{foo: "bar"}') - ->once(); + ->with($fd, '0{foo: "bar"}') + ->once(); App::shouldReceive('push') - ->with($fd, '40') - ->once(); + ->with($fd, '40') + ->once(); $handler = new WebsocketHandler; $this->assertTrue($handler->onOpen($fd, $request)); @@ -57,9 +57,9 @@ public function testOnOpenWithFalseReturn() $fd = 1; $request = m::mock(Request::class); $request->shouldReceive('input') - ->with('sid') - ->once() - ->andReturn(true); + ->with('sid') + ->once() + ->andReturn(true); $handler = new WebsocketHandler; $this->assertFalse($handler->onOpen($fd, $request)); diff --git a/tests/Table/TableTest.php b/tests/Table/TableTest.php index 7e35a6e4..fa32dbed 100644 --- a/tests/Table/TableTest.php +++ b/tests/Table/TableTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Table; - use Mockery as m; use Swoole\Table; use SwooleTW\Http\Table\SwooleTable; diff --git a/tests/Task/FakeJob.php b/tests/Task/FakeJob.php index 37f953b9..272b658b 100644 --- a/tests/Task/FakeJob.php +++ b/tests/Task/FakeJob.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Task; - use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Queue\InteractsWithQueue; diff --git a/tests/Task/QueueFactoryTest.php b/tests/Task/QueueFactoryTest.php index 4afc0e51..0f27937e 100644 --- a/tests/Task/QueueFactoryTest.php +++ b/tests/Task/QueueFactoryTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Task; - use Illuminate\Support\Str; use Mockery as m; use SwooleTW\Http\Helpers\FW; diff --git a/tests/Task/SwooleJobTest.php b/tests/Task/SwooleJobTest.php index 98fc5c23..2f2ffaca 100644 --- a/tests/Task/SwooleJobTest.php +++ b/tests/Task/SwooleJobTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Task; - use Illuminate\Container\Container; use Mockery as m; use SwooleTW\Http\Task\SwooleTaskJob; diff --git a/tests/Task/SwooleQueueTest.php b/tests/Task/SwooleQueueTest.php index bb3fcf23..cbff7344 100644 --- a/tests/Task/SwooleQueueTest.php +++ b/tests/Task/SwooleQueueTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Task; - use Mockery as m; use SwooleTW\Http\Helpers\FW; use SwooleTW\Http\Task\QueueFactory; diff --git a/tests/TestCase.php b/tests/TestCase.php index 0965d984..1e666707 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests; - use Illuminate\Support\Facades\Facade; use Mockery as m; use phpmock\Mock; @@ -27,10 +26,10 @@ public function tearDown() protected function mockMethod($name, \Closure $function, $namespace = null) { - $builder = new MockBuilder(); + $builder = new MockBuilder; $builder->setNamespace($namespace) - ->setName($name) - ->setFunction($function); + ->setName($name) + ->setFunction($function); $mock = $builder->build(); $mock->enable(); diff --git a/tests/Transformers/RequestTest.php b/tests/Transformers/RequestTest.php index d68555d1..2eecd190 100644 --- a/tests/Transformers/RequestTest.php +++ b/tests/Transformers/RequestTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Transformers; - use Illuminate\Http\Request as IlluminateRequest; use Mockery as m; use Swoole\Http\Request as SwooleRequest; @@ -48,14 +47,14 @@ public function testHandleStatic() $response = m::mock('response'); $response->shouldReceive('status') - ->with(200) - ->once(); + ->with(200) + ->once(); $response->shouldReceive('header') - ->with('Content-Type', 'foo') - ->once(); + ->with('Content-Type', 'foo') + ->once(); $response->shouldReceive('sendfile') - ->with('/foo.bar') - ->once(); + ->with('/foo.bar') + ->once(); Request::handleStatic(new SwooleRequestStub, $response, '/'); @@ -69,7 +68,7 @@ public function testHandleStaticWithBlackList() $request->server['request_uri'] = 'foo.php'; $result = Request::handleStatic($request, null, '/'); - $this->assertNull($result); + $this->assertFalse($result); } public function testHandleStaticWithNoneFile() @@ -82,7 +81,7 @@ public function testHandleStaticWithNoneFile() }); $result = Request::handleStatic(new SwooleRequestStub, null, '/'); - $this->assertNull($result); + $this->assertFalse($result); $this->assertTrue($isFile); } diff --git a/tests/Transformers/ResponseTest.php b/tests/Transformers/ResponseTest.php index 3a2c268d..41df5999 100644 --- a/tests/Transformers/ResponseTest.php +++ b/tests/Transformers/ResponseTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Transformers; - use Illuminate\Http\Response as IlluminateResponse; use Swoole\Http\Response as SwooleResponse; use SwooleTW\Http\Tests\TestCase; diff --git a/tests/Websocket/Middleware/AuthenticateTest.php b/tests/Websocket/Middleware/AuthenticateTest.php index 7f24acd1..fcd5b4f9 100644 --- a/tests/Websocket/Middleware/AuthenticateTest.php +++ b/tests/Websocket/Middleware/AuthenticateTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Websocket\Middleware; - use Illuminate\Contracts\Auth\Factory as Auth; use Illuminate\Http\Request; use Mockery as m; @@ -15,12 +14,12 @@ public function testAuthenticate() { $auth = m::mock(Auth::class); $auth->shouldReceive('authenticate') - ->once() - ->andReturn('user'); + ->once() + ->andReturn('user'); $request = m::mock(Request::class); $request->shouldReceive('setUserResolver') - ->once(); + ->once(); $middleware = new Authenticate($auth); $middleware->handle($request, function ($next) { diff --git a/tests/Websocket/Middleware/DecrpytCookiesTest.php b/tests/Websocket/Middleware/DecrpytCookiesTest.php index 586f171e..8c0347b0 100644 --- a/tests/Websocket/Middleware/DecrpytCookiesTest.php +++ b/tests/Websocket/Middleware/DecrpytCookiesTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Websocket\Middleware; - use Illuminate\Contracts\Encryption\Encrypter as EncrypterContract; use Illuminate\Http\Request; use Mockery as m; @@ -34,11 +33,11 @@ public function testDecrypt() $encrypter = m::mock(EncrypterContract::class); $encrypter->shouldReceive('decrypt') - ->once() - ->with('sasaya', false); + ->once() + ->with('sasaya', false); $encrypter->shouldReceive('decrypt') - ->once() - ->with('ccc', false); + ->once() + ->with('ccc', false); $middleware = $this->getMiddleware($encrypter); $middleware->disableFor('foo'); diff --git a/tests/Websocket/Middleware/StartSessionTest.php b/tests/Websocket/Middleware/StartSessionTest.php index b9d75c64..0ab4c8e4 100644 --- a/tests/Websocket/Middleware/StartSessionTest.php +++ b/tests/Websocket/Middleware/StartSessionTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Websocket\Middleware; - use SwooleTW\Http\Tests\TestCase; class StartSessionTest extends TestCase diff --git a/tests/Websocket/RedisRoomTest.php b/tests/Websocket/RedisRoomTest.php index ce2b3634..eeda14c2 100644 --- a/tests/Websocket/RedisRoomTest.php +++ b/tests/Websocket/RedisRoomTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Websocket; - use Mockery as m; use Predis\Client as RedisClient; use SwooleTW\Http\Tests\TestCase; @@ -14,11 +13,11 @@ public function testPrepare() { $redis = $this->getRedis(); $redis->shouldReceive('keys') - ->once() - ->andReturn($keys = ['foo', 'bar']); + ->once() + ->andReturn($keys = ['foo', 'bar']); $redis->shouldReceive('del') - ->with($keys) - ->once(); + ->with($keys) + ->once(); $redisRoom = new RedisRoom([]); $redisRoom->prepare($redis); @@ -39,7 +38,7 @@ public function testAddValue() { $redis = $this->getRedis(); $redis->shouldReceive('pipeline') - ->once(); + ->once(); $redisRoom = $this->getRedisRoom($redis); $redisRoom->addValue(1, ['foo', 'bar'], 'fds'); @@ -49,7 +48,7 @@ public function testAddAll() { $redis = $this->getRedis(); $redis->shouldReceive('pipeline') - ->times(3); + ->times(3); $redisRoom = $this->getRedisRoom($redis); $redisRoom->add(1, ['foo', 'bar']); @@ -59,7 +58,7 @@ public function testAdd() { $redis = $this->getRedis(); $redis->shouldReceive('pipeline') - ->twice(); + ->twice(); $redisRoom = $this->getRedisRoom($redis); $redisRoom->add(1, 'foo'); @@ -69,7 +68,7 @@ public function testDeleteAll() { $redis = $this->getRedis(); $redis->shouldReceive('pipeline') - ->times(3); + ->times(3); $redisRoom = $this->getRedisRoom($redis); $redisRoom->delete(1, ['foo', 'bar']); @@ -79,7 +78,7 @@ public function testDelete() { $redis = $this->getRedis(); $redis->shouldReceive('pipeline') - ->twice(); + ->twice(); $redisRoom = $this->getRedisRoom($redis); $redisRoom->delete(1, 'foo'); @@ -89,8 +88,8 @@ public function testGetRooms() { $redis = $this->getRedis(); $redis->shouldReceive('smembers') - ->with('swoole:fds:1') - ->once(); + ->with('swoole:fds:1') + ->once(); $redisRoom = $this->getRedisRoom($redis); $redisRoom->getRooms(1); @@ -100,8 +99,8 @@ public function testGetClients() { $redis = $this->getRedis(); $redis->shouldReceive('smembers') - ->with('swoole:rooms:foo') - ->once(); + ->with('swoole:rooms:foo') + ->once(); $redisRoom = $this->getRedisRoom($redis); $redisRoom->getClients('foo'); diff --git a/tests/Websocket/SimpleParserTest.php b/tests/Websocket/SimpleParserTest.php index 214b3a26..f55f28e1 100644 --- a/tests/Websocket/SimpleParserTest.php +++ b/tests/Websocket/SimpleParserTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Websocket; - use Mockery as m; use Swoole\Websocket\Frame; use SwooleTW\Http\Tests\TestCase; diff --git a/tests/Websocket/TableRoomTest.php b/tests/Websocket/TableRoomTest.php index b2df7d3a..26a6813b 100644 --- a/tests/Websocket/TableRoomTest.php +++ b/tests/Websocket/TableRoomTest.php @@ -2,9 +2,9 @@ namespace SwooleTW\Http\Tests\Websocket; - use Swoole\Table; use SwooleTW\Http\Tests\TestCase; +use SwooleTW\Http\Websocket\Rooms\RoomContract; use SwooleTW\Http\Websocket\Rooms\TableRoom; class TableRoomTest extends TestCase @@ -48,7 +48,7 @@ public function testInvalidTableName() public function testSetValue() { - $this->tableRoom->setValue($key = 1, $value = ['foo', 'bar'], $table = 'fds'); + $this->tableRoom->setValue($key = 1, $value = ['foo', 'bar'], $table = RoomContract::DESCRIPTORS_KEY); $this->assertSame($value, $this->tableRoom->getValue($key, $table)); } @@ -57,17 +57,17 @@ public function testAddAll() { $this->tableRoom->add($key = 1, $values = ['foo', 'bar']); - $this->assertSame($values, $this->tableRoom->getValue($key, $table = 'fds')); - $this->assertSame([$key], $this->tableRoom->getValue('foo', 'rooms')); - $this->assertSame([$key], $this->tableRoom->getValue('bar', 'rooms')); + $this->assertSame($values, $this->tableRoom->getValue($key, $table = RoomContract::DESCRIPTORS_KEY)); + $this->assertSame([$key], $this->tableRoom->getValue('foo', RoomContract::ROOMS_KEY)); + $this->assertSame([$key], $this->tableRoom->getValue('bar', RoomContract::ROOMS_KEY)); } public function testAdd() { $this->tableRoom->add($key = 1, $value = 'foo'); - $this->assertSame([$value], $this->tableRoom->getValue($key, $table = 'fds')); - $this->assertSame([$key], $this->tableRoom->getValue($value, 'rooms')); + $this->assertSame([$value], $this->tableRoom->getValue($key, $table = RoomContract::DESCRIPTORS_KEY)); + $this->assertSame([$key], $this->tableRoom->getValue($value, RoomContract::ROOMS_KEY)); } public function testDeleteAll() @@ -75,9 +75,9 @@ public function testDeleteAll() $this->tableRoom->add($key = 1, $values = ['foo', 'bar']); $this->tableRoom->delete($key); - $this->assertSame([], $this->tableRoom->getValue($key, $table = 'fds')); - $this->assertSame([], $this->tableRoom->getValue('foo', 'rooms')); - $this->assertSame([], $this->tableRoom->getValue('bar', 'rooms')); + $this->assertSame([], $this->tableRoom->getValue($key, $table = RoomContract::DESCRIPTORS_KEY)); + $this->assertSame([], $this->tableRoom->getValue('foo', RoomContract::ROOMS_KEY)); + $this->assertSame([], $this->tableRoom->getValue('bar', RoomContract::ROOMS_KEY)); } public function testDelete() @@ -85,9 +85,9 @@ public function testDelete() $this->tableRoom->add($key = 1, $values = ['foo', 'bar']); $this->tableRoom->delete($key, 'foo'); - $this->assertSame(['bar'], $this->tableRoom->getValue($key, $table = 'fds')); - $this->assertSame([], $this->tableRoom->getValue('foo', 'rooms')); - $this->assertSame([$key], $this->tableRoom->getValue('bar', 'rooms')); + $this->assertSame(['bar'], $this->tableRoom->getValue($key, $table = RoomContract::DESCRIPTORS_KEY)); + $this->assertSame([], $this->tableRoom->getValue('foo', RoomContract::ROOMS_KEY)); + $this->assertSame([$key], $this->tableRoom->getValue('bar', RoomContract::ROOMS_KEY)); } public function testGetRooms() @@ -95,7 +95,7 @@ public function testGetRooms() $this->tableRoom->add($key = 1, $values = ['foo', 'bar']); $this->assertSame( - $this->tableRoom->getValue($key, $table = 'fds'), + $this->tableRoom->getValue($key, $table = RoomContract::DESCRIPTORS_KEY), $this->tableRoom->getRooms($key) ); } @@ -107,7 +107,7 @@ public function testGetClients() $this->tableRoom->add($keys[1], $room); $this->assertSame( - $this->tableRoom->getValue($room, $table = 'rooms'), + $this->tableRoom->getValue($room, $table = RoomContract::ROOMS_KEY), $this->tableRoom->getClients($room) ); } diff --git a/tests/Websocket/WebsocketTest.php b/tests/Websocket/WebsocketTest.php index 5341b124..1bb95688 100644 --- a/tests/Websocket/WebsocketTest.php +++ b/tests/Websocket/WebsocketTest.php @@ -2,7 +2,6 @@ namespace SwooleTW\Http\Tests\Websocket; - use Illuminate\Container\Container; use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract; use Illuminate\Http\Request; @@ -11,6 +10,7 @@ use Illuminate\Support\Facades\Config; use InvalidArgumentException; use Mockery as m; +use SwooleTW\Http\Server\Facades\Server; use SwooleTW\Http\Tests\TestCase; use SwooleTW\Http\Websocket\Rooms\RoomContract; use SwooleTW\Http\Websocket\Websocket; @@ -45,60 +45,60 @@ public function testJoin() { $room = m::mock(RoomContract::class); $room->shouldReceive('add') - ->with($sender = 1, $name = ['room']) - ->once(); + ->with($sender = 1, $name = ['room']) + ->once(); $websocket = $this->getWebsocket($room) - ->setSender($sender) - ->join($name); + ->setSender($sender) + ->join($name); } public function testInAlias() { $room = m::mock(RoomContract::class); $room->shouldReceive('add') - ->with($sender = 1, $name = ['room']) - ->once(); + ->with($sender = 1, $name = ['room']) + ->once(); $websocket = $this->getWebsocket($room) - ->setSender($sender) - ->in($name); + ->setSender($sender) + ->in($name); } public function testJoinAll() { $room = m::mock(RoomContract::class); $room->shouldReceive('add') - ->with($sender = 1, $names = ['room1', 'room2']) - ->once(); + ->with($sender = 1, $names = ['room1', 'room2']) + ->once(); $websocket = $this->getWebsocket($room) - ->setSender($sender) - ->join($names); + ->setSender($sender) + ->join($names); } public function testLeave() { $room = m::mock(RoomContract::class); $room->shouldReceive('delete') - ->with($sender = 1, $name = ['room']) - ->once(); + ->with($sender = 1, $name = ['room']) + ->once(); $websocket = $this->getWebsocket($room) - ->setSender($sender) - ->leave($name); + ->setSender($sender) + ->leave($name); } public function testLeaveAll() { $room = m::mock(RoomContract::class); $room->shouldReceive('delete') - ->with($sender = 1, $names = ['room1', 'room2']) - ->once(); + ->with($sender = 1, $names = ['room1', 'room2']) + ->once(); $websocket = $this->getWebsocket($room) - ->setSender($sender) - ->leave($names); + ->setSender($sender) + ->leave($names); } public function testCallbacks() @@ -120,50 +120,50 @@ public function testLoginUsing() { $user = m::mock(AuthenticatableContract::class); $user->shouldReceive('getAuthIdentifier') - ->once() - ->andReturn($id = 1); + ->once() + ->andReturn($id = 1); $room = m::mock(RoomContract::class); $room->shouldReceive('add') - ->with($sender = 1, ['uid_1']) - ->once(); + ->with($sender = 1, ['uid_1']) + ->once(); $websocket = $this->getWebsocket($room) - ->setSender($sender) - ->loginUsing($user); + ->setSender($sender) + ->loginUsing($user); } public function testLoginUsingId() { $room = m::mock(RoomContract::class); $room->shouldReceive('add') - ->with($sender = 1, ['uid_1']) - ->once(); + ->with($sender = 1, ['uid_1']) + ->once(); $websocket = $this->getWebsocket($room) - ->setSender($sender) - ->loginUsingId(1); + ->setSender($sender) + ->loginUsingId(1); } public function testToUserId() { $room = m::mock(RoomContract::class); $room->shouldReceive('getClients') - ->with('uid_1') - ->once() - ->andReturn([$uid = 1]); + ->with('uid_1') + ->once() + ->andReturn([$uid = 1]); $websocket = $this->getWebsocket($room)->toUserId($uid); $this->assertTrue(in_array($uid, $websocket->getTo())); $room->shouldReceive('getClients') - ->with('uid_2') - ->once() - ->andReturn([2]); + ->with('uid_2') + ->once() + ->andReturn([2]); $room->shouldReceive('getClients') - ->with('uid_3') - ->once() - ->andReturn([3]); + ->with('uid_3') + ->once() + ->andReturn([3]); $websocket->toUserId([2, 3]); $this->assertTrue(in_array(2, $websocket->getTo())); @@ -174,35 +174,35 @@ public function testToUser() { $user = m::mock(AuthenticatableContract::class); $user->shouldReceive('getAuthIdentifier') - ->once() - ->andReturn($uid = 1); + ->once() + ->andReturn($uid = 1); $room = m::mock(RoomContract::class); $room->shouldReceive('getClients') - ->with('uid_1') - ->once() - ->andReturn([$uid]); + ->with('uid_1') + ->once() + ->andReturn([$uid]); $websocket = $this->getWebsocket($room)->toUser($user); $this->assertTrue(in_array($uid, $websocket->getTo())); $room->shouldReceive('getClients') - ->with('uid_2') - ->once() - ->andReturn([2]); + ->with('uid_2') + ->once() + ->andReturn([2]); $room->shouldReceive('getClients') - ->with('uid_3') - ->once() - ->andReturn([3]); + ->with('uid_3') + ->once() + ->andReturn([3]); $userA = m::mock(AuthenticatableContract::class); $userA->shouldReceive('getAuthIdentifier') - ->once() - ->andReturn(2); + ->once() + ->andReturn(2); $userB = m::mock(AuthenticatableContract::class); $userB->shouldReceive('getAuthIdentifier') - ->once() - ->andReturn(3); + ->once() + ->andReturn(3); $websocket->toUser($users = [$userA, $userB]); $this->assertTrue(in_array(2, $websocket->getTo())); @@ -213,9 +213,9 @@ public function testGetUserId() { $room = m::mock(RoomContract::class); $room->shouldReceive('getRooms') - ->with($sender = 1) - ->once() - ->andReturn(['uid_1']); + ->with($sender = 1) + ->once() + ->andReturn(['uid_1']); $websocket = $this->getWebsocket($room)->setSender($sender); $this->assertEquals($sender, $websocket->getUserId()); @@ -225,12 +225,12 @@ public function testLogout() { $room = m::mock(RoomContract::class); $room->shouldReceive('getRooms') - ->with($sender = 1) - ->once() - ->andReturn(['uid_1']); + ->with($sender = 1) + ->once() + ->andReturn(['uid_1']); $room->shouldReceive('delete') - ->with($sender, $name = ['uid_1']) - ->once(); + ->with($sender, $name = ['uid_1']) + ->once(); $websocket = $this->getWebsocket($room)->setSender($sender); $websocket->logout(); @@ -240,9 +240,9 @@ public function testIsUserIdOnline() { $room = m::mock(RoomContract::class); $room->shouldReceive('getClients') - ->with('uid_1') - ->once() - ->andReturn([1]); + ->with('uid_1') + ->once() + ->andReturn([1]); $websocket = $this->getWebsocket($room); $this->assertTrue($websocket->isUserIdOnline(1)); @@ -252,8 +252,8 @@ public function testReset() { $websocket = $this->getWebsocket(); $websocket->setSender(1) - ->broadcast() - ->to('foo'); + ->broadcast() + ->to('foo'); $websocket->reset(true); @@ -265,23 +265,23 @@ public function testReset() public function testPipeline() { App::shouldReceive('call') - ->once() - ->andReturnSelf(); + ->once() + ->andReturnSelf(); $request = m::mock(Request::class); $middlewares = ['foo', 'bar']; $pipeline = m::mock(Pipeline::class); $pipeline->shouldReceive('send') - ->with($request) - ->once() - ->andReturnSelf(); + ->with($request) + ->once() + ->andReturnSelf(); $pipeline->shouldReceive('through') - ->with($middlewares) - ->once() - ->andReturnSelf(); + ->with($middlewares) + ->once() + ->andReturnSelf(); $pipeline->shouldReceive('then') - ->once() - ->andReturn($request); + ->once() + ->andReturn($request); $websocket = $this->getWebsocket(null, $pipeline); $websocket->middleware($middlewares); @@ -322,34 +322,34 @@ public function testEmit() $broadcast = true; $room = m::mock(RoomContract::class); $room->shouldReceive('getClients') - ->with(m::type('string')) - ->times(3) - ->andReturn([3, 4, 5]); + ->with(m::type('string')) + ->times(3) + ->andReturn([3, 4, 5]); App::shouldReceive('make') - ->with('swoole.server') - ->once() - ->andReturnSelf(); + ->with(Server::class) + ->once() + ->andReturnSelf(); App::shouldReceive('task') - ->with([ - 'action' => 'push', - 'data' => [ - 'sender' => $sender, - 'fds' => [1, 2, 3, 4, 5], - 'broadcast' => $broadcast, - 'assigned' => true, - 'event' => $event = 'event', - 'message' => $data = 'data', - ], - ]) - ->once(); + ->with([ + 'action' => 'push', + 'data' => [ + 'sender' => $sender, + 'fds' => [1, 2, 3, 4, 5], + 'broadcast' => $broadcast, + 'assigned' => true, + 'event' => $event = 'event', + 'message' => $data = 'data', + ], + ]) + ->once(); $websocket = $this->getWebsocket($room); $websocket->setSender($sender) - ->to($to) - ->broadcast() - ->emit($event, $data); + ->to($to) + ->broadcast() + ->emit($event, $data); $this->assertSame([], $websocket->getTo()); $this->assertFalse($websocket->getIsBroadcast()); @@ -360,13 +360,13 @@ public function testClose() $fd = 1; App::shouldReceive('make') - ->with('swoole.server') - ->once() - ->andReturnSelf(); + ->with(Server::class) + ->once() + ->andReturnSelf(); App::shouldReceive('close') - ->with($fd) - ->once(); + ->with($fd) + ->once(); $websocket = $this->getWebsocket(); $websocket->close($fd); @@ -378,8 +378,8 @@ protected function getWebsocket(RoomContract $room = null, $pipeline = null) $pipeline = $pipeline ?: m::mock(Pipeline::class); Config::shouldReceive('get') - ->once() - ->andReturn([]); + ->once() + ->andReturn([]); return new Websocket($room, $pipeline); } diff --git a/tests/fixtures/bootstrap/app.php b/tests/fixtures/bootstrap/app.php index 4ab5ca49..ed346bb1 100644 --- a/tests/fixtures/bootstrap/app.php +++ b/tests/fixtures/bootstrap/app.php @@ -1,6 +1,5 @@