Response PHP Class Code Examples

This page contains top rated real world PHP examples of class Response extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: BatchMoveTest.php Project: rukzuk/rukzuk
0
 /**
  * @test
  * @group integration
  */
 public function batchmoveMediaShouldMoveMediasAsExpected()
 {
     $expectedSourceMediaCountBeforeMove = 4;
     $expectedSourceMediaCountAfterMove = 1;
     $expectedDestinationMediaCountAfterMove = 3;
     $sourceAlbumId = 'ALBUM-du0ecf0d-acc4-4fdb-dem4-72ebb08780bm-ALBUM';
     $destinationAlbumId = 'ALBUM-te1ecf03-acc4-4adb-add4-72ebb08780bm-ALBUM';
     $websiteId = 'SITE-te1ecf03-acc4-4adb-add4-72ebb08780bm-SITE';
     $mediaIds = array('MDB-bm5fg6ec-ai0f-4961-92bd-765d4aa581a0-MDB', 'MDB-bm5fg6ec-ai0f-4961-92bd-765d4aa581a1-MDB', 'MDB-bm5fg6ec-ai0f-4961-92bd-765d4aa581a2-MDB');
     $getAllRequestSource = sprintf('/media/getall/params/{"websiteId":"%s","albumid":"%s"}', $websiteId, $sourceAlbumId);
     $this->dispatch($getAllRequestSource);
     $response = $this->getResponseBody();
     $this->assertNotNull($response);
     $this->assertInternalType('string', $response);
     $response = new Response($response);
     $this->assertTrue($response->getSuccess());
     $responseData = $response->getData();
     $this->assertObjectHasAttribute('media', $responseData);
     $actualSourceMedias = $responseData->media;
     $this->assertInternalType('array', $actualSourceMedias);
     $this->assertSame($expectedSourceMediaCountBeforeMove, count($actualSourceMedias));
     $batchMoveRequestUri = sprintf('/media/batchmove/params/{"ids":%s,"websiteId":"%s","albumid":"%s"}', json_encode($mediaIds), $websiteId, $destinationAlbumId);
     $this->dispatch($batchMoveRequestUri);
     $response = $this->getResponseBody();
     $this->assertNotNull($response);
     $this->assertInternalType('string', $response);
     $response = new Response($response);
     $this->assertTrue($response->getSuccess());
     $getAllRequestDestination = sprintf('/media/getall/params/{"websiteId":"%s","albumid":"%s"}', $websiteId, $destinationAlbumId);
     $this->dispatch($getAllRequestDestination);
     $response = $this->getResponseBody();
     $this->assertNotNull($response);
     $this->assertInternalType('string', $response);
     $response = new Response($response);
     $this->assertTrue($response->getSuccess());
     $responseData = $response->getData();
     $this->assertObjectHasAttribute('media', $responseData);
     $actualDestinationMedias = $responseData->media;
     $this->assertInternalType('array', $actualDestinationMedias);
     $this->assertSame($expectedDestinationMediaCountAfterMove, count($actualDestinationMedias));
     foreach ($actualDestinationMedias as $media) {
         $this->assertInstanceOf('stdClass', $media);
         $this->assertObjectHasAttribute('albumId', $media);
         $this->assertSame($destinationAlbumId, $media->albumId);
         $this->assertObjectHasAttribute('id', $media);
         $this->assertContains($media->id, $mediaIds);
     }
     $getAllRequestSource = sprintf('/media/getall/params/{"websiteId":"%s","albumid":"%s"}', $websiteId, $sourceAlbumId);
     $this->dispatch($getAllRequestSource);
     $response = $this->getResponseBody();
     $this->assertNotNull($response);
     $this->assertInternalType('string', $response);
     $response = new Response($response);
     $this->assertTrue($response->getSuccess());
     $responseData = $response->getData();
     $this->assertObjectHasAttribute('media', $responseData);
     $actualSourceMediasAfterMove = $responseData->media;
     $this->assertInternalType('array', $actualSourceMediasAfterMove);
     $this->assertSame($expectedSourceMediaCountAfterMove, count($actualSourceMediasAfterMove));
 }
Example #2
Show file File: Md5ValidatorPluginTest.php Project: Frinstio/AlfredWorkflow.com
0
 public function testProperlyValidatesWhenUsingContentEncoding()
 {
     $plugin = new Md5ValidatorPlugin(true);
     $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/');
     $request->getEventDispatcher()->addSubscriber($plugin);
     // Content-MD5 is the MD5 hash of the canonical content after all
     // content-encoding has been applied.  Because cURL will automatically
     // decompress entity bodies, we need to re-compress it to calculate.
     $body = EntityBody::factory('abc');
     $body->compress();
     $hash = $body->getContentMd5();
     $body->uncompress();
     $response = new Response(200, array('Content-MD5' => $hash, 'Content-Encoding' => 'gzip'), 'abc');
     $request->dispatch('request.complete', array('response' => $response));
     $this->assertEquals('abc', $response->getBody(true));
     // Try again with an unknown encoding
     $response = new Response(200, array('Content-MD5' => $hash, 'Content-Encoding' => 'foobar'), 'abc');
     $request->dispatch('request.complete', array('response' => $response));
     // Try again with compress
     $body->compress('bzip2.compress');
     $response = new Response(200, array('Content-MD5' => $body->getContentMd5(), 'Content-Encoding' => 'compress'), 'abc');
     $request->dispatch('request.complete', array('response' => $response));
     // Try again with encoding and disabled content-encoding checks
     $request->getEventDispatcher()->removeSubscriber($plugin);
     $plugin = new Md5ValidatorPlugin(false);
     $request->getEventDispatcher()->addSubscriber($plugin);
     $request->dispatch('request.complete', array('response' => $response));
 }
Example #3
Show file File: ComandosLimb.php Project: ketu84/Limb
0
 private function apostadYa($endpoint, $request, $urlApi)
 {
     $this->log->debug("Obteniedo apostadYa");
     $time = microtime(true);
     $response = new Response($endpoint, $request->get_chat_id(), Response::TYPE_CHAT_ACTION);
     $response->chat_action = 'typing';
     $response->send();
     $emoji_pointing = Utils::convert_emoji(0x1f449);
     $emoji_r_arrow = Utils::convert_emoji(0x27a1);
     //Se obtiene la fase actual
     $jsonFaseActual = Utils::callApi($request, 'util/faseActual', $urlApi);
     $faseActual = json_decode($jsonFaseActual);
     $max_apostable = floatval($faseActual->importe);
     //Se obtiene la fecha del proximo partido
     $jsonFecha = Utils::callApi($request, 'util/fechaProxPartido/', $urlApi);
     $fecha = json_decode($jsonFecha);
     //Partidos de esa fecha
     $jsonPartidos = Utils::callApi($request, 'partidos/fecha/' . $fecha->fecha, $urlApi);
     $partidos = json_decode($jsonPartidos);
     //$text='*Faltan por apostar:*'.PHP_EOL;
     setlocale(LC_ALL, "es_ES");
     $text = '*' . strftime("%d %b", strtotime($fecha->fecha)) . ' - Faltan por apostar:*' . PHP_EOL . PHP_EOL;
     $insultar = false;
     foreach ($partidos as $partido) {
         //Apostado en ese partido
         $jsonApostantes = Utils::callApi($request, '/util/apostadoApostantePartido/' . $partido->id, $urlApi);
         $apostantes = json_decode($jsonApostantes);
         $arrApostantes = $partido->usuarios;
         foreach ($apostantes as $apostante) {
             if ($apostante->apostado == $max_apostable) {
                 $i = 0;
                 foreach ($arrApostantes as $apost) {
                     if ($apost->id == $apostante->idapostante) {
                         array_splice($arrApostantes, $i, 1);
                         continue;
                     }
                     $i++;
                 }
             }
         }
         if (sizeof($arrApostantes) > 0) {
             $text .= ' *' . $partido->local->nombre_corto . ' vs ' . $partido->visitante->nombre_corto . '* ' . substr($partido->hora, 0, 5) . PHP_EOL;
             $insultar = true;
             foreach ($arrApostantes as $apost) {
                 $text .= $emoji_pointing . $apost->nombre . PHP_EOL;
             }
         }
     }
     if ($insultar) {
         $text .= PHP_EOL . 'Apostad ya ' . Utils::getInsultoPlural();
     } else {
         $text .= "Han apostado todos" . PHP_EOL;
     }
     $response = new Response($endpoint, $request->get_chat_id(), Response::TYPE_TEXT);
     $response->text = $text;
     $response->markdown = true;
     $this->log->debug("Fin Obteniedo apostadYa (" . (microtime(true) - $time) . " s): ");
     return $response;
 }
Example #4
Show file File: linkeddataendpoint.php Project: neumann89/FUB-xml-project6-2013
0
function extractLinkedData($link, $origin)
{
    global $ep;
    // Wenn es die URL im Graph schon gibt, nichts machen, TODO besser updaten?
    if (graphContainsUrl($link)) {
        $res = new Response(null, "URL {$link} already visited, skip indexing");
        return res;
    } else {
        $parser = ARC2::getTurtleParser();
        //$data = $_POST['turtle'];
        $parser->parse($link);
        $triples = $parser->getTriples();
        // print_r($triples);
        // Wenn keine Tripel gefunden wurden
        if (count($triples) < 1) {
            $res = new Response(null, "URL {$link} contains no triples");
        } else {
            // in Datenbank einfügen
            $ep->insert($triples, $origin);
            //echo "<pre>";
            //print_r($triples);
            //echo "</pre>";
            $res = new Response(null, "URL {$link}: added " . count($triples) . " triples");
        }
        return $res;
    }
}
Example #5
Show file File: DynamicContactResource.php Project: cjvaz/expressomail
0
 /**
  * Remove um contato recente
  *
  * @license    http://www.gnu.org/copyleft/gpl.html GPL
  * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
  * @sponsor    Caixa Econômica Federal
  * @author     José Vicente Tezza Jr. 
  * @access     public
  * */
 function delete($request, $id)
 {
     $this->secured();
     //verificar se a preferencia de contatos dinamicos nao esta ativada
     if (!$this->isEnabledDynamicContacts(Config::me("uidNumber"))) {
         $response = new Response($request);
         $this->createException($request, $response, Response::UNAUTHORIZED, 'Resource unauthorized', 'disabled dynamic contacts preference');
         return $response;
     }
     $response = new Response($request);
     $response->addHeader('Content-type', 'aplication/json');
     $response->code = Response::NOCONTENT;
     try {
         //Verifica se o recurso existe
         $dinamicContact = Controller::read(array('concept' => 'dynamicContact', 'id' => $id));
         //Se existe o recurso
         if ($dinamicContact) {
             $delete = Controller::delete(array('concept' => 'dynamicContact', 'id' => $id));
             if (!$delete) {
                 $this->createException($request, $response, Response::INTERNALSERVERERROR, 'Internal Server Error', Controller::service('PostgreSQL')->error);
                 return $response;
             }
         } else {
             $this->createException($request, $response, Response::NOTFOUND, 'Bad request', 'Invalid data');
             return $response;
         }
     } catch (Exception $ex) {
         $this->createException($request, $response, Response::INTERNALSERVERERROR, 'Internal Server Error', 'Internal Server Error');
         return $response;
     }
     $response->body = json_encode(null);
     return $response;
 }
Example #6
Show file File: !15-9-15EguidesController.php Project: thebuggl-org/tests-buggl
0
 public function pdfPreviewAction(Request $request)
 {
     $isAdmin = $this->getRequest()->getSession()->has('has_admin_access');
     $user = $this->get('security.context')->getToken()->getUser();
     $filename = $request->get('filename');
     if (!$this->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') && !$isAdmin) {
         $response = new Response();
         $response->setStatusCode(404);
         return $response;
     }
     if (!$isAdmin) {
         $eguide = $this->getDoctrine()->getRepository('BugglMainBundle:EGuide')->findOneBy(array("pdfFilename" => $filename));
         $purchaseInfo = $this->getDoctrine()->getRepository('BugglMainBundle:PaypalPurchaseInfo')->findOneByBuyerAndEguide($user, $eguide);
         $purchased = !is_null($purchaseInfo) || $user != 'anon.' && $eguide->getLocalAuthor()->getId() == $user->getId();
         if (!$purchased) {
             $response = new Response();
             $response->setStatusCode(404);
             return $response;
         }
     }
     // echo $filename; exit;
     $request = $this->get('request');
     $path = $this->get('kernel')->getRootDir() . "/../web/uploads/eguide_pdf/";
     $content = file_get_contents($path . $filename);
     $response = new Response();
     //set headers
     $response->headers->set('Content-Type', 'application/pdf');
     // $response->headers->set('Content-Disposition', 'attachment;filename="'.$filename);
     $response->setContent($content);
     return $response;
 }
Example #7
Show file File: role.php Project: bladep911/respond
0
 /**
  * @method POST
  */
 function post()
 {
     // get token
     $token = Utilities::ValidateJWTToken();
     // check if token is not null
     if ($token != NULL) {
         try {
             parse_str($this->request->data, $request);
             // parse request
             $roleId = $request['roleId'];
             // remove role
             Role::Remove($roleId, $token->SiteId);
             // return a response
             $response = new Tonic\Response(Tonic\Response::OK);
             $response->contentType = 'text/html';
             $response->body = 'success';
             return $response;
         } catch (Exception $e) {
             $response = new Tonic\Response(Tonic\Response::BADREQUEST);
             $response->body = $e->getMessage();
             return $response;
         }
     } else {
         // unauthorized access
         return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
     }
 }
Example #8
Show file File: ApiKeyListener.php Project: tuandv2611/api-key-bundle
0
 /**
  * This interface must be implemented by firewall listeners.
  *
  * @param GetResponseEvent $event
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if (!$this->keyExtractor->hasKey($request)) {
         $response = new Response();
         $response->setStatusCode(401);
         $event->setResponse($response);
         return;
     }
     $apiKey = $this->keyExtractor->extractKey($request);
     $token = new ApiKeyUserToken();
     $token->setApiKey($apiKey);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         $token = $this->securityContext->getToken();
         if ($token instanceof ApiKeyUserToken && $token->getCredentials() == $apiKey) {
             $this->securityContext->setToken(null);
         }
         $message = $failed->getMessage();
     }
     $response = new Response();
     $response->setContent($message);
     $response->setStatusCode(403);
     $event->setResponse($response);
 }
Example #9
Show file File: HeaderAuthenticationListener.php Project: shakaran/powerline-server
0
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $apiToken = null;
     if ($request->headers->has('Token')) {
         $apiToken = new ApiToken();
         $apiToken->setToken($request->headers->get('Token'), 'user');
     } else {
         if ($request->headers->has('Authorization')) {
             $isTokenAuth = preg_match('/^Bearer type="(?P<type>\\S+?)"\\s+token="(?P<token>\\S+?)"$/i', $request->headers->get('Authorization'), $matches);
             if ($isTokenAuth) {
                 $apiToken = new ApiToken();
                 $apiToken->setToken($matches['token'], $matches['type']);
             }
         }
     }
     if (!$apiToken) {
         $response = new Response();
         $response->setStatusCode(401, 'Authentication required.');
         $event->setResponse($response);
         return;
     }
     try {
         $authToken = $this->authenticationManager->authenticate($apiToken);
         $this->securityContext->setToken($authToken);
     } catch (AuthenticationException $failed) {
         $response = new Response();
         $response->setStatusCode(401, 'Incorrect Token.');
         $event->setResponse($response);
     }
 }
Example #10
Show file File: DefaultRevalidationTest.php Project: KANU82/guzzle
0
 public function testHandles404RevalidationResponses()
 {
     $request = new Request('GET', 'http://foo.com');
     $request->setClient(new Client());
     $badResponse = new Response(404, array(), 'Oh no!');
     $badRequest = clone $request;
     $badRequest->setResponse($badResponse, true);
     $response = new Response(200, array(), 'foo');
     $plugin = new CachePlugin();
     $c = new ArrayCache();
     $c->save('foo', array(200, array(), 'foo'));
     $s = new DefaultCacheStorage(new DoctrineCacheAdapter($c));
     $k = new CallbackCacheKeyProvider(function () {
         return 'foo';
     });
     $rev = $this->getMockBuilder('Guzzle\\Plugin\\Cache\\DefaultRevalidation')->setConstructorArgs(array($k, $s, $plugin))->setMethods(array('createRevalidationRequest'))->getMock();
     $rev->expects($this->once())->method('createRevalidationRequest')->will($this->returnValue($badRequest));
     try {
         $rev->revalidate($request, $response);
         $this->fail('Should have thrown an exception');
     } catch (BadResponseException $e) {
         $this->assertSame($badResponse, $e->getResponse());
         $this->assertFalse($c->fetch('foo'));
     }
 }
Example #11
Show file File: WsseListener.php Project: snieditions/rest-api
0
 /**
  * {@inheritdoc}
  */
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $wsseRegex = '/UsernameToken Username="([^"]+)", PasswordDigest="([^"]+)", Nonce="([^"]+)", Created="([^"]+)"/';
     if (!$request->headers->has('x-wsse') || 1 !== preg_match($wsseRegex, $request->headers->get('x-wsse'), $matches)) {
         $response = new Response();
         $response->setStatusCode(Response::HTTP_FORBIDDEN);
         $event->setResponse($response);
         return;
     }
     $token = new WsseToken();
     $token->setUser($matches[1]);
     $token->digest = $matches[2];
     $token->nonce = $matches[3];
     $token->created = $matches[4];
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->tokenStorage->setToken($authToken);
         return;
     } catch (AuthenticationException $failed) {
         //TODO: LOG
     }
     // By default deny authorization
     $response = new Response();
     $response->setStatusCode(Response::HTTP_FORBIDDEN);
     $event->setResponse($response);
 }
Example #12
Show file File: ErrorEventTest.php Project: anthrotech/laravel_sample
0
 public function testInterceptsWithEvent()
 {
     $client = new Client();
     $request = new Request('GET', '/');
     $response = new Response(404);
     $transaction = new Transaction($client, $request);
     $except = new RequestException('foo', $request, $response);
     $event = new ErrorEvent($transaction, $except);
     $event->throwImmediately(true);
     $this->assertTrue($except->getThrowImmediately());
     $event->throwImmediately(false);
     $this->assertFalse($except->getThrowImmediately());
     $this->assertSame($except, $event->getException());
     $this->assertSame($response, $event->getResponse());
     $this->assertSame($request, $event->getRequest());
     $res = null;
     $request->getEmitter()->on('complete', function ($e) use(&$res) {
         $res = $e;
     });
     $good = new Response(200);
     $event->intercept($good);
     $this->assertTrue($event->isPropagationStopped());
     $this->assertSame($res->getClient(), $event->getClient());
     $this->assertSame($good, $res->getResponse());
 }
Example #13
Show file File: BridgeExceptionSubscriber.php Project: luisbrito/Phraseanet
0
 public function onSilexError(GetResponseForExceptionEvent $event)
 {
     if (!$event->getException() instanceof \Bridge_Exception) {
         return;
     }
     $e = $event->getException();
     $request = $event->getRequest();
     $params = ['account' => null, 'elements' => [], 'message' => $e->getMessage(), 'error_message' => null, 'notice_message' => null, 'file' => $e->getFile(), 'line' => $e->getLine(), 'r_method' => $request->getMethod(), 'r_action' => $request->getRequestUri(), 'r_parameters' => $request->getMethod() == 'GET' ? [] : $request->request->all()];
     if ($e instanceof \Bridge_Exception_ApiConnectorNotConfigured) {
         $params = array_replace($params, ['account' => $this->app['bridge.account']]);
         $response = new Response($this->app['twig']->render('/prod/actions/Bridge/notconfigured.html.twig', $params), 200, ['X-Status-Code' => 200]);
     } elseif ($e instanceof \Bridge_Exception_ApiConnectorNotConnected) {
         $params = array_replace($params, ['account' => $this->app['bridge.account']]);
         $response = new Response($this->app['twig']->render('/prod/actions/Bridge/disconnected.html.twig', $params), 200, ['X-Status-Code' => 200]);
     } elseif ($e instanceof \Bridge_Exception_ApiConnectorAccessTokenFailed) {
         $params = array_replace($params, ['account' => $this->app['bridge.account']]);
         $response = new Response($this->app['twig']->render('/prod/actions/Bridge/disconnected.html.twig', $params), 200, ['X-Status-Code' => 200]);
     } elseif ($e instanceof \Bridge_Exception_ApiDisabled) {
         $params = array_replace($params, ['api' => $e->get_api()]);
         $response = new Response($this->app['twig']->render('/prod/actions/Bridge/deactivated.html.twig', $params), 200, ['X-Status-Code' => 200]);
     } else {
         $response = new Response($this->app['twig']->render('/prod/actions/Bridge/error.html.twig', $params), 200, ['X-Status-Code' => 200]);
     }
     $response->headers->set('Phrasea-StatusCode', 200);
     $event->setResponse($response);
 }
Example #14
Show file File: Client.php Project: chujiu/phpssdb
0
 public function __call($cmd, $params = array())
 {
     $cmd = strtolower($cmd);
     if ($this->async_auth_password !== null) {
         $pass = $this->async_auth_password;
         $this->async_auth_password = null;
         $auth = $this->__call('auth', array($pass));
         if ($auth->data !== true) {
             throw new \Exception("Authentication failed");
         }
     }
     if ($this->batch_mode) {
         $this->batch_cmds[] = array($cmd, $params);
         return $this;
     }
     try {
         if ($this->send_req($cmd, $params) === false) {
             $resp = new Response('error', 'send error');
         } else {
             $resp = $this->recv_resp($cmd, $params);
         }
     } catch (Exception $e) {
         if ($this->_easy) {
             throw $e;
         } else {
             $resp = new Response('error', $e->getMessage());
         }
     }
     if ($resp->code == 'noauth') {
         $msg = $resp->message;
         throw new \Exception($msg);
     }
     $resp = $this->check_easy_resp($cmd, $resp);
     return $resp;
 }
Example #15
Show file File: DeleteTest.php Project: rukzuk/rukzuk
0
 /**
  * @test
  * @group integration
  */
 public function deletePageShouldBeRejectedWhenAuthenticatedUserHasNoPagesPrivileges()
 {
     $params = array('runId' => 'CMSRUNID-00000000-0000-0000-0000-000000000001-CMSRUNID', 'id' => 'PAGE-de45d096-00np-4ab5-895b-92e7a4ba3703-PAGE', 'websiteId' => 'SITE-de3dfb9f-362a-4b89-a084-53c4696473f8-SITE');
     $paramsAsJson = json_encode($params);
     $this->dispatch('page/getbyid/params/' . $paramsAsJson);
     $response = $this->getResponseBody();
     $response = new Response($response);
     $this->assertTrue($response->getSuccess());
     $responseData = $response->getData();
     $this->assertObjectHasAttribute('id', $responseData);
     $this->assertSame($params['id'], $responseData->id);
     $this->assertObjectHasAttribute('websiteId', $responseData);
     $this->assertSame($params['websiteId'], $responseData->websiteId);
     $userName = 'delete.page.no.page.privileges@sbcms.de';
     $userPassword = 'TEST09';
     $this->assertSuccessfulLogin($userName, $userPassword);
     $this->activateGroupCheck();
     $this->dispatch('page/delete/params/' . $paramsAsJson);
     $this->deactivateGroupCheck();
     $response = $this->getResponseBody();
     $response = new Response($response);
     $this->assertFalse($response->getSuccess());
     $responseError = $response->getError();
     $this->assertSame(7, $responseError[0]->code);
     $this->assertNull($response->getData());
     $this->dispatch('page/getbyid/params/' . $paramsAsJson);
     $response = $this->getResponseBody();
     $response = new Response($response);
     $this->assertTrue($response->getSuccess());
     $responseData = $response->getData();
     $this->assertObjectHasAttribute('id', $responseData);
     $this->assertSame($params['id'], $responseData->id);
     $this->assertObjectHasAttribute('websiteId', $responseData);
     $this->assertSame($params['websiteId'], $responseData->websiteId);
 }
Example #16
Show file File: EstacionesController.php Project: matiasraies/Symfony2Inta
0
 public function listarAction(Request $request)
 {
     if ($request->headers->get('Token') != "sipas-inta-2016") {
         return new Response("NO AUTORIZADO....");
     }
     switch ($request->query->get('clase')) {
         case 'estaciones':
             $list = $this->getDoctrine()->getManager()->getRepository('ServiceBundle:EstacionesMet')->getListEstMetAll();
             $response = new Response(json_encode($list));
             break;
         case 'list-bol-meses-info':
             $idEstacion = $request->query->get('idEstacion');
             $list = $this->getDoctrine()->getManager()->getRepository('ServiceBundle:MeteoroInfo')->getListBolMesesAniosByIdEstacion($idEstacion);
             $response = new Response(json_encode($list));
             break;
         case 'info-bol-meses':
             break;
         case 'list-bol-mes-anio-info':
             $idEstacion = $request->query->get('idEstacion');
             $mes = $request->query->get('mes');
             $anio = $request->query->get('anio');
             $listmet = $this->getDoctrine()->getManager()->getRepository('ServiceBundle:MeteoroInfo')->getListByIdEstacion($idEstacion, $mes, $anio);
             $response = new Response(json_encode($listmet));
             break;
         default:
             $response = new Response("NO RESPONDE EL POST....");
     }
     return $response;
 }
Example #17
Show file File: EditTemplateSnippetControllerTestCase.php Project: rukzuk/rukzuk
0
 /**
  * @test
  * @group integration
  * @dataProvider editDataProvider
  */
 public function editShouldAlterTemplateSnippetAsExpected($editParams, $expectedData)
 {
     $editParams['runId'] = $this->runId;
     $editParams['websiteId'] = $this->websiteId;
     $userName = 'controller.templatesnippet.update@sbcms.de';
     $userPassword = 'TEST01';
     $this->assertSuccessfulLogin($userName, $userPassword);
     $getAllUrl = sprintf('/templatesnippet/getall/params/{"websiteid":"%s"}', $editParams['websiteId']);
     $this->dispatch($getAllUrl);
     $response = $this->getResponseBody();
     $this->assertNotNull($response);
     $this->assertInternalType('string', $response);
     $response = new Response($response);
     $this->assertTrue($response->getSuccess());
     $responseData = $response->getData();
     $this->assertObjectHasAttribute('templatesnippets', $responseData);
     $this->assertInternalType('array', $responseData->templatesnippets);
     $this->assertGreaterThan(0, count($responseData->templatesnippets));
     $templateSnippetCountBeforeUpdate = count($responseData->templatesnippets);
     $dataBeforeUpdate = null;
     foreach ($responseData->templatesnippets as $templateSnippet) {
         $this->assertInstanceOf('stdClass', $templateSnippet);
         $this->assertObjectHasAttribute('id', $templateSnippet);
         if ($templateSnippet->id === $editParams['id']) {
             $dataBeforeUpdate = get_object_vars($templateSnippet);
         }
     }
     $request = sprintf($this->serviceUrl, json_encode($editParams));
     $this->dispatch($request);
     $response = $this->getResponseBody();
     $this->assertNotNull($response);
     $this->assertInternalType('string', $response);
     $response = new Response($response);
     $this->assertTrue($response->getSuccess());
     $this->dispatch($getAllUrl);
     $response = $this->getResponseBody();
     $this->assertNotNull($response);
     $this->assertInternalType('string', $response);
     $response = new Response($response);
     $this->assertTrue($response->getSuccess());
     $responseData = $response->getData();
     $this->assertObjectHasAttribute('templatesnippets', $responseData);
     $this->assertInternalType('array', $responseData->templatesnippets);
     $this->assertSame($templateSnippetCountBeforeUpdate, count($responseData->templatesnippets));
     $updatedTemplateSnippet = null;
     foreach ($responseData->templatesnippets as $templateSnippet) {
         $this->assertInstanceOf('stdClass', $templateSnippet);
         $this->assertObjectHasAttribute('id', $templateSnippet);
         if ($templateSnippet->id === $editParams['id']) {
             $updatedTemplateSnippet = get_object_vars($templateSnippet);
         }
     }
     foreach ($updatedTemplateSnippet as $key => $value) {
         if (isset($expectedData[$key])) {
             $this->assertEquals($expectedData[$key], $value);
         } else {
             $this->assertEquals($dataBeforeUpdate[$key], $value);
         }
     }
 }
Example #18
Show file File: NewsController.php Project: Jujuwar/bruminator2.0
0
 /**
  * @Route("/news/ajax/edit", name="admin_news_ajax_edit")
  */
 public function ajaxEditAction(Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         try {
             $em = $this->getDoctrine()->getManager();
             $news = $em->getRepository('MainBundle:News')->findOneBy(array('id' => $request->get('id')));
             $news->setTitle($request->get('title'));
             $news->setMessage($request->get('message'));
             $news->setDate(empty($request->get('date')) ? new \DateTime() : \DateTime::createFromFormat('d/m/Y H:i', $request->get('date')));
             $errors = $this->get('validator')->validate($news);
             if (count($errors) == 0) {
                 $em->flush();
                 $response = new Response(json_encode(array('status' => 'ok', 'return' => $this->render('AdminBundle:News:newsRow.html.twig', array('news' => $news))->getContent())));
             } else {
                 $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Impossible de modifier la news', 'errors' => $this->render('AdminBundle:News:validation.html.twig', array('errors' => $errors))->getContent(), 'debug' => $errors)));
             }
         } catch (\Exception $e) {
             $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Une erreur inconnue s\'est produite', 'debug' => $e->getMessage())));
         }
         $response->headers->set('Content-Type', 'application/json');
         return $response;
     }
     $response = new Response(json_encode(array('status' => 'ko', 'message' => 'Accès refusé', 'debug' => 'Bad request')));
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
Example #19
Show file File: Theme.php Project: Silwereth/core
0
 /**
  * Display the page output.
  *
  *
  * @return Response
  */
 public function themefooter(Response $response = null)
 {
     // end output buffering and get module output
     if (null === $response) {
         $response = new Response();
         $maincontent = ob_get_contents();
         ob_end_clean();
     }
     $maincontent = $response->getContent();
     // add the module wrapper
     if (!$this->themeinfo['system'] && (bool) $this->themeconfig['modulewrapper'] && $this->toplevelmodule) {
         $maincontent = '<div id="z-maincontent" class="' . ($this->homepage ? 'z-homepage ' : '') . 'z-module-' . DataUtil::formatForDisplay(strtolower($this->toplevelmodule)) . ' ' . $this->type . ' ' . $this->func . '">' . $maincontent . '</div>';
     }
     $event = new \Zikula\Core\Event\GenericEvent($this, array(), $maincontent);
     $maincontent = $this->eventManager->dispatch('theme.prefetch', $event)->getData();
     $this->cache_id = md5($this->cache_id . '|' . $maincontent);
     // Assign the main content area to the template engine
     $this->assign('maincontent', $maincontent);
     // render the page using the correct template
     $output = $this->fetch($this->themeconfig['page'], $this->cache_id);
     $event = new \Zikula\Core\Event\GenericEvent($this, array(), $output);
     $content = $this->eventManager->dispatch('theme.postfetch', $event)->getData();
     $response->setContent($content);
     return $response;
 }
Example #20
Show file File: ResponseTest.php Project: DonaldNgai/PHPAuthentication
0
 public function testIsServerError()
 {
     $r1 = new \Slim\Http\Response();
     $r2 = new \Slim\Http\Response();
     $r1->setStatus(500);
     $r2->setStatus(400);
     $this->assertTrue($r1->isServerError());
     $this->assertFalse($r2->isServerError());
 }
Frequently Used Methods