/**
  * Create from the given result a Response instance and send it.
  *
  * @param mixed  $response
  *
  * @return \Symfony\Component\HttpFoundation\Response
  */
 protected function processResponse($response)
 {
     if ($response instanceof Renderable) {
         // If the response which is returned from the called Action is a Renderable instance,
         // we will assume we want to render it using the Controller's templated environment.
         if (is_string($this->layout) && !$response instanceof Layout) {
             $response = Template::make($this->layout, $this->template)->with('content', $response);
         }
         // Create a proper Response instance.
         $response = new Response($response->render(), 200, array('Content-Type' => 'text/html'));
     }
     // If the response is not a instance of Symfony Response, create a proper one.
     if (!$response instanceof SymfonyResponse) {
         $response = new Response($response);
     }
     return $response;
 }
Exemple #2
0
function routeRequest(Response $response, Request $request)
{
    $routesDefinitionsCallback = function (RouteCollector $r) {
        foreach (require __DIR__ . "/routes.php" as $route) {
            $r->addRoute($route[0], $route[1], $route[2]);
        }
    };
    $dispatcher = \FastRoute\simpleDispatcher($routesDefinitionsCallback);
    $routeInfo = $dispatcher->dispatch($request->getMethod(), $request->getPath());
    switch ($routeInfo[0]) {
        case Dispatcher::NOT_FOUND:
            $response->setStatusCode(404);
            $response->setContent('404 - not found');
            break;
        case Dispatcher::METHOD_NOT_ALLOWED:
            $response->setStatusCode(403);
            $response->setContent('403 - not allowed');
            break;
        case Dispatcher::FOUND:
            $response->setStatusCode(200);
            $className = $routeInfo[1][0];
            $method = $routeInfo[1][1];
            $vars = $routeInfo[2];
            return new Step("{$className}::{$method}", InjectionParams::fromRouteParams($vars));
    }
    return new step(function () {
        echo "something went wrong";
    });
}
Exemple #3
0
 /**
  * Response constructor.
  * @param $client
  * @param \Http\Response $response
  */
 public function __construct(Client $client, \Http\Response $response)
 {
     $this->client = $client;
     $this->body = $body = json_decode($response->getBody(), TRUE);
     if (isset($body['items'])) {
         $this->items = $body['items'];
     }
     if (isset($body['_meta'])) {
         $this->total_count = $body['_meta']['totalCount'];
         $this->page_count = $body['_meta']['pageCount'];
         $this->current_page = $body['_meta']['currentPage'];
         $this->per_page = $body['_meta']['perPage'];
     }
     if (isset($body['_links'])) {
         $this->pages = array_map('current', $body['_links']);
     }
     foreach ($body as $key => $value) {
         if ($key !== 'items' and $key[0] !== '_') {
             $this->additional[$key] = $value;
         }
     }
 }
 /**
  * Delete a single person based on the ID
  *
  * URI: /delete
  *
  */
 public function delete()
 {
     if ($this->request->getParameter('csrf') === $this->csrf->getCurrentToken()) {
         try {
             $this->people->deleteById((int) $this->request->getParameter('id'));
             $message = 'success';
             $response = 200;
         } catch (\Exception $e) {
             $message = 'failure';
             $response = 500;
         }
     } else {
         $message = 'failure';
         $response = 500;
     }
     $template_vars = array('json' => json_encode(array('message' => $message)));
     $html = $this->renderer->render('page/data.php', $template_vars);
     $this->response->setStatusCode($response);
     $this->response->setContent($html);
 }
Exemple #5
0
 /**
  * Override the errorHandler
  */
 public static final function errorHandler($severity, $message, $filepath, $line)
 {
     $is_error = ((E_ERROR | E_COMPILE_ERROR | E_CORE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR) & $severity) === $severity;
     $level = self::$levels[$severity];
     $context = self::getContext(self::ERROR, $level, $message, $filepath, $line);
     if (!in_array($severity, array_merge([E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR], self::$ignore), true)) {
         error_log("{$level}: {$message} in {$filepath} in line {$line}");
         if (!empty(self::$logger)) {
             self::$logger->error("{$level}: {$message} in {$filepath} in line {$line}", $context);
         }
     }
     if ($is_error) {
         if (!empty(self::$logger)) {
             self::$logger->critical("{$level}: {$message} in {$filepath} in line {$line}", $context);
         }
         if (!is_null(self::$lastAction)) {
             $fn = self::$lastAction;
             $fn();
         }
         self::$httpHandler->overwrite(self::getErrorTemplate(self::$httpHandler, self::$defaultErrorPath))->withStatus(500)->send();
     }
 }
Exemple #6
0
 /**
  * @param Route $route
  */
 private function process(Route $route, Request $request)
 {
     $this->dispatch('process.before', [$request]);
     $arguments = $route->getArguments();
     array_unshift($arguments, $request);
     try {
         $response = call_user_func_array($route->getCallable(), $arguments);
         if (!$response instanceof Response) {
             $response = new Response($response);
         }
         $response->send();
     } catch (HttpException $e) {
         throw $e;
     } catch (\Exception $e) {
         throw new HttpException(500, null, $e);
     }
 }
Exemple #7
0
<?php

require '../vendor/autoload.php';
//use \HTTP\Response\Status;
//use \HTTP\Response\CacheControl;
// I know, I didn't write proper unit tests, I know...I know...
//$a  = new \HTTP\Response\Allow;
//die('a'.$a);
use HTTP\Response;
die(Response\CacheControl::getName());
$response = new \HTTP\Response();
echo $response->getProtocolVersion() . PHP_EOL;
$response = $response->withProtocolVersion('1.0');
echo $response->getProtocolVersion() . PHP_EOL;
print_r($response->getHeaders());
echo PHP_EOL;
var_dump($response->hasHeader($response::CACHE_CONTROL));
echo PHP_EOL;
$response = $response->withHeader($response::CACHE_CONTROL, 'bananas');
echo PHP_EOL;
print_r($response->getHeader($response::CACHE_CONTROL));
$response = $response->withAddedHeader($response::CACHE_CONTROL, CacheControl::MAX_AGE);
echo $response->getHeaderLine($response::CACHE_CONTROL);
echo PHP_EOL;
$response = $response->withoutHeader($response::CACHE_CONTROL);
print_r($response->getHeader($response::CACHE_CONTROL));
echo PHP_EOL;
echo $response->getStatusCode();
echo PHP_EOL;
$response = $response->withStatus(Status::CODE500, "big fail");
echo $response->getStatusCode();
Exemple #8
0
        $response = new Response($content, 400);
        $response->send();
    }
    $_SESSION['is_authenticated'] = true;
    $_SESSION['id'] = $user->getId();
    $_SESSION['login'] = $user->getLogin();
    $app->redirect('/statuses');
});
$app->post('/register', function (Request $request) use($app, $userMapper) {
    $login = htmlspecialchars($request->getParameter('user'));
    $password = htmlspecialchars($request->getParameter('password'));
    $password_verif = htmlspecialchars($request->getParameter('password2'));
    if (!isset($login) || !isset($password)) {
        $erreur = "Empty parameters";
        $content = $app->render('register.php', array('erreur' => $erreur, 'login' => $login));
        $response = new Response($content, 400);
        $response->send();
    }
    if (!($password == $password_verif)) {
        $erreur = "The two password aren't similars";
        return $app->render('register.php', array('erreur' => $erreur, 'login' => $login));
    }
    $userMapper->persist(new User(null, $login, $password));
    $app->redirect('/login?login='******'/logout', function (Request $request) use($app) {
    session_destroy();
    $app->redirect('/statuses');
});
/////////////////////////////////////////////////////////////////////////////////////////////////
//                          FIREWALL                                                           //
Exemple #9
0
 /**
  * JsonResponse constructor.
  *
  * @param $content
  * @param int   $statusCode
  * @param array $headers
  */
 public function __construct($content, $statusCode = 200, array $headers = [])
 {
     parent::__construct(self::serialize($content), $statusCode, array_merge(['Content-Type' => 'application/json'], $headers));
 }
 /**
  * Create a response instance from the given value.
  *
  * @param  \Symfony\Component\HttpFoundation\Request  $request
  * @param  mixed  $response
  * @return \Http\Response
  */
 protected function prepareResponse($request, $response)
 {
     if (!$response instanceof SymfonyResponse) {
         $response = new Response($response);
     }
     return $response->prepare($request);
 }
Exemple #11
0
 public function testStatus()
 {
     $response = new Response('body', '200');
     $status = $response->getStatus()->getCode();
     $this->assertEquals($response->getStatus()->getCode(), 200);
 }
Exemple #12
0
 /**
  * @param Route $route
  */
 private function process(Route $route, Request $request)
 {
     $arguments = $route->getArguments();
     array_unshift($arguments, $request);
     try {
         $contentResponse = call_user_func_array($route->getCallable(), $arguments);
         //~ http_response_code($this->statusCode);
         //~ echo $response;
         $response = new Response($contentResponse, $this->statusCode);
         $response->send();
     } catch (HttpException $e) {
         throw $e;
     } catch (\Exception $e) {
         throw new HttpException(500, null, $e);
     }
 }
Exemple #13
0
 public function request($data)
 {
     if (is_string($data)) {
         $url = $data;
         $data = null;
     } else {
         $url = isset($data['url']) ? $data['url'] : null;
     }
     if (!$url) {
         throw new Exception('InvalidArgumentException: $url is required!');
     }
     $params = isset($data['body']) ? $data['body'] : null;
     $method = isset($data['method']) ? strtoupper((string) $data['method']) : 'GET';
     $headers = isset($data['headers']) ? $data['headers'] : null;
     $query = parse_url($url, PHP_URL_QUERY);
     // merge headers with config headers
     $headers = $headers ? array_merge($this->config->getHeaders(), $headers) : $this->config->getHeaders();
     // apply basic http authentication from config
     $auth = $this->config->getBasicAuthentication();
     if ($auth && !isset($headers['Authorization'])) {
         $headers['Authorization'] = $auth;
     }
     // handle content type
     if (isset($headers['Content-Type'])) {
         $contentType = $headers['Content-Type'];
     } else {
         // omit for GET, DELETE?
         $headers['Content-Type'] = $contentType = $this->config->getContentType();
     }
     if (in_array($method, self::$bodyLessMethods, true)) {
         $url .= ($query ? '&' : '?') . (is_array($params) ? http_build_query($params, null, '&') : $params);
         unset($headers['Content-Type']);
         $params = null;
     } else {
         if (!$params) {
         } elseif (strpos($contentType, 'application/json') !== false) {
             $params = json_encode($params);
         } elseif (strpos($contentType, 'text/plain') !== false) {
             $params = (string) $params;
         } else {
             $params = http_build_query($params, null, '&');
         }
     }
     if ($params) {
         $headers['Content-Length'] = strlen($params);
     }
     $readHeaders = true;
     $ch = curl_init($url);
     curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
     curl_setopt($ch, CURLOPT_TIMEOUT, $this->config->getTimeout());
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     if ($readHeaders === true) {
         curl_setopt($ch, CURLOPT_HEADER, true);
         curl_setopt($ch, CURLINFO_HEADER_OUT, true);
     }
     curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getCurlHeaders($headers));
     // disable SSL verification, if needed
     if ($this->config->getSSLVerification() === false) {
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
     }
     //Execute Curl Request
     $result = curl_exec($ch);
     if ($result === false) {
         throw new Exception(curl_error($ch));
     }
     //Retrieve Response Status
     $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     if ($readHeaders === true) {
         // Get Request and Response Headers
         $requestHeaders = curl_getinfo($ch, CURLINFO_HEADER_OUT);
         //Using alternative solution to CURLINFO_HEADER_SIZE as it throws invalid number when called using PROXY.
         if (function_exists('mb_strlen')) {
             $responseHeaderSize = mb_strlen($result, '8bit') - curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);
             $responseHeaders = mb_substr($result, 0, $responseHeaderSize, '8bit');
             $result = mb_substr($result, $responseHeaderSize, mb_strlen($result), '8bit');
         } else {
             $responseHeaderSize = strlen($result) - curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD);
             $responseHeaders = substr($result, 0, $responseHeaderSize);
             $result = substr($result, $responseHeaderSize);
         }
     } else {
         $responseHeaders = '<response headers disabled>';
     }
     // $this->logger->debug("Request Headers \t: " . str_replace("\r\n", ", ", $requestHeaders));
     // $this->logger->debug(($data && $data != '' ? "Request Data\t\t: " . $data : "No Request Payload") . "\n" . str_repeat('-', 128) . "\n");
     // $this->logger->info("Response Status \t: " . $httpStatus);
     // $this->logger->debug("Response Headers\t: " . str_replace("\r\n", ", ", $responseHeaders));
     //Close the curl request
     curl_close($ch);
     // if ($httpStatus < 200 || $httpStatus >= 300) {
     //     $ex = new PayPalConnectionException(
     //         $this->httpConfig->getUrl(),
     //         "Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}.",
     //         $httpStatus
     //     );
     //     $ex->setData($result);
     //     $this->logger->error("Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}. " . $result);
     //     $this->logger->debug("\n\n" . str_repeat('=', 128) . "\n");
     //     throw $ex;
     // }
     $response = new Response($url, $httpStatus, $responseHeaders, $result);
     if ($this->logger) {
         $this->logger->debug('request -> ' . print_r(['url' => $strUrl, 'ctx' => $arrContentOptions, 'response' => $response->toString()], true));
     }
     return $response;
 }
 /**
  * Prepare the given value as a Response object.
  *
  * @param  mixed  $value
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function prepareResponse($value)
 {
     if (!$value instanceof SymfonyResponse) {
         $value = new Response($value);
     }
     return $value->prepare($this['request']);
 }