96 lines
3.0 KiB
PHP
96 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace Picea\Method;
|
|
|
|
use Picea\Extension\Extension,
|
|
Picea\Extension\ExtensionTrait;
|
|
|
|
use Picea\Compiler\Context;
|
|
|
|
use Picea\Extension\FunctionExtension;
|
|
use Psr\Http\Message\RequestInterface;
|
|
use Psr\Http\Message\ServerRequestInterface;
|
|
|
|
class Request implements Extension, FunctionExtension {
|
|
use ExtensionTrait;
|
|
|
|
public array $tokens;
|
|
|
|
public string $token;
|
|
|
|
public ServerRequestInterface $request;
|
|
|
|
public function __construct(ServerRequestInterface $request, Context $context) {
|
|
$this->request = $request;
|
|
}
|
|
|
|
public function parse(\Picea\Compiler\Context &$context, ?string $arguments, string $token, array $options = []) : string { }
|
|
|
|
public function exportFunctions(): array
|
|
{
|
|
return [
|
|
"cookie" => [ $this, 'cookie' ],
|
|
"get" => [ $this, 'get' ],
|
|
"post" => [ $this, 'post' ],
|
|
"request" => [ $this, 'request' ],
|
|
"server" => [ $this, 'server' ],
|
|
];
|
|
}
|
|
|
|
public function cookie(? string $variableName = null, $default = null)
|
|
{
|
|
return $variableName === null ? $this->request->getCookieParams() : static::arrayGet($this->request->getCookieParams(), $variableName) ?? $default;
|
|
}
|
|
|
|
public function get(? string $variableName = null, $default = null)
|
|
{
|
|
return $variableName === null ? $this->request->getQueryParams() : static::arrayGet($this->request->getQueryParams(), $variableName) ?? $default;
|
|
}
|
|
|
|
public function post(? string $variableName = null, $default = null)
|
|
{
|
|
return $variableName === null ? $this->_post() : static::arrayGet($this->_post(), $variableName) ?? $default;
|
|
}
|
|
|
|
public function request(? string $variableName = null, $default = null)
|
|
{
|
|
return $variableName === null ? array_merge($this->get(), $this->post()) : $this->post($variableName) ?? $this->get($variableName) ?? $default;
|
|
}
|
|
|
|
public function server(? string $variableName = null, $default = null)
|
|
{
|
|
return $variableName === null ? $this->request->getServerParams() : static::arrayGet($this->request->getServerParams(), $variableName) ?? $default;
|
|
}
|
|
|
|
public static function arrayGet(array $array, string $path, string $delimiter = '.')
|
|
{
|
|
$pathArr = explode($delimiter, $path);
|
|
|
|
if ( isset($array[$pathArr[0]]) ) {
|
|
if ( isset($pathArr[1]) ) {
|
|
return static::arrayGet($array[array_shift($pathArr)], implode($delimiter, $pathArr));
|
|
}
|
|
else {
|
|
return $array[$pathArr[0]];
|
|
}
|
|
}
|
|
else {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
protected function _post() : array
|
|
{
|
|
$post = $this->request->getParsedBody();
|
|
|
|
if ( ! $post ) {
|
|
$content = utf8_encode((string) $this->request->getBody());
|
|
|
|
if ( $content && ( $json = json_decode($content, true) ) ) {
|
|
$post = $json;
|
|
}
|
|
}
|
|
|
|
return $post ?: [];
|
|
}
|
|
} |