/** * Add headers represented by an array of header lines. * * @param string[] $headers Response headers as array of header lines. * * @return $this * * @throws \UnexpectedValueException For invalid header values. * @throws \InvalidArgumentException For invalid status code arguments. */ public function setHeadersFromArray(array $headers) { $statusLine = trim(array_shift($headers)); $parts = explode(' ', $statusLine, 3); if (count($parts) < 2 || substr(strtolower($parts[0]), 0, 5) !== 'http/') { throw new \UnexpectedValueException(sprintf('"%s" is not a valid HTTP status line', $statusLine)); } $reasonPhrase = count($parts) > 2 ? $parts[2] : ''; $this->response = $this->response->withStatus((int) $parts[1], $reasonPhrase)->withProtocolVersion(substr($parts[0], 5)); foreach ($headers as $headerLine) { $headerLine = trim($headerLine); if ('' === $headerLine) { continue; } $parts = explode(':', $headerLine, 2); if (count($parts) !== 2) { throw new \UnexpectedValueException(sprintf('"%s" is not a valid HTTP header line', $headerLine)); } $name = trim(urldecode($parts[0])); $value = trim(urldecode($parts[1])); if ($this->response->hasHeader($name)) { $this->response = $this->response->withAddedHeader($name, $value); } else { $this->response = $this->response->withHeader($name, $value); } } return $this; }
protected function htmlBody(array $data) { // Aura.view setup $view_factory = new ViewFactory(); $view = $view_factory->newInstance(); // add templates to the view registry $view_registry = $view->getViewRegistry(); // main view $layout_registry = $view->getLayoutRegistry(); $layout_registry->set('layout', $this->viewDir . '/layout.php'); // partial view $view_registry = $view->getViewRegistry(); $partial = $this->request->getAttribute('_content'); $view_registry->set('_content', $this->viewDir . '/_' . $partial); // set partial view main content file as dynamic partial $dataset = ['data' => $data, 'partial' => $partial]; $view->setData($dataset); // do it // set views $view->setView('_content'); $view->setLayout('layout'); $output = $view->__invoke(); // or just $view() // $this->response = $this->response->withHeader('Content-Type', 'text/html'); $this->response->getBody()->write($output); }
public function execute(Request $request, Response $response, callable $next = null) { if ($this->boot()->auth->getIdentity()) { return $response->withHeader('Location', "/"); } return $next($request, $response); }
public function __invoke(Request $request, Response $response, callable $next = null) { if (Auth::guest()) { return $response->withHeader('Location', '/auth/login'); } return $next($request, $response); }
public function execute(Request $req, Response $res, callable $next = null) { try { $id = $req->getAttribute('id'); //$name = urldecode($req->getAttribute('name')); //$params = $req->getQueryParams(); $debtentrosumma = $this->boot()->get('debtentrosumma'); $entrodebtsumma = $this->boot()->get('entrodebtsumma'); $data1 = $debtentrosumma->byId($id)->current(); $data2 = $entrodebtsumma->byId($id)->current(); $s1 = is_array($data1) ? $data1['summa'] : 0; $s2 = is_array($data2) ? $data2['summa'] : 0; if ($s1 == $s2) { $s1 = 0; $s2 = 0; } else { $s1 = $s1 > $s2 ? $s1 - $s2 : 0; $s2 = $s2 > $s1 ? $s2 - $s1 : 0; } $html = "<table border='1'><tr><th colspan='2'>Деньги</th></tr>"; $html .= "<tr><th>мы должны</th><th>субъект должен нам</th></tr>"; $html .= "<tr><td>{$s2}</td><td>{$s1}</td></tr></table>"; return $res->withHeader('Content-Type', 'text/html')->withBody($this->toStream($html)); } catch (\Exception $ex) { return new JsonResponse(['status' => 'error', 'error' => $ex->getMessage()], 500); } }
/** * Check Remember Me * * This method checks whether RememberMe cookie exists * If it does, get the user credentials and make it global for easy use * If not, just route the login page * * @param ServerRequestInterface $req PSR-7 Request * @param ResponseInterface $res PSR-7 Response * * @return callable */ protected function checkRememberMe(Request $req, Response $res) { dd(Cookies::get('hihi')); die; $cookie = $this->app->cookies->get($this->c['myConfig']->get('auth.remember')); if ($cookie && !$this->app->auth) { $credentials = explode('___', $cookie); // If the cookie isn't valid if (empty(trim($cookie)) || count($credentials) !== 2) { return $res->withHeader('Location', $this->app->router->pathFor('login')); } $identifier = $credentials[0]; $hashLib = $this->c->get('hash'); $token = $hashLib->hash($credentials[1]); $user = User::where('remember_identifier', $identifier)->first(); if ($user) { if ($hashLib->hashCheck($token, $user->remember_token)) { // Finally, user can login $_SESSION[$this->c['myConfig']->get('auth.session')] = $user->user_id; $this->app->auth = $user; } else { $user->removeRememberCredentials(); } } // Endif user is found in DB } // Endif the cookie is there }
public function execute(Request $request, Response $response, callable $next = null) { $collectionname = $request->getAttribute('collectionname'); $collectionname = $this->boot()->config['collections'][$collectionname]; $collection = $this->boot()->get($collectionname); return $response->withHeader('Content-Type', 'application/json')->withBody($this->toJsonStream([['name' => $collection], ['name' => 'sdfgds4567657 56fgsdfg'], ['name' => 'sdfgdsfgsdfg 56 756745670']])); }
public function modify(ResponseInterface $response) : ResponseInterface { if (false === strpos($response->getHeaderLine('Content-Type'), 'application/json')) { return $response; } return $response->withHeader('Content-Type', $this->contentType); }
/** * * @param ResponseInterface $response * @param int $statusCode * @param array $data * * @return ResponseInterface * * @throws \InvalidArgumentException * @throws \RuntimeException */ public function render(ResponseInterface $response, $statusCode = 200, array $data = []) { $newResponse = $response->withHeader('Content-Type', 'application/json'); $newResponse = $newResponse->withStatus($statusCode); $newResponse->getBody()->write(json_encode($data)); return $newResponse; }
protected function htmlBody($data) { if (isset($data)) { $this->response = $this->response->withHeader('Content-Type', 'text/html'); $this->response->getBody()->write($data); } }
/** * Execute the middleware. * * @param RequestInterface $request * @param ResponseInterface $response * @param callable $next * * @return ResponseInterface */ public function __invoke(RequestInterface $request, ResponseInterface $response, callable $next) { if ($request->getUri()->getPath() === '/robots.txt') { $body = Middleware::createStream(); if ($this->allow) { $body->write("User-Agent: *\nAllow: /"); } else { $body->write("User-Agent: *\nDisallow: /"); } return $next($request, $response->withBody($body)); } if ($this->allow) { return $next($request, $response->withHeader(self::HEADER, 'index, follow')); } return $next($request, $response->withHeader(self::HEADER, 'noindex, nofollow, noarchive')); }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $out = null) { $page = intval($request->getAttribute('page')) ?: 0; $pictures = $this->apodApi->getPage($page, $this->resultsPerPage); $response->getBody()->write(json_encode($pictures)); return $response->withHeader('Cache-Control', ['public', 'max-age=3600'])->withHeader('Content-Type', 'application/json'); }
public function __invoke(Request $request, Response $response, callable $next = null) { if (!$this->boot()->get('auth')->getIdentity()) { return $response->withHeader('Location', "/auth"); } return $this->execute($request, $response, $next); }
/** * Execute the router. * * @return ResponseInterface * @throws AppException * @throws RuntimeException * @throws UnexpectedValueException */ public function exec() { global $CONFIG; $this->response = $this->response->withHeader('Content-Type', $this->getOutputContentType()); $routeMethod = $this->route->getMethod(); $requestMethod = strtolower($this->request->getMethod()); // OPTIONS request, don't response if ($requestMethod == 'options') { return $this->response; } $mode = 0; //error_log('[exec] >>>>>>>'.$routeMethod.'####'.$requestMethod); if (!is_null($routeMethod) && $routeMethod != $requestMethod) { if ($CONFIG->strict) { throw new AppException('Request method does not match the route request method.'); } else { error_log(sprintf('[WARING] Request method `%s` does not match the route request method `%s`.', $requestMethod, $routeMethod)); } } else { $mode = $requestMethod == 'get' ? 1 : 2; } if ($this->hasAction()) { $params = $this->getFilteredParams($mode); if (count($this->invalid)) { error_log('Invalid inputs: ' . var_export($this->invalid, true)); $invalidKeys = array_map(function ($item) { return $item['name'] . ' - ' . $item['code']; }, $this->invalid); throw new RuntimeException('Invalid inputs : ' . implode(',', array_values($invalidKeys))); } $context = new Context($this->request); $params = array_merge(array('_CONTEXT_' => $context), $params); //$result = call_user_func_array(array($this->controller, $this->getNormalizedAction()), $params); $closure = $this->controllerClosure; $result = $closure($this->getNormalizedAction(), $params); error_log('###############' . var_export($result, true)); if ($CONFIG->strict && (is_null($result) || !is_numeric($result))) { throw new UnexpectedValueException('Controller must return numeric value.'); } $statusMessage = $this->controller->getStatusMessage(); if (!is_null($result)) { $statusCode = $result; } else { $statusCode = $this->controller->getStatusCode(); if (is_null($result)) { $statusCode = Constants::SYS_SUCCESS; error_log('[WARNING] ' . $this->controllerClassName . ' ' . $this->getNormalizedAction() . ' has not return code, use default return code.'); } } $outputs = $this->controller->getOutputs(); $json = array('status' => (int) $statusCode, 'msg' => (string) $statusMessage); if (!empty($outputs)) { $json['data'] = $outputs; } return $this->processResponse($json, $this->response); } else { throw new AppException(sprintf('Action %s not found in Controller %s', $this->getNormalizedAction(), $this->getControllerClassName())); } }
/** * Proxy to PsrResponseInterface::withHeader() * * {@inheritdoc} */ public function withHeader($header, $value) { if ($this->complete) { return $this; } $new = $this->psrResponse->withHeader($header, $value); return new self($new); }
/** * Return the stylesheets for the Debugbar * * @param Request $request * @param Response $response * @param array $args * @return ResponseInterface */ public function css(Request $request, Response $response, $args) { $renderer = $this->debugbar->getJavascriptRenderer(); $body = $response->getBody(); $body->rewind(); $body->write($renderer->dumpAssetsToString('css')); return $response->withHeader('Content-type', 'text/css'); }
/** * @param ResponseInterface $response * @param Storage $storage * @return ResponseInterface */ public function writeToResponse(ResponseInterface $response, Storage $storage) { $this->handler->write($this->id, $storage->toArray()); if ($this->reset) { return $response->withHeader('Set-Cookie', "{$this->name}={$this->id}"); } return $response; }
/** * Proxy to PsrResponseInterface::withHeader() * * {@inheritdoc} * @throws RuntimeException if response is already completed */ public function withHeader($header, $value) { if ($this->complete) { throw $this->responseIsAlreadyCompleted(__METHOD__); } $new = $this->psrResponse->withHeader($header, $value); return new self($new); }
/** * @param string $filename * @param \Psr\Http\Message\ServerRequestInterface $request * @param \Psr\Http\Message\ResponseInterface $response * * @return \Psr\Http\Message\ResponseInterface * @throws \livetyping\hermitage\foundation\exceptions\ImageNotFoundException */ public function __invoke(string $filename, Request $request, Response $response) : Response { $this->prepare($filename); $image = $this->storage->get($filename); $body = new Body(fopen('php://temp', 'r+')); $body->write($image->getBinary()); return $response->withHeader('Content-Type', $image->getMimeType())->withBody($body); }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $query = $request->getQueryParams(); $target = isset($query['target']) ? $query['target'] : 'World'; $target = htmlspecialchars($target, ENT_HTML5, 'UTF-8'); var_dump($this->helper->generate('hello', ['id' => 'sha1'])); $response->getBody()->write(sprintf('<h1>Hello, %s!</h1>', $target)); return $response->withHeader('Content-Type', 'text/html'); }
/** * Handler. * * @param ServerRequestInterface $request * @param ResponseInterface $response * * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response) { $page = $request->getAttribute('page', '/index'); $content = $this->contentLoader->getContent($page); $template = $content->getMetadataEntry('template'); $params = array_merge($content->getMetadata(), ['html' => $content->getHtml()]); $response->getBody()->write($this->plates->render($template, $params)); return $response->withHeader('Content-Type', 'text/html'); }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { /* $html = $this->templateRenderer->render('app::index'); $response->getBody()->write($html); return $response->withHeader('Content-Type', 'text/html'); */ $html = $this->templateRenderer->render('app::index'); $response->getBody()->write($html); return $response->withHeader('Content-Type', 'text/html')->withHeader('Cache-Control', ['public', 'max-age=3600']); }
public function post(ServerRequestInterface $request, ResponseInterface $response) { $data = $request->getParsedBody(); $queue = QueueService::factory($data); $this->queueService->save($queue); $responseData = ['_links' => ['self' => ['/api/v0/queue/' . $queue->getId()]], 'id' => $queue->getId(), 'name' => $queue->getName()]; $response->getBody()->write(json_encode($responseData)); return $response->withHeader('Content-Type', 'application/json'); }
public function dispatch(Request $request, Response $response, $args) { $this->logger->info("Status api action dispatched"); $status = \App\Model\LogQuery::create()->orderByTimestamp('desc')->limit(1)->find()->toArray(); $status = $status[0]; $status['Data'] = json_decode($status['Data']); $response->withHeader('Content-Type', 'application/json'); $response->write(json_encode($status)); return $response; }
public function __invoke(Request $req, Response $res, callable $next) : Response { $tag = $req->getAttribute('tag'); $type = $req->getAttribute('type', 'rss'); $path = $tag ? $this->getTagFeedPath($tag, $type) : $this->getFeedPath($type); if (!file_exists($path)) { return $next($req, $res->withStatus(404), 'Not found'); } return $res->withHeader('Content-Type', sprintf('application/%s+xml', $type))->withBody(new Stream(fopen($path, 'r'))); }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable|null $next * * @return HtmlResponse */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { if ($this->cache->contains('blog:xml-feed')) { $feed = $this->cache->fetch('blog:xml-feed'); } else { $feed = $this->generateXmlFeed(); $this->cache->save('blog:xml-feed', $feed); } $response->getBody()->write($feed); return $response->withHeader('Content-Type', 'application/atom+xml')->withHeader('Cache-Control', ['public', 'max-age=3600']); }
/** * Inject the Content-Length header if is not already present. * * @param ResponseInterface $response * @return ResponseInterface */ private function injectContentLength(ResponseInterface $response) { if (!$response->hasHeader('Content-Length')) { // PSR-7 indicates int OR null for the stream size; for null values, // we will not auto-inject the Content-Length. if (null !== $response->getBody()->getSize()) { return $response->withHeader('Content-Length', (string) $response->getBody()->getSize()); } } return $response; }
public function execute(Request $request, Response $response, callable $next = null) { $body = $request->getParsedBody(); $adapter = new CredentialTreatmentAdapter($this->boot()->db); $adapter->setTableName('entity_subject')->setIdentityColumn('login')->setCredentialColumn('password')->setIdentity($body['login'])->setCredential($body['password']); $result = $this->boot()->auth->authenticate($adapter); if ($result->isValid()) { $data = $adapter->getResultRowObject(null, 'password'); $this->boot()->auth->getStorage()->write($data); } return $response->withHeader('Location', "/"); }
private function middlewareResponseBody(Response $response) { if ($this->response['contentType'] == 'redirect') { return $response->withHeader("Location", $this->response['redirect']); } if ($this->response['contentType'] == 'json') { $response->getBody()->write(json_encode($this->response['data'])); return $response; } $response->getBody()->write($this->response['body']); return $response; }
/** * * Return a response object (an instance of \Psr\Http\Message\ResponseInterface) * if the user is not logged in (The url the user is currently accessing will be * stored in $_SESSION with the key `static::SESSN_PARAM_LOGIN_REDIRECT`. Upon * a successful login, the user will be redirected back to the current url in * $this->actionLogin(). * * False is returned if the user is logged in and there is no need to redirect to * the login page. * * @return boolean|\Psr\Http\Message\ResponseInterface * */ protected function getResponseObjForLoginRedirectionIfNotLoggedIn() { if (!$this->isLoggedIn()) { $this->storeCurrentUrlForLoginRedirection(); $controller = $this->controller_name_from_uri; if (empty($controller)) { $controller = 'base-controller'; } $prepend_action = !S3MVC_APP_AUTO_PREPEND_ACTION_TO_ACTION_METHOD_NAMES; $action = $prepend_action ? 'action-login' : 'login'; $redr_path = s3MVC_GetBaseUrlPath() . "/{$controller}/{$action}"; return $this->response->withHeader('Location', $redr_path); } return false; }