Make next call argumentless and add traits
parent
9d8ab04348
commit
554bb6b7e3
@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace BitCommunism\Http\Context;
|
||||
|
||||
|
||||
use Dflydev\FigCookies\Cookie;
|
||||
use Dflydev\FigCookies\Cookies;
|
||||
|
||||
trait RequestTraits
|
||||
{
|
||||
/**
|
||||
* @var Cookies
|
||||
*/
|
||||
protected $cookies;
|
||||
|
||||
public function getCookies(): Cookies {
|
||||
if ($this->cookies === null) {
|
||||
$this->cookies = Cookies::fromRequest($this->getRequest());
|
||||
}
|
||||
|
||||
return $this->cookies;
|
||||
}
|
||||
|
||||
public function getCookie($name): ?Cookie {
|
||||
return $this->getCookies()->get($name);
|
||||
}
|
||||
|
||||
public function getCookieValue(string $name, string $default = ""): string {
|
||||
$cookie = $this->getCookie($name);
|
||||
|
||||
if ($cookie !== null) {
|
||||
return $cookie->getValue();
|
||||
}
|
||||
|
||||
return $default;
|
||||
}
|
||||
}
|
@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
|
||||
namespace BitCommunism\Http\Context;
|
||||
|
||||
|
||||
use Dflydev\FigCookies\SetCookie;
|
||||
use Dflydev\FigCookies\SetCookies;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use function GuzzleHttp\Psr7\stream_for;
|
||||
|
||||
|
||||
trait ResponseTraits
|
||||
{
|
||||
/**
|
||||
* @var SetCookies
|
||||
*/
|
||||
private $setCookies;
|
||||
|
||||
public function json($obj, $options = 0, $depth = 512): void
|
||||
{
|
||||
$this->withResponse(function (ResponseInterface $response) use ($obj, $options, $depth) {
|
||||
return $response->withHeader('Content-Type', 'application/json')
|
||||
->withBody(stream_for(json_encode($obj, $options, $depth)));
|
||||
});
|
||||
}
|
||||
|
||||
public function redirect($to, $status = 302): void
|
||||
{
|
||||
$this->withResponse(function (ResponseInterface $response) use ($to, $status) {
|
||||
return $response->withStatus($status)->withHeader('Location', $to);
|
||||
});
|
||||
}
|
||||
|
||||
public function getSetCookies(): SetCookies {
|
||||
if ($this->setCookies === null) {
|
||||
$this->setCookies = SetCookies::fromResponse($this->getResponse());
|
||||
}
|
||||
|
||||
return $this->setCookies;
|
||||
}
|
||||
|
||||
public function setCookie($name, $value) {
|
||||
$this->addCookie(SetCookie::create($name, $value));
|
||||
}
|
||||
|
||||
public function addCookie(SetCookie $cookie) {
|
||||
$this->setCookies = $this->setCookies->with($cookie);
|
||||
}
|
||||
|
||||
public function renderResponse() {
|
||||
return $this->setCookies->renderIntoSetCookieHeader(parent::renderResponse());
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue