* @date 2019-11-06 02:17:24 */ declare(strict_types=1); namespace App\Middlewares; use Hyperf\HttpServer\Contract\RequestInterface; use Hyperf\HttpServer\Response; use Hyperf\Utils\ApplicationContext; use Hyperf\Utils\Str; use Psr\Http\Message\ResponseInterface as PsrResponseInterface; class OverWriteResponse extends Response { /** * Redirect to a url with a status. */ public function redirect( string $toUrl, int $status = 302, string $schema = 'http' ): PsrResponseInterface { $toUrl = value(function () use ($toUrl, $schema) { if (! ApplicationContext::hasContainer() || Str::startsWith($toUrl, ['http://', 'https://'])) { return $toUrl; } /** @var RequestInterface $request */ $request = ApplicationContext::getContainer()->get(RequestInterface::class); $uri = $request->getUri(); $hostPort = $uri->getAuthority(); $host = $uri->getHost(); if (env('HIDE_SERVER_PORT', false) === true) { $hostPort = $host; } // Build the url by $schema and host. return $schema . '://' . $hostPort . (Str::startsWith($toUrl, '/') ? $toUrl : '/' . $toUrl); }); return $this->getResponse()->withStatus($status)->withAddedHeader('Location', $toUrl); } }