/**
  * Convert data to JSON and set as response, with caching header.
  *
  * @param $data mixed
  *
  * @return Response
  */
 public function buildResponse($data)
 {
     // Construct response based on provided data.
     $builtResponse = $this->response->withHeader('Content-Type', 'application/json')->write(json_encode($data, JSON_PRETTY_PRINT));
     // Return the response with an ETag added, for caching.
     return $this->c->cache->withEtag($builtResponse, sha1($builtResponse->getBody()));
 }
Beispiel #2
2
 public function goBack()
 {
     if ($this->request->hasHeader('HTTP_REFERER')) {
         $referer = $this->request->getHeader('HTTP_REFERER')[0];
         return $this->response->withRedirect($referer, 301);
     }
     return $this->goHome();
 }
Beispiel #3
1
 public function getUserDetails(Request $request, Response $response, $arguments)
 {
     $user = $this->container->user;
     if ($user) {
         return $response->withJson($user, 200, JSON_PRETTY_PRINT);
     }
 }
Beispiel #4
0
 public function __invoke(Request $req, Response $res)
 {
     $school = $req->getAttribute('school', false);
     if (!$school) {
         return $res->withStatus(403, 'No school');
     }
     $teacherId = $req->getParam('teacher_id');
     $teacher = $this->staffService->getTeacherById($teacherId);
     if ($teacher['school_id'] !== $school->id) {
         return $res->withStatus(403, 'No school');
     }
     if ($req->isPost()) {
         $inputFilter = $this->inputFilter;
         $result = $inputFilter($req->getParams());
         if (!$result['is_valid']) {
             $res = $res->withStatus(422);
             $res = $res->withJson($result);
             return $res;
         }
         $this->service->saveAnswers($teacherId, $result['values']);
     }
     $data = $this->service->getAnswers($teacherId);
     $res = $res->withJson($data);
     return $res;
 }
Beispiel #5
0
 /**
  * assert that the response is a redirect with $path (if set).
  * 
  * @param string $path
  */
 protected function responseIsRedirect($path = '')
 {
     $this->assertTrue($this->response->isRedirect());
     if ($path) {
         $this->assertEquals($this->root_url . $path, $this->response->getHeaderLine('Location'));
     }
 }
Beispiel #6
0
 /**
  * Execute the middleware.
  *
  * @param ExtendedRequest $request
  * @param Response        $response
  * @param callable        $next
  *
  * @return Response
  */
 public function __invoke(ExtendedRequest $request, Response $response, callable $next)
 {
     $router = $this->router;
     $route = $request->getCurrentRoute();
     $locales = $this->locale;
     $locale = $locales->getDefault();
     $lang = $route->getArgument($router->getLanguageIdentifier());
     $lang = ltrim($lang, '/');
     $redirect = false;
     if ($lang) {
         try {
             // Find language in list of available locales and set it as active
             $locale = $locales->findByLanguage($lang);
             $locales->setActive($locale);
             if ($router->isOmitDefaultLanguage() && $locale == $locales->getDefault()) {
                 // Trigger redirect to correct path (as language set in path is default lang and we want to omit it)
                 $redirect = true;
             }
         } catch (Exception $e) {
             // Trigger "notFound" as setActive() throws Exception if $locale is not valid / available
             $next = $this->notFoundHandler;
         }
     } elseif (!$router->isOmitDefaultLanguage()) {
         // Trigger redirect to correct path (as language is not set in path but we don't want to omit default lang)
         $redirect = true;
     }
     // Redirect to route with proper language identifier value set (or omitted)
     if ($redirect) {
         $path = $router->pathFor($route->getName(), $route->getArguments(), $request->getParams(), $locale->getLanguage());
         $uri = $request->getUri()->withPath($path);
         return $response->withRedirect($uri);
     }
     return $next($request, $response);
 }
Beispiel #7
0
 /**
  * This function outputs the given $data as valid HAL+JSON to the client
  * and sets the HTTP Response Code to the given $statusCode.
  *
  * @param array|SlimBootstrap\DataObject $data       The data to output to
  *                                                   the client
  * @param int                            $statusCode The status code to set
  *                                                   in the reponse
  */
 public function write($data, $statusCode = 200)
 {
     $path = $this->_request->getPath();
     $hal = new hal\Hal($path);
     if (true === is_array($data)) {
         $pathData = explode('/', $path);
         unset($pathData[0]);
         $endpointName = end($pathData);
         $endpointUri = '/' . implode('/', $pathData) . '/';
         foreach ($data as $entry) {
             /** @var SlimBootstrap\DataObject $entry */
             $identifiers = $entry->getIdentifiers();
             $resourceName = $endpointUri . implode('/', array_values($identifiers));
             $resource = new hal\Hal($resourceName, $entry->getData() + $entry->getIdentifiers());
             $this->_addAdditionalLinks($resource, $entry->getLinks());
             $hal->addLink($endpointName, $resourceName);
             $hal->addResource($endpointName, $resource);
         }
     } else {
         $hal->setData($data->getData() + $data->getIdentifiers());
         $this->_addAdditionalLinks($hal, $data->getLinks());
     }
     $body = $this->_jsonEncode($hal);
     if (false === $body) {
         $this->_response->setStatus(500);
         $this->_response->setBody("Error encoding requested data.");
         return;
     }
     $this->_headers->set('Content-Type', 'application/hal+json; charset=UTF-8');
     $this->_response->setStatus($statusCode);
     $this->_response->setBody($hal->asJson());
 }
 /**
  * Execute the middleware.
  *
  * @param  \Slim\Http\Request  $req
  * @param  \Slim\Http\Response $res
  * @param  callable            $next
  * @return \Slim\Http\Response
  */
 public function __invoke(Request $req, Response $res, callable $next)
 {
     $uri = $req->getUri();
     $path = $this->filterTrailingSlash($uri);
     if ($uri->getPath() !== $path) {
         return $res->withStatus(301)->withHeader('Location', $path)->withBody($req->getBody());
     }
     //        if ($this->filterBaseurl($uri)) {
     //            return $res->withStatus(301)
     //                ->withHeader('Location', (string) $uri)
     //                ->withBody($req->getBody());
     //        }
     $server = $req->getServerParams();
     if (!isset($server['REQUEST_TIME_FLOAT'])) {
         $server['REQUEST_TIME_FLOAT'] = microtime(true);
     }
     $uri = $uri->withPath($path);
     $req = $this->filterRequestMethod($req->withUri($uri));
     $res = $next($req, $res);
     $res = $this->filterPrivateRoutes($uri, $res);
     // Only provide response calculation time in non-production env, tho.
     if ($this->settings['mode'] !== 'production') {
         $time = (microtime(true) - $server['REQUEST_TIME_FLOAT']) * 1000;
         $res = $res->withHeader('X-Response-Time', sprintf('%2.3fms', $time));
     }
     return $res;
 }
Beispiel #9
0
 public function __invoke(Request $request, Response $response, $arguments)
 {
     $response->write('this is just the beginning of my application');
     foreach ($arguments as $argument) {
         $response->write("\n {$argument}");
     }
 }
Beispiel #10
0
 public function test(Request $request, Response $response, array $args)
 {
     $uid = $args['uid'];
     $myaccount = R::load('accounts', $uid);
     $accountId = $myaccount->accountid;
     $account = R::findOne('accounts', ' accountid = ?', [$accountId]);
     if (!empty($account)) {
         $apiKey = $account['apikey'];
         $type = $account['servertype'];
         $oandaInfo = new Broker_Oanda($type, $apiKey, $accountId);
     } else {
         $this->flash->addMessage('flash', "Oanda AccountId not found");
         return $response->withRedirect($request->getUri()->getBaseUrl() . $this->router->pathFor('homepage'));
     }
     $side = 'buy';
     $pair = 'EUR_USD';
     $price = '1.1400';
     $expiry = time() + 60;
     $stopLoss = '1.1300';
     $takeProfit = NULL;
     $risk = 1;
     //        $side='buy';
     //        $pair='GBP_CHF';
     //        $price='2.1443';
     //        $expiry = $oandaInfo->getExpiry(time()+60);
     //        $stopLoss='2.1452';
     //        $takeProfit=NULL;
     //        $risk=1;
     //$oandaInfo->placeLimitOrder($side,$pair,$price,$expiry,$stopLoss,$takeProfit,$risk);
     $oandaInfo->processTransactions();
 }
 public function send()
 {
     foreach ($this->response->headers() as $name => $value) {
         header("{$name}: {$value}", true, $this->response->getStatus());
     }
     echo $this->response->getBody();
 }
Beispiel #12
0
 public function learningcenterRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("learningcenter", ["id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/learningcenter");
 }
Beispiel #13
0
 /**
  * {@inheritdoc}
  */
 public function register()
 {
     $this->getContainer()->share('settings', function () {
         return new Collection($this->defaultSettings);
     });
     $this->getContainer()->share('environment', function () {
         return new Environment($_SERVER);
     });
     $this->getContainer()->share('request', function () {
         return Request::createFromEnvironment($this->getContainer()->get('environment'));
     });
     $this->getContainer()->share('response', function () {
         $headers = new Headers(['Content-Type' => 'text/html']);
         $response = new Response(200, $headers);
         return $response->withProtocolVersion($this->getContainer()->get('settings')['httpVersion']);
     });
     $this->getContainer()->share('router', function () {
         return new Router();
     });
     $this->getContainer()->share('foundHandler', function () {
         return new RequestResponse();
     });
     $this->getContainer()->share('errorHandler', function () {
         return new Error($this->getContainer()->get('settings')['displayErrorDetails']);
     });
     $this->getContainer()->share('notFoundHandler', function () {
         return new NotFound();
     });
     $this->getContainer()->share('notAllowedHandler', function () {
         return new NotAllowed();
     });
     $this->getContainer()->share('callableResolver', function () {
         return new CallableResolver($this->getContainer());
     });
 }
Beispiel #14
0
 public function __invoke(Request $req, Response $res, array $args = [])
 {
     $school = $req->getAttribute('school', false);
     if (!$school) {
         return $res->withStatus(403, 'No school');
     }
     $params = $req->getParams();
     $id = $params['id'];
     $params['school_id'] = $school->id;
     if (isset($params['lessons']) && !is_array($params['lessons'])) {
         $params['lessons'] = explode(',', $params['lessons']);
     }
     unset($params['id']);
     try {
         if ($id) {
             $lab = $this->labservice->updateLab($params, $id);
             $res = $res->withStatus(200);
         } else {
             $lab = $this->labservice->createLab($params);
             $res = $res->withStatus(201);
         }
         $res = $res->withJson($lab);
     } catch (Exception $ex) {
         $res = $res->withStatus(500, $ex->getMessage());
     }
     return $res;
 }
Beispiel #15
0
 /**
  * @param int $statusCode
  * @param string $urlPath
  */
 public function redirect($statusCode, $urlPath)
 {
     $urlPath = ltrim($urlPath, '/');
     $baseUrl = $this->scheme . '://' . $this->host . '/' . $urlPath;
     $this->response->status($statusCode);
     $this->response->header('Location', $baseUrl);
 }
 public function render(Response $response, $template = "", $data = [])
 {
     extract($data);
     ob_start();
     include $this->templatePath . $template;
     $output = ob_get_clean();
     return $response->write($output);
 }
 public function productRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("product", ["id" => $attr["id"]]);
     $db->delete("person_cripple", ["cripple_id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/product");
 }
 protected function request($method, $url, array $requestParameters = [], array $headers = [])
 {
     $request = $this->prepareRequest($method, $url, $requestParameters, $headers);
     $response = new Response();
     $app = $this->app;
     $this->response = $app->callMiddlewareStack($request, $response);
     $this->jsonResponseData = json_decode((string) $this->response->getBody(), true);
 }
Beispiel #19
0
 public function disavantaged_typeRemove(Request $req, Response $res, $attr = [])
 {
     $container = $this->slim->getContainer();
     $db = $container->medoo;
     $db->delete("disavantaged_type", ["id" => $attr["id"]]);
     $db->delete("person_disavantaged", ["disavantaged_id" => $attr["id"]]);
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/disavantaged_type");
 }
 public function writeUnauthorized()
 {
     $this->response = $this->response->withStatus(401);
     $apiResponse = new ApiResponse();
     $apiResponse->setStatusFail();
     $apiResponse->setData("Unauthorized");
     $this->body->write($apiResponse->toJSON());
 }
Beispiel #21
0
 public function testWritePlain()
 {
     $this->_jsonTestOutputWriter->expects($this->exactly(1))->method('_jsonEncode')->with($this->equalTo(array('mockKey' => 'mockValue')))->will($this->returnValue('{"mockKey": "mockValue"}'));
     $this->_mockHeaders->expects($this->exactly(1))->method('set')->with($this->equalTo('Content-Type'), $this->equalTo('application/json; charset=UTF-8'));
     $this->_mockResponse->expects($this->exactly(1))->method('setStatus')->with($this->equalTo(200));
     $this->_mockResponse->expects($this->exactly(1))->method('setBody')->with($this->equalTo('{"mockKey": "mockValue"}'));
     $this->_jsonTestOutputWriter->writePlain(array('mockKey' => 'mockValue'));
 }
 /**
  * @param Response $response
  * @param int      $status
  *
  * @return ResponseInterface
  */
 public function render(Response $response, $status = 200)
 {
     // Put the default top-level members into $result object
     $result = new \StdClass();
     $result->data = $this->data;
     $result->errors = $this->errors;
     return $response->withJson($result, $status);
 }
Beispiel #23
0
 /**
  * @param \swoole_http_request $request
  * @param \swoole_http_response $response
  * @throws \Exception
  */
 public function __invoke($request, $response)
 {
     $this->app->getContainer()['environment'] = $this->app->getContainer()->factory(function () {
         return new Environment($_SERVER);
     });
     $this->app->getContainer()['request'] = $this->app->getContainer()->factory(function ($container) {
         return Request::createFromEnvironment($container['environment']);
     });
     $this->app->getContainer()['response'] = $this->app->getContainer()->factory(function ($container) {
         $headers = new Headers(['Content-Type' => 'text/html']);
         $response = new Response(200, $headers);
         return $response->withProtocolVersion($container->get('settings')['httpVersion']);
     });
     /**
      * @var ResponseInterface $appResponse
      */
     $appResponse = $this->app->run(true);
     // set http header
     foreach ($appResponse->getHeaders() as $key => $value) {
         $filter_header = function ($header) {
             $filtered = str_replace('-', ' ', $header);
             $filtered = ucwords($filtered);
             return str_replace(' ', '-', $filtered);
         };
         $name = $filter_header($key);
         foreach ($value as $v) {
             $response->header($name, $v);
         }
     }
     // set http status
     $response->status($appResponse->getStatusCode());
     // send response to browser
     if (!$this->isEmptyResponse($appResponse)) {
         $body = $appResponse->getBody();
         if ($body->isSeekable()) {
             $body->rewind();
         }
         $settings = $this->app->getContainer()->get('settings');
         $chunkSize = $settings['responseChunkSize'];
         $contentLength = $appResponse->getHeaderLine('Content-Length');
         if (!$contentLength) {
             $contentLength = $body->getSize();
         }
         $totalChunks = ceil($contentLength / $chunkSize);
         $lastChunkSize = $contentLength % $chunkSize;
         $currentChunk = 0;
         while (!$body->eof() && $currentChunk < $totalChunks) {
             if (++$currentChunk == $totalChunks && $lastChunkSize > 0) {
                 $chunkSize = $lastChunkSize;
             }
             $response->write($body->read($chunkSize));
             if (connection_status() != CONNECTION_NORMAL) {
                 break;
             }
         }
         $response->end();
     }
 }
Beispiel #24
0
 public function __invoke(Request $req, Response $res)
 {
     $result = $this->authService->authenticate();
     if (!$result->isValid()) {
         $this->flash->addMessage('danger', reset($result->getMessages()));
         return $res->withRedirect($this->loginUrl);
     }
     return $res->withRedirect($this->successUrl);
 }
Beispiel #25
0
 /**
  * @param $data
  *
  * @dataProvider normalizeAllDataProvider
  */
 public function testWriteArray($data)
 {
     $localCsvTestOutputWriter = $this->getMock('\\SlimBootstrap\\ResponseOutputWriter\\Csv', array('_csvEncode'), array($this->_mockRequest, $this->_mockResponse, $this->_mockHeaders, 'mockShortName'));
     $this->_mockHeaders->expects($this->once())->method('set')->with($this->identicalTo("Content-Type"), $this->identicalTo("text/csv; charset=UTF-8"));
     $this->_mockResponse->expects($this->once())->method('setStatus')->with($this->equalTo(200));
     $localCsvTestOutputWriter->expects($this->once())->method('_csvEncode');
     $this->_mockResponse->expects($this->once())->method('setBody');
     $localCsvTestOutputWriter->write($data, 200);
 }
Beispiel #26
0
 /**
  * It performs the setup of a reactPHP response from a SlimpPHP response
  * object and finishes the communication
  *
  * @param \React\Http\Response $reactResp    ReactPHP native response object
  * @param \Slim\Http\Response  $slimResponse SlimPHP native response object
  * @param boolean              $endRequest   If true, response flush will be finished
  *
  * @return void
  */
 static function setReactResponse(\React\Http\Response $reactResp, \Slim\Http\Response $slimResponse, $endRequest = false)
 {
     $headers = static::reduceHeaders($slimResponse->getHeaders());
     $reactResp->writeHead($slimResponse->getStatusCode(), $headers);
     $reactResp->write($slimResponse->getBody());
     if ($endRequest === true) {
         $reactResp->end();
     }
 }
 public function __invoke(Request $req, Response $res)
 {
     $school = $req->getAttribute('school', false);
     if (!$school) {
         return $res->withStatus(403, 'No school');
     }
     $this->service->setTotalTeachers($school->id, (int) $req->getParam('total_teachers', 0));
     return $res->withStatus(204);
 }
 /**
  * Create new container
  *
  * @param array $settings Associative array of settings. User settings are in a 'settings' sub-array
  */
 public function __construct($settings = [])
 {
     $userSettings = [];
     if (isset($settings['settings'])) {
         $userSettings = $settings['settings'];
         unset($settings['settings']);
     }
     // Add settings factory that also collects the default settings
     $defaultSettings = $this->defaultSettings;
     $settings['factories']['settings'] = function ($c) use($userSettings, $defaultSettings) {
         return array_merge($defaultSettings, $userSettings);
     };
     // Add default services if they aren't added already
     if (!isset($settings['environment'])) {
         $settings['factories']['environment'] = function ($c) {
             return new Environment($_SERVER);
         };
     }
     if (!isset($settings['request'])) {
         $settings['factories']['request'] = function ($c) {
             return Request::createFromEnvironment($c['environment']);
         };
     }
     if (!isset($settings['response'])) {
         $settings['factories']['response'] = function ($c) {
             $headers = new Headers(['Content-Type' => 'text/html']);
             $response = new Response(200, $headers);
             return $response->withProtocolVersion($c['settings']['httpVersion']);
         };
     }
     if (!isset($settings['router'])) {
         $settings['factories']['router'] = function ($c) {
             return new Router();
         };
     }
     if (!isset($settings['callableResolver'])) {
         $settings['factories']['callableResolver'] = function ($c) {
             return new CallableResolver($c);
         };
     }
     if (!isset($settings['foundHandler'])) {
         $settings['invokables']['foundHandler'] = RequestResponse::class;
     }
     if (!isset($settings['errorHandler'])) {
         $settings['factories']['errorHandler'] = function ($c) {
             return new Error($c->get('settings')['displayErrorDetails']);
         };
     }
     if (!isset($settings['notFoundHandler'])) {
         $settings['invokables']['notFoundHandler'] = NotFound::class;
     }
     if (!isset($settings['notAllowedHandler'])) {
         $settings['invokables']['notAllowedHandler'] = NotAllowed::class;
     }
     parent::__construct($settings);
 }
Beispiel #29
0
 public function anyLogout(Request $req, Response $res)
 {
     $container = $this->slim->getContainer();
     /** @var Aura\Session\Session */
     $session = $container->session;
     $loginSegment = $session->getSegment("login");
     $loginSegment->clear();
     $session->commit();
     return $res->withHeader("Location", $req->getUri()->getBasePath() . "/login");
 }
 public function __invoke(Request $request, Response $response, $args)
 {
     $this->request =& $request;
     if ($this->execute($args)) {
         $responder = new $this->responder($response, $this->responseInfo);
         return $responder();
     } else {
         return $response->withStatus(self::STATUS_NOT_FOUND);
     }
 }