OverWriteResponse.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. /**
  3. * 描述.
  4. *
  5. * @author nj <nj@gmail.com>
  6. * @date 2019-11-06 02:17:24
  7. */
  8. declare(strict_types=1);
  9. namespace App\Middlewares;
  10. use Hyperf\HttpServer\Contract\RequestInterface;
  11. use Hyperf\HttpServer\Response;
  12. use Hyperf\Utils\ApplicationContext;
  13. use Hyperf\Utils\Str;
  14. use Psr\Http\Message\ResponseInterface as PsrResponseInterface;
  15. class OverWriteResponse extends Response
  16. {
  17. /**
  18. * Redirect to a url with a status.
  19. */
  20. public function redirect(
  21. string $toUrl,
  22. int $status = 302,
  23. string $schema = 'http'
  24. ): PsrResponseInterface {
  25. $toUrl = value(function () use ($toUrl, $schema) {
  26. if (! ApplicationContext::hasContainer() || Str::startsWith($toUrl, ['http://', 'https://'])) {
  27. return $toUrl;
  28. }
  29. /** @var RequestInterface $request */
  30. $request = ApplicationContext::getContainer()->get(RequestInterface::class);
  31. $uri = $request->getUri();
  32. $hostPort = $uri->getAuthority();
  33. $host = $uri->getHost();
  34. if (env('HIDE_SERVER_PORT', false) === true) {
  35. $hostPort = $host;
  36. }
  37. // Build the url by $schema and host.
  38. return $schema . '://' . $hostPort . (Str::startsWith($toUrl, '/') ? $toUrl : '/' . $toUrl);
  39. });
  40. return $this->getResponse()->withStatus($status)->withAddedHeader('Location', $toUrl);
  41. }
  42. }