/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable|null $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $response->write('<!DOCTYPE HTML>' . PHP_EOL); $response->write('<html>' . PHP_EOL); if ($next) { $response = $next($request, $response); } $response->write('</html>' . PHP_EOL); return $response; }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable|null $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $response->write(PHP_EOL . '<body class="claro">' . PHP_EOL); $response->write(' <h2> Main Request Headers</h2>' . PHP_EOL); $response->write(' <div id="MainRequestHeadesrsGrid"></div>' . PHP_EOL); $response->write(' <div id="AllType"></div>' . PHP_EOL); $next($request, $response); $response->write(PHP_EOL . $request->getAttributes() . '</br>' . PHP_EOL); $response->write(PHP_EOL . '</body>' . PHP_EOL); return $response; }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable|null $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $response->write('<head>' . PHP_EOL); $response->write(' <title>Title></title>' . PHP_EOL); $response->write(' <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . PHP_EOL); $next($request, $response); $response->write(PHP_EOL . '</head>' . PHP_EOL); if ($next) { return $next($request, $response); } return $response; }
public function dispatch(Request $request, Response $response, $args) { $this->logger->info("Company Information page action dispatched"); // Get Countries from json // TODO: Improve - Get Countries from data $menu = null; try { $filename = __DIR__ . '/../Model/scheme/Company/countries.json'; if (file_exists($filename)) { $str = file_get_contents($filename); $countries = json_decode($str); } else { $this->flash->addMessage('error', 'countries.json not found'); } } catch (Exception $e) { $this->flash->addMessage('error', 'Error getting Countries. ' . $e->getMessage()); } if (!is_null($this->currentCompany->address)) { $address = $this->currentCompany->address->fetch(); } else { $address = $this->addressRepository->create(); } // Get messages $messages = $this->flash->getMessages(); $body = $this->view->fetch('company/information/information.twig', ['flash' => $messages, 'company' => $this->currentCompany, 'address' => $address, 'countries' => $countries->data]); return $response->write($body); // $this->view->render($response, 'company/information.twig'); // return $response; }
public function dispatch(Request $request, Response $response, $args) { $this->id = $args['id']; // $this->logger->info("[" . $this->id . "] - Get data with the weather forecast"); FileSystemCache::$cacheDir = './cache/tmp'; $key = FileSystemCache::generateCacheKey('cache-feed-' . $this->id, null); $data = FileSystemCache::retrieve($key); if ($data === false) { $this->data_json = array('datetime' => json_decode(file_get_contents('http://dsx.weather.com/cs/v2/datetime/' . $this->locale . '/' . $args['id'] . ':1:BR'), true), 'now' => json_decode(file_get_contents('http://dsx.weather.com/wxd/v2/MORecord/' . $this->locale . '/' . $args['id'] . ':1:BR'), true), 'forecasts' => json_decode(file_get_contents('http://dsx.weather.com/wxd/v2/15DayForecast/' . $this->locale . '/' . $args['id'] . ':1:BR'), true)); $data = array('info' => $this->processInfo(), 'now' => $this->processNow(), 'forecasts' => $this->processForecast()); FileSystemCache::store($key, $data, 1800); } else { // $this->logger->info("[" . $this->id . "] - Using cache to generate xml"); } $xmlBuilder = new XmlBuilder('root'); $xmlBuilder->setSingularizer(function ($name) { if ('forecasts' === $name) { return 'item'; } return $name; }); $xmlBuilder->load($data); $xml_output = $xmlBuilder->createXML(true); $response->write($xml_output); $response = $response->withHeader('content-type', 'text/xml'); return $response; }
/** * Render the template. * * @param string $name * @param string[] $data * * @throws \LogicException * * @return \Psr\Http\Message\ResponseInterface */ public function render($name, array $data = []) { if (!isset($this->response)) { throw new \LogicException(sprintf('Invalid %s object instance', ResponseInterface::class)); } return $this->response->write($this->plates->render($name, $data)); }
/** * Finalize response, writes to response given data as json if array is given. * Must be public so that error handling can also call. * * @param custom $return * @return \Psr\Http\Message\ResponseInterface */ public function finalize($return) { if (is_array($return)) { $this->setContentType('application/json'); $return = json_encode($return); } return $this->response->write($return); }
/** * Render the subpage page. * * @param \Psr\Http\Message\ServerRequestInterface $request * @param \Psr\Http\Message\ResponseInterface $response * @return \Psr\Http\Message\ResponseInterface */ public function subpage(Request $request, Response $response) { $translator = $this->get('translator'); $data = ['title' => $translator->get('welcome.subpage_text'), 'welcomeMessage' => $translator->get('welcome.subpage_message')]; $view = View::make('layouts::default', $data); $view->nest('body', 'welcome.subpage', $data); return $response->write($view); }
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; }
/** * @param \Psr\Http\Message\ServerRequestInterface $request * @param \Psr\Http\Message\ResponseInterface $response * @param array $args * * @return \Psr\Http\Message\ResponseInterface */ public function get(Request $request, Response $response, $args) { $this->logger->info(substr(strrchr(rtrim(__CLASS__, '\\'), '\\'), 1) . ': ' . __FUNCTION__); $path = explode('/', $request->getUri()->getPath())[1]; $result = $this->dataaccess->get($path, $args); if ($result == null) { return $response->withStatus(404); } else { return $response->write(json_encode($result)); } }
/** * Handle notes validation, creation and update * * @param \Psr\Http\Message\ServerRequestInterface $request PSR7 request * @param \Psr\Http\Message\ResponseInterface $response PSR7 response * @param callable $next Next middleware * * @return \Psr\Http\Message\ResponseInterface */ public function dispatch(Request $request, Response $response, $args) { $id = isset($args['id']) ? (int) $args['id'] : null; $input = $request->getParsedBody(); $validator = v::key('body', v::stringType()->notEmpty()->length(5, null, true)); $validator->assert($input); if ($id === null) { $note = $this->create($input); } else { $note = $this->update($input, $id); } return $response->write(json_encode([$note])); }
public function dispatch(Request $request, Response $response, $args) { $user = $this->container->get('currentUser'); $id = isset($args['id']) ? (int) $args['id'] : null; $notes = []; if ($id) { $note = Note::where('id', $id)->where('user_id', $user->userId)->firstOrFail(); $notes = [$note]; } else { $notes = User::findOrFail($user->userId)->notes; } return $response->write(json_encode(['message' => 'List of Notes', 'data' => $notes])); }
/** * @param Container $container A DI (Pimple) container. * @param RequestInterface $request A PSR-7 compatible Request instance. * @param ResponseInterface $response A PSR-7 compatible Response instance. * @return ResponseInterface */ public function __invoke(Container $container, RequestInterface $request, ResponseInterface $response) { $config = $this->config(); // Handle explicit redirects if (!empty($config['redirect'])) { $uri = $this->parseRedirect($config['redirect'], $request); if ($uri) { return $response->withRedirect($uri, $config['redirect_mode']); } } $templateContent = $this->templateContent($container, $request); $response->write($templateContent); return $response; }
/** * Show member action - 'api_member_show' * * @param ServerRequestInterface $request * @param ResponseInterface $response * @param int $id member id * * @return \Psr\Http\Message\MessageInterface * * @throws ResourceNotFoundException */ public function showAction(ServerRequestInterface $request, ResponseInterface $response, $id) { /** @var MemberManager $manager */ $manager = $this->get('member.manager'); /** @var Serializer $serializer */ $serializer = $this->get('serializer'); $member = $manager->findMemberByActive($id); if (!$member) { $this->getMonolog()->warning('Member not found', ['id' => $id]); throw new ResourceNotFoundException('Member not found'); } $context = SerializationContext::create()->enableMaxDepthChecks()->setGroups(array('Default')); return $response->write($serializer->serialize($member, 'json', $context)); }
public function dispatch(Request $request, Response $response, $args) { // Get Cuisine Types from json $cuisineTypes = Utils::getCuisineTypes(); $dressCodes = Utils::getDressCodes(); $reservations = Utils::getReservations(); $alcoholTypes = Utils::getAlcoholTypes(); $musicTypes = Utils::getMusicTypes(); $this->logger->info("Company Environment page action dispatched"); // Get messages $messages = $this->flash->getMessages(); $body = $this->view->fetch('company/environment/environment.twig', ['flash' => $messages, 'company' => $this->currentCompany, 'cuisineTypes' => $cuisineTypes->data, 'dressCodes' => $dressCodes->data, 'reservations' => $reservations->data, 'alcoholTypes' => $alcoholTypes->data, 'musicTypes' => $musicTypes->data]); return $response->write($body); }
public function dispatch(Request $request, Response $response, $args) { $input = $request->getParsedBody(); $this->validate($input); // TODO catch exception and send user not found message $user = User::where('username', $input['username'])->firstOrFail(); if (!password_verify($input['password'], $user->password)) { return $response->withStatus(401)->write(json_encode(['message' => 'Unauthorized'])); } $data = $this->createData($user); $secretKey = base64_decode($this->settings->get('jwt')['key']); $algorithm = $this->settings->get('jwt')['algorithm']; $jwt = JWT::encode($data, $secretKey, $algorithm); return $response->write(json_encode(['jwt' => $jwt])); }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable|null $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $response->write(<<<DOJO_GRID <script> require([ 'res/AllTypeGrid' ], function (AllTypeGrid) { AllTypeGrid.startup(); }); </script> DOJO_GRID ); if ($next) { return $next($request, $response); } return $response; }
public function signUp(Request $request, Response $response, $args) { $this->logger->info("SignUp page action dispatched"); $uri = $request->getUri(); if ($request->getMethod() == 'POST') { $data = $request->getParsedBody(); $v = new $this->validator($data); $v->lang('es'); $v->rule('required', array('email', 'username', 'password', 'company')); if ($v->validate()) { try { $this->logger->info("Signup with parameters: " . $data['email'] . " - " . $data['username'] . " - " . $data['password'] . " - " . $data['company']); $newUser = new User(); $newUser->setUsername($data['username']); $newUser->setEmail($data['email']); $newUser->setPassword($data['password']); $newUser->signUp(); if ($newUser != null && $newUser->isAuthenticated()) { $result = ParseCloud::run('addUserToRole', ['roleName' => 'Manager'], false); $this->logger->info("User added to Manager Role? " . $result); $company = new Company(); $company->setName($data['company']); $company->save(); $this->flash->addMessage('info', 'Sample flash message'); return $response->withStatus(302)->withHeader('Location', $uri->withPath('')); } } catch (ParseException $e) { ParseErrorHandler::handleParseError($e); $this->flash->addMessage('error', $e->getMessage()); return $response->withStatus(302)->withHeader('Location', $uri->withPath('signup')); } } foreach ($v->errors() as $field => $errors) { foreach ($errors as $error) { $this->flash->addMessage('error', $error); } } return $response->withStatus(302)->withHeader('Location', $uri->withPath('signup')); } // Get Messages $messages = $this->flash->getMessages(); // Fetch Template $body = $this->view->fetch('login/signup.twig', ['flash' => $messages]); // Write Response return $response->write($body); }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable|null $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null) { $response->write(<<<DOJO_HEAD <script src='./js/dojo/dojo.js' data-dojo-config="async: true, parseOnLoad: true"> </script> <link rel="stylesheet" href="./js/dijit/themes/claro/claro.css"> <link rel="stylesheet" href="./js/dgrid/css/dgrid.css"> <link rel="stylesheet" href="./js\\dgrid/css/skins/claro.css"> DOJO_HEAD ); if ($next) { return $next($request, $response); } return $response; }
public function login(Request $request, Response $response, $args) { $this->logger->info("Login page action start"); if ($request->getMethod() == 'POST') { $uri = $request->getUri(); $data = $request->getParsedBody(); $this->logger->info("Login with parameters POST"); $v = new $this->validator($data); $v->lang('es'); $v->rule('required', array('username', 'password')); if ($v->validate()) { $this->logger->info("Login with parameters VALIDATION PASS"); try { $this->logger->info("Login with parameters: " . $data['username'] . " - " . $data['password']); $this->currentUser = UserRepository::logIn($data['username'], $data['password']); if ($this->currentUser != null && $this->currentUser->isAuthenticated()) { $this->flash->addMessage('info', 'Sample flash message'); $this->logger->info("Login successfull redirected to Home"); return $response->withStatus(302)->withHeader('Location', $uri->withPath('')); } } catch (ParseException $e) { ParseErrorHandler::handleParseError($e); $this->flash->addMessage('error', $e->getMessage()); $this->logger->error("Login parse exception ·" . $e->getMessage() . " REDIRECT Login"); return $response->withStatus(302)->withHeader('Location', $uri->withPath('login')); } } foreach ($v->errors() as $field => $errors) { foreach ($errors as $error) { $this->flash->addMessage('error', $error); } } $this->logger->error("Login form validation fail·- REDIRECT Login"); return $response->withStatus(302)->withHeader('Location', $uri->withPath('login')); } // Get Messages $messages = $this->flash->getMessages(); // Fetch Template $body = $this->view->fetch('login/login.twig', ['flash' => $messages]); $this->logger->info("Login page dispathed"); // Write Response return $response->write($body); }
/** * @param Container $container A DI (Pimple) container. * @param RequestInterface $request A PSR-7 compatible Request instance. * @param ResponseInterface $response A PSR-7 compatible Response instance. * @return ResponseInterface */ public function __invoke(Container $container, RequestInterface $request, ResponseInterface $response) { $config = $this->config(); $event = $this->loadEventFromPath($container); $templateIdent = $event->templateIdent(); $templateController = $event->templateIdent(); if (!$templateController) { return $response->withStatus(404); } $templateFactory = $container['template/factory']; $template = $templateFactory->create($templateController); $template->init($request); // Set custom data from config. $template->setData($config['template_data']); $template->setEvent($event); $templateContent = $container['view']->render($templateIdent, $template); $response->write($templateContent); return $response; }
/** * Получаем каталог * @param \Psr\Http\Message\ServerRequestInterface $request * @param \Psr\Http\Message\ResponseInterface $response */ public function getCatalog($request, $response) { $categories = Model::factory('Models\\Category')->find_many(); $products = Model::factory('Models\\Product')->find_many(); $data = []; $url = 'http://' . $_SERVER['HTTP_HOST']; $data['about'] = 'О нас ...'; $data['categories'] = []; foreach ($categories as $categoryt) { $arr = []; $arr['img'] = null; if ($categoryt->image) { $arr['img'] = $url . '/_/' . $categoryt->image; } $arr['id'] = $categoryt->id; $arr['title'] = $categoryt->title; $data['categories'][] = $arr; } $data['products'] = []; foreach ($products as $product) { $arr = []; $arr['img'] = null; if ($product->image) { $arr['img'] = $url . '/_/' . $product->image; } $arr['id'] = $product->id; $arr['title'] = $product->title; $arr['description'] = $product->description; $arr['price'] = (int) $product->price; $arr['categoryID'] = $product->category_id; $data['products'][] = $arr; } $response->withHeader('Content-type', 'application/json'); // $response->withHeader('Access-Control-Allow-Origin', '*'); header('Access-Control-Allow-Origin: *'); return $response->write(json_encode($data)); }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args) { return $response->write($this->container->get('RegistrationService')->verifyUser($request, $response, $args)); }
/** * @param \Psr\Http\Message\ServerRequestInterface $request * @param \Psr\Http\Message\ResponseInterface $response * @param array $args * * @return \Psr\Http\Message\ResponseInterface */ public function showHello(Request $request, Response $response, $args) { $this->logger->info(substr(strrchr(rtrim(__CLASS__, '\\'), '\\'), 1) . ': ' . __FUNCTION__); return $response->write($this->powered . ' using Slim 3 Framework'); }
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args) { return $response->write($this->container->get('AuthenticationService')->authenticate($request, $response, $args)); }
/** * Encode and return exception. * * @param Throwable|Exception $exception * @param ResponseInterface $response * @param int $status * @return ResponseInterface */ protected function encodeException($exception, ResponseInterface $response, $status = 500) { $error = ['message' => $exception->getMessage(), 'type' => get_class($exception)]; if ($this->getDisplayErrorDetails()) { $error['exception'] = []; do { $error['exception'][] = ['type' => get_class($exception), 'code' => $exception->getCode(), 'message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => explode("\n", $exception->getTraceAsString())]; } while ($exception = $exception->getPrevious()); } return $response->write(json_encode($error))->withStatus($status); }
/** * Encode JsonSerializable instance response, with status 200. * * @param JsonSerializable $action_result * @param ResponseInterface $response * @param int $status * @return ResponseInterface */ protected function encodeJsonSerializable(JsonSerializable $action_result, ResponseInterface $response, $status = 200) { return $response->write(json_encode($action_result))->withStatus($status); }
/** * Write the given message to the response and mark it complete. * * If the message is an Http\Response decorator, call and return its * `end()` method; otherwise, decorate the response and `end()` it. * * @param ResponseInterface $response * @param string $message * @return Http\Response */ private function completeResponse(ResponseInterface $response, $message) { if ($response instanceof Http\Response) { return $response->write($message); } $response = new Http\Response($response); return $response->write($message); }
public function testMiddlewareKernel(ServerRequestInterface $req, ResponseInterface $res) { return $res->write('hello from testMiddlewareKernel'); }
public function dispatch(Request $request, Response $response, $args) { // $this->logger->info("Home page action dispatched"); return $response->write(json_encode(['greeting' => 'Welcome to this awesome REST API!'])); }