You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
http/src/Context.php

148 lines
2.9 KiB
PHP

<?php
namespace BitCommunism\Http;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class Context implements \ArrayAccess
{
/**
* @var ServerRequestInterface
*/
private $request;
/**
* @var ResponseInterface
*/
private $response;
/**
* @var array
*/
private $context = [];
/**
* @var array
*/
private $vars;
/**
* @var array
*/
private $settings;
/**
* Context constructor.
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param array $vars
* @param array $settings
*/
public function __construct(ServerRequestInterface $request, ResponseInterface $response, array $vars = [], array $settings = [])
{
$this->request = $request;
$this->response = $response;
$this->vars = $vars;
$this->settings = $settings;
}
/**
* @return ServerRequestInterface
*/
public function getRequest(): ServerRequestInterface
{
return $this->request;
}
/**
* @param ServerRequestInterface $request
*/
public function setRequest(ServerRequestInterface $request): void
{
$this->request = $request;
}
/**
* @return ResponseInterface
*/
public function getResponse(): ResponseInterface
{
return $this->response;
}
/**
* @param ResponseInterface $response
*/
public function setResponse(ResponseInterface $response): void
{
$this->response = $response;
}
public function withResponse($fn)
{
$this->setResponse($fn($this->getResponse()));
}
public function getSetting($name, $default = null)
{
return $this->settings[$name] ?? $default;
}
public function getVar($name, $default = null)
{
return $this->settings[$name] ?? $default;
}
/**
* @return array
*/
public function getVars(): array
{
return $this->vars;
}
/**
* @return array
*/
public function getSettings(): array
{
return $this->settings;
}
/**
* @param array $settings
*/
public function setSettings(array $settings): void
{
$this->settings = $settings;
}
public function redirect($to, $status = 302): void {
$this->withResponse(function (ResponseInterface $response) use ($to, $status) {
return $response->withStatus($status)->withHeader('Location', $to);
});
}
public function offsetExists($offset)
{
return isset($this->context[$offset]);
}
public function offsetGet($offset)
{
return $this->context[$offset];
}
public function offsetSet($offset, $value)
{
$this->context[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->context[$offset]);
}
}