create() public static method

Example: return Response::create($body, 200) ->setSharedMaxAge(300);
public static create ( mixed $content = '', integer $status = 200, array $headers = [] ) : Response
$content mixed The response content, see setContent()
$status integer The response status code
$headers array An array of response headers
return Response
 public function __invoke(Request $request)
 {
     if ($this->service->delete($request->getRequestURI()) === false) {
         throw new ServiceUnavailableHttpException(null, "Failed to delete resource");
     }
     return Response::create("", Response::HTTP_NO_CONTENT);
 }
 /**
  * Check Product existence for a given ID
  *
  * This API method will check if the given ID matches an existing product.
  *
  * @api_public
  * @param Request $request
  * @return Response
  */
 public function checkIdExistsAction(Request $request)
 {
     $id = $request->attributes->get('id');
     // TODO: check in DB if product ID exists
     return Response::create()->setStatusCode($id > 42 ? 404 : 200);
     // or 404 if not found.
 }
Exemplo n.º 3
0
 /** @inheritdoc */
 public function __construct(array $settings = [])
 {
     $this->_request = IfSet::get($settings, 'request', Request::createFromGlobals());
     $this->_response = IfSet::get($settings, 'response', Response::create());
     $this->_container = null;
     parent::__construct($settings);
 }
Exemplo n.º 4
0
 public function execute($request)
 {
     //generate cache key
     $key = $this->generateCacheKey($request);
     //check if exist in cache
     //if exist return
     if ($content = $this->cache->get($key)) {
         $response = Response::create($content, 200, ['Content-Type' => 'application/json']);
     } else {
         $token = $this->getToken();
         $request->headers->set('Authorization', "Bearer {$token}");
         //do request
         $forward_url = $this->api_base . $request->getPathInfo();
         $response = $this->proxy->forward($request)->to($forward_url);
         //token expired refresh and try again
         if ($response->getStatusCode() == 401) {
             $token = $this->generateToken();
             $request->headers->set('Authorization', "Bearer {$token}");
             $response = $this->proxy->forward($request)->to($forward_url);
         }
         //if status is 200 save in cache
         if ($response->getStatusCode() == 200) {
             $this->cache->set($key, $response->getContent());
             $this->cache->expire($key, 3600 * 12);
             //clear in 12 hours
         }
     }
     //output response
     return $response;
 }
Exemplo n.º 5
0
 /**
  * Настраиваем зависимости фреймворка.
  */
 protected function setDefaultDependencies()
 {
     $this->container->set(Request::class, function (Container $c) {
         return Request::createFromGlobals();
     });
     $this->container->set(Response::class, function (Container $c) {
         return Response::create();
     });
     $this->container->set(RouteParser::class, function (Container $c) {
         return new RouteParser\Std();
     });
     $this->container->set(RouteCollector::class, function (Container $c) {
         /** @var RouteParser $routeParser */
         $routeParser = $c->get(RouteParser::class);
         return new RouteCollector($routeParser, new RouteDataGenerator());
     });
     $this->container->set(RouteDispatcher::class, function (Container $c) {
         /** @var RouteCollector $router */
         $router = $c->get(RouteCollector::class);
         return new RouteDispatcher($router->getData());
     });
     $this->container->set(UrlGenerator::class, function (Container $c) {
         /** @var RouteCollector $routeCollector */
         $routeCollector = $c->get(RouteCollector::class);
         /** @var RouteParser $routeParser */
         $routeParser = $c->get(RouteParser::class);
         return new UrlGenerator($routeCollector, $routeParser);
     });
 }
Exemplo n.º 6
0
    public function onQuickUploadResponse(FilterResponseEvent $event)
    {
        $request = $event->getRequest();
        if ($request->get('responseType') === 'json') {
            return;
        }
        $response = $event->getResponse();
        $funcNum = $request->get('CKEditorFuncNum');
        $funcNum = preg_replace('/[^0-9]/', '', $funcNum);
        if ($response instanceof JsonResponse) {
            $responseData = $response->getData();
            $fileUrl = isset($responseData['url']) ? $responseData['url'] : '';
            $errorMessage = isset($responseData['error']['message']) ? $responseData['error']['message'] : '';
            ob_start();
            ?>
<script type="text/javascript">
    window.parent.CKEDITOR.tools.callFunction(<?php 
            echo json_encode($funcNum);
            ?>
, <?php 
            echo json_encode($fileUrl);
            ?>
, <?php 
            echo json_encode($errorMessage);
            ?>
);
</script>
            <?php 
            $event->setResponse(Response::create(ob_get_clean()));
        }
    }
Exemplo n.º 7
0
 public function testCreate()
 {
     $response = Response::create('foo', 301, array('Foo' => 'bar'));
     $this->assertInstanceOf('Symfony\\Component\\HttpFoundation\\Response', $response);
     $this->assertEquals(301, $response->getStatusCode());
     $this->assertEquals('bar', $response->headers->get('foo'));
 }
    public function getRedirectResponse()
    {
        if (!$this instanceof RedirectResponseInterface || !$this->isRedirect()) {
            throw new RuntimeException('This response does not support redirection.');
        }
        if ('GET' === $this->getRedirectMethod()) {
            return HttpRedirectResponse::create($this->getRedirectUrl());
        } elseif ('POST' === $this->getRedirectMethod()) {
            $hiddenFields = '';
            foreach ($this->getRedirectData() as $key => $value) {
                $hiddenFields .= sprintf('<input type="hidden" name="%1$s" value="%2$s" />', htmlentities($key, ENT_QUOTES, 'UTF-8', false), htmlentities($value, ENT_QUOTES, 'UTF-8', false)) . "\n";
            }
            $output = '<!DOCTYPE html>
<html>
    <head>
        <title>Redirecting...</title>
    </head>
    <body onload="document.forms[0].submit();">
        <form action="%1$s" method="post">
            <p>Redirecting to payment page...</p>
            <p>
                %2$s
                <input type="submit" value="Continue" />
            </p>
        </form>
    </body>
</html>';
            $output = sprintf($output, htmlentities($this->getRedirectUrl(), ENT_QUOTES, 'UTF-8', false), $hiddenFields);
            return HttpResponse::create($output);
        }
        throw new RuntimeException('Invalid redirect method "' . $this->getRedirectMethod() . '".');
    }
 public function createResponse($exception, $onlyHtmlBodyContent = false)
 {
     if (!$exception instanceof FlattenException) {
         $exception = FlattenException::create($exception);
     }
     return Response::create($this->render($exception, $onlyHtmlBodyContent), $exception->getStatusCode(), $exception->getHeaders())->setCharset($this->charset);
 }
Exemplo n.º 10
0
 /**
  * {@inheritdoc}
  * @param Request $request
  * @return Response
  */
 public function onLogoutSuccess(Request $request)
 {
     if ($accessToken = $this->accessTokenManager->findTokenByToken($request->get('access_token'))) {
         $this->accessTokenManager->deleteToken($accessToken);
     }
     if ($accessToken = $this->accessTokenManager->findTokenByToken($request->cookies->get('access_token'))) {
         $this->accessTokenManager->deleteToken($accessToken);
     }
     if ($accessToken = $request->server->get('HTTP_AUTHORIZATION')) {
         if ($accessTokenObj = $this->accessTokenManager->findTokenByToken(substr($accessToken, 7))) {
             $this->accessTokenManager->deleteToken($accessTokenObj);
         }
     }
     if ($refreshToken = $this->refreshTokenManager->findTokenByToken($request->cookies->get('refresh_token'))) {
         $this->refreshTokenManager->deleteToken($refreshToken);
     }
     $request->headers->remove('Authorization');
     $request->server->remove('HTTP_AUTHORIZATION');
     $request->cookies->remove('access_token');
     $request->cookies->remove('refresh_token');
     $response = Response::create();
     $response->headers->clearCookie('access_token');
     $response->headers->clearCookie('refresh_token');
     return $response;
 }
Exemplo n.º 11
0
 /**
  * @param Request $request
  * @param int     $id
  *
  * @return Response
  * @throws \Exception
  */
 public function createAction(Request $request, $id = 0)
 {
     $repository = $this->getRepository();
     if (!$repository instanceof CrudRepositoryInterface) {
         throw new \Exception("Repository class must be implemented CrudRepositoryInterface");
     }
     $viewData = [];
     $entity = $repository->find($id);
     if (!$entity) {
         $entity = $repository->createEntity();
     }
     $form = $this->getCreateForm($entity);
     $form->handleRequest($request);
     if ($form->isSubmitted() && $request->getMethod() === "POST") {
         if ($form->isValid()) {
             $em = $this->getDoctrine()->getManager();
             $em->persist($entity);
             $em->flush();
             return RedirectResponse::create($this->getRouter());
         } else {
             return Response::create($form->getErrorsAsString(), 406);
         }
     }
     $viewData['form'] = $form->createView();
     $response = $this->render($this->createView, $viewData);
     return $response;
 }
Exemplo n.º 12
0
 public function testResponseObjectConstructionWithCustomResponse()
 {
     $representation = new Json();
     $symResponse = \Symfony\Component\HttpFoundation\Response::create();
     $response = new Response($representation, $symResponse);
     $this->assertEquals($representation, $response->getRepresentation());
 }
 public function checkSemaphoreAction(Request $request)
 {
     // TODO !5: comportement de cette action à voir quand rabbitMQ arrivera
     //dump($request->attributes->get('footprint'));
     return Response::create('', 202, []);
     // '', 409, ['ps_status_text' => 'This request is already in working queue.']);
 }
Exemplo n.º 14
0
 /**
  * @covers \Colonel\HttpKernel::handle
  * @covers \Colonel\HttpKernel::run
  */
 public function test_NoRouteStrategyException_is_thrown()
 {
     $this->setExpectedException(NoRouteStrategyDefinedException::class);
     new HttpKernel(['debug' => false, 'services' => ['di' => []], 'routes' => ['test_group' => ['test_route' => ['pattern' => '/', 'controller' => function () {
         return Response::create('<h1>It works!</h1>', 200);
     }, 'method' => 'GET']]]]);
 }
Exemplo n.º 15
0
 public function terminate()
 {
     if ($this->booted) {
         $response = Response::create('');
         $this->kernel->terminate($this->request, $response);
     }
 }
Exemplo n.º 16
0
 /**
  * @test
  */
 public function filter_adds_location_as_xheader()
 {
     $url = 'http://www.rebuy.de/';
     $response = Response::create('', 200, [RemoveLocationFilter::LOCATION => $url]);
     $this->filter->filter($response);
     $this->assertEquals($url, $response->headers->get('X-Proxy-Location'));
 }
Exemplo n.º 17
0
 protected function convertExceptionToResponse(Exception $e)
 {
     $e = FlattenException::create($e);
     $handler = new KommerceExceptionHandler(config('app.debug'));
     $decorated = $this->decorate($handler->getContent($e), $handler->getStylesheet($e));
     return SymfonyResponse::create($decorated, $e->getStatusCode(), $e->getHeaders());
 }
Exemplo n.º 18
0
 /**
  * Render an exception into an HTTP response.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Exception  $e
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function render($request, Exception $e)
 {
     $e = FlattenException::create($e);
     $handler = new SymfonyExceptionHandler(env('APP_DEBUG', false));
     $decorated = $this->decorate($handler->getContent($e), $handler->getStylesheet($e));
     return Response::create($decorated, $e->getStatusCode(), $e->getHeaders());
 }
Exemplo n.º 19
0
 public function wrapResponse($response)
 {
     if (!$response instanceof Response) {
         $response = is_scalar($response) ? Response::create($response) : JsonResponse::create($response);
     }
     return $response;
 }
Exemplo n.º 20
0
 protected function handleWithSymfony(Exception $exception)
 {
     if (!$exception instanceof FlattenException) {
         $exception = FlattenException::create($exception);
     }
     $handler = new ExceptionHandler($this->debug);
     return Response::create($handler->getHtml($exception), $exception->getStatusCode(), $exception->getHeaders());
 }
Exemplo n.º 21
0
 /**
  * @Route("/goals/delete", name="goal_delete")
  */
 public function deleteAction(Request $request)
 {
     $client = new Client(['base_uri' => 'https://api-metrika.yandex.ru', 'verify' => false]);
     $goalId = json_decode($request->getContent());
     $goalId = $goalId->goal->id;
     $response = $client->request('DELETE', "management/v1/counter/35120570/goal/{$goalId}", ['query' => ['oauth_token' => '70dc8f685eb04c9c8ffe5cd58814440d']]);
     return Response::create($response->getBody(), 200, ['Content-type' => 'text/x-json; charset=UTF-8']);
 }
Exemplo n.º 22
0
 public function getRedirectResponse()
 {
     if (!$this->isRedirect()) {
         throw new RuntimeException('This response does not support redirection.');
     }
     $output = json_encode($this->getData());
     return HttpResponse::create($output);
 }
 /**
  * It should not pass on the terminate request when using a non-terminable kernel.
  */
 public function testTerminateNonTerminable()
 {
     $request = Request::create('/');
     $response = Response::create();
     $this->terminableKernel->terminate($request, $response)->shouldNotBeCalled();
     $taggingKernel = $this->createKernel($this->kernel->reveal());
     $taggingKernel->terminate($request, $response);
 }
 public function promiseAction(Request $request)
 {
     $secs = intval($request->attributes->get("secs"));
     $deferred = new Deferred();
     $this->loop->addTimer($secs, function () use($secs, $deferred) {
         $deferred->resolve(Response::create("{$secs} seconds later...\n"));
     });
     return $deferred->promise();
 }
Exemplo n.º 25
0
 public function render($request, Exception $e)
 {
     if (!method_exists($e, 'getHttpCode')) {
         $exc = new FlattenException();
     } else {
         $exc = $e;
     }
     return Response::create(ErrorHandler::exceptionError($e), $exc->getHttpCode())->setCharset('utf-8');
 }
Exemplo n.º 26
0
 protected function setUp()
 {
     $this->em = $this->getMockBuilder('Doctrine\\ORM\\EntityManager')->disableOriginalConstructor()->getMock();
     $this->listener = new CreateConfigListener($this->em, 'baggy', 20, 50, 'fr', 1);
     $this->dispatcher = new EventDispatcher();
     $this->dispatcher->addSubscriber($this->listener);
     $this->request = Request::create('/');
     $this->response = Response::create();
 }
Exemplo n.º 27
0
 /**
  * @test
  */
 public function to_sends_request()
 {
     $request = Request::createFromGlobals();
     $url = 'http://www.example.com';
     $adapter = $this->getMockBuilder('\\Proxy\\Adapter\\Dummy\\DummyAdapter')->getMock();
     $adapter->expects($this->once())->method('send')->with($request, $url)->willReturn(Response::create());
     $proxy = new Proxy($adapter);
     $proxy->forward($request)->to($url);
 }
 public function getFileAction($fileId)
 {
     try {
         $object = $this->fileUploaderDocumentRepo->findOneById($fileId);
     } catch (\Exception $e) {
         throw new NotFoundHttpException('The requested file could not be found');
     }
     return Response::create(stream_get_contents($object->getFile()), 200, ['Content-Type' => 'application/octet-stream', 'Content-Disposition' => 'attachment; filename="' . $object->getName() . '"', 'Content-Length' => $object->getSize(), 'Content-Transfer-Encoding' => 'binary', 'Expires' => 0, 'Cache-Control' => 'must-revalidate', 'Pragma' => 'public']);
 }
Exemplo n.º 29
0
 public function output($identifier)
 {
     if ($feed = PageFeed::getByHandle($identifier)) {
         if ($xml = $feed->getOutput($this->request)) {
             return Response::create($xml, 200, array('Content-Type' => 'text/xml'));
         }
     }
     return Response::create('', 404);
 }
 /**
  * @param \Symfony\Component\HttpFoundation\Request $request
  *
  * @return \Symfony\Component\HttpFoundation\Response
  * @throws \InvalidArgumentException
  */
 public function getSwaggerResponse(Request $request)
 {
     $swagger = $this->getSwagger();
     $response = Response::create($swagger, Response::HTTP_OK, ['Content-Type' => 'application/json']);
     $response->setCache($this->cacheConfig);
     $response->setEtag(md5($swagger));
     $response->isNotModified($request);
     return $response;
 }