/** * @testdox Creates paginator via paginator service using request parameters. * @dataProvider providePaginatorCreationData * * * @param $paginatorName * @param $params * @param $defaultParams * @param $usePostParams * @param $expect */ public function testPaginatorCreation($paginatorName, $params, $defaultParams, $usePostParams, $expect) { if ($defaultParams) { $options = array_merge($params, $defaultParams); } else { $options = $params; } $request = new Request(); if ($usePostParams) { $request->setPost(new Parameters($params)); } else { $request->setQuery(new Parameters($params)); } $paginator = $this->getMockBuilder('\\Zend\\Paginator\\Paginator')->disableOriginalConstructor()->getMock(); $paginator->expects($this->once())->method('setCurrentPageNumber')->with($expect['page'])->will($this->returnSelf()); $paginator->expects($this->once())->method('setItemCountPerPage')->with($expect['count'])->will($this->returnSelf()); $paginator->expects($this->once())->method('setPageRange')->with($expect['range'])->will($this->returnSelf()); $paginators = $this->getMockBuilder('\\Core\\Paginator\\PaginatorService')->disableOriginalConstructor()->getMock(); $paginators->expects($this->once())->method('get')->with($paginatorName, $options)->willReturn($paginator); $sm = $this->getMockBuilder('\\Zend\\ServiceManager\\ServiceManager')->disableOriginalConstructor()->getMock(); $event = $this->getMockBuilder(CreatePaginatorEvent::class)->disableOriginalConstructor()->getMock(); $em = $this->getMockBuilder(EventManager::class)->disableOriginalConstructor()->setMethods(['getEvent', 'trigger'])->getMock(); $sm->expects($this->exactly(2))->method('get')->withConsecutive(['Core/PaginatorService'], ['Core/CreatePaginator/Events'])->willReturnOnConsecutiveCalls($paginators, $em); // check if event create paginator is triggered $em->expects($this->once())->method('getEvent')->with(CreatePaginator::EVENT_CREATE_PAGINATOR)->willReturn($event); $em->expects($this->once())->method('trigger')->with($event); $controller = $this->getMockBuilder('\\Zend\\Mvc\\Controller\\AbstractActionController')->setMethods(['getServiceLocator', 'getRequest'])->getMockForAbstractClass(); $controller->expects($this->once())->method('getRequest')->willReturn($request); $target = new CreatePaginator($sm); $target->setController($controller); $pager = false === $defaultParams ? $target($paginatorName, $usePostParams) : $target($paginatorName, $defaultParams, $usePostParams); $this->assertSame($paginator, $pager); }
/** * @covers Application\Controller\BusstopController::indexAction * @dataProvider indexValueProvider */ public function testIndexAction($paramArray, $count, $totalCount) { $queryBuilder = $this->getMock('Doctrine\\ORM\\QueryBuilder', array(), array(), '', false); $entityManager = $this->getMock('Doctrine\\ORM\\EntityManager', array(), array(), '', false); $entityManager->expects($this->any())->method('createQueryBuilder')->will($this->returnValue($queryBuilder)); $this->controller->setEntityManager($entityManager); $queryBuilder->expects($this->any())->method('select')->will($this->returnSelf()); $queryBuilder->expects($this->any())->method('from')->will($this->returnSelf()); $queryBuilder->expects($this->any())->method('andWhere')->will($this->returnSelf()); $queryBuilder->expects($this->any())->method('setParameter')->will($this->returnSelf()); $queryBuilder->expects($this->any())->method('setMaxResults')->will($this->returnSelf()); $queryBuilder->expects($this->any())->method('setFirstResult')->will($this->returnSelf()); $query = $this->getMockBuilder('Doctrine\\ORM\\AbstractQuery')->setMethods(array('getResult', 'getSingleScalarResult'))->disableOriginalConstructor()->getMockForAbstractClass(); $queryBuilder->expects($this->any())->method('getQuery')->will($this->returnValue($query)); $busstop = new BusStop(); $busstop->setLatitude(52)->setLongitude(5); $results = array(); if ($count) { $results = array_fill(0, $count, $busstop); } $query->expects($this->once())->method('getResult')->will($this->returnValue($results)); $query->expects($this->once())->method('getSingleScalarResult')->will($this->returnValue($totalCount)); $this->request->setQuery(new Parameters($paramArray)); $this->routeMatch->setParam('action', 'index'); $result = $this->controller->dispatch($this->request); $response = $this->controller->getResponse(); $this->assertEquals(200, $response->getStatusCode()); $this->assertInstanceOf('Zend\\View\\Model\\ViewModel', $result); }
public function testJavascriptAcceptHeaderSelectsJsonStrategyAndSetsJsonpCallback() { $request = new HttpRequest(); $request->getHeaders()->addHeaderLine('Accept', 'application/javascript'); $request->setQuery(new Parameters(array('callback' => 'foo'))); $this->event->setRequest($request); $result = $this->strategy->selectRenderer($this->event); $this->assertSame($this->renderer, $result); $this->assertTrue($result->hasJsonpCallback()); }
public function testParameterRetrievalDefaultValue() { $request = new Request(); $p = new \Zend\Stdlib\Parameters(array('foo' => 'bar')); $request->setQuery($p); $request->setPost($p); $request->setFiles($p); $default = 15; $this->assertSame($default, $request->getQuery('baz', $default)); $this->assertSame($default, $request->getPost('baz', $default)); $this->assertSame($default, $request->getFiles('baz', $default)); $this->assertSame($default, $request->getHeaders('baz', $default)); $this->assertSame($default, $request->getHeader('baz', $default)); }
public function testRequestAllowsSettingOfParameterContainer() { $request = new Request(); $p = new \Zend\Stdlib\Parameters(); $request->setQuery($p); $request->setPost($p); $request->setFile($p); $request->setServer($p); $request->setEnv($p); $this->assertSame($p, $request->query()); $this->assertSame($p, $request->post()); $this->assertSame($p, $request->file()); $this->assertSame($p, $request->server()); $this->assertSame($p, $request->env()); }
public function testUpdate() { $userArray = array('location' => 'there', 'groups' => array(array('name' => 'groupB')), 'profile' => array('firstname' => 'Toby')); $request = new Request(); $request->setMethod(Request::METHOD_PUT); $request->setQuery(new Parameters(array('id' => 'superdweebie'))); $request->setContent($userArray); $event = new MvcEvent(); $event->setRouteMatch(new RouteMatch(array())); $event->setApplication($this->serviceManager->get('application')); $response = null; $this->controller->setEvent($event); $consoleModel = $this->controller->dispatch($request, $response); $repository = $this->documentManager->getRepository('Sds\\DoctrineExtensionsModule\\Test\\TestAsset\\Document\\User'); $this->documentManager->clear(); $user = $repository->find($this->id); $this->assertEquals('superdweebie', $user->getId()); $this->assertEquals('there', $user->location()); $this->assertEquals('groupB', $user->getGroups()[0]); $this->assertEquals('Toby', $user->getProfile()->getFirstName()); }
protected function execute($url, $method, array $query = null, array $rawdata = null, Headers $headers = null) { $request = new Request(); // Headers $request->getHeaders()->addHeaders(array('Content-Type' => $this->getContentType())); if ($headers) { $request->getHeaders()->addHeaders($headers); } // Query if ($query) { $request->setQuery(new Parameters($query)); } $request->setUri($url)->setMethod($method); switch ($method) { case self::HTTP_VERB_POST: case self::HTTP_VERB_PUT: case self::HTTP_VERB_PATCH: if ($rawdata) { $request->setPost(new Parameters($rawdata)); } break; } $client = new HttpClient('', $this->_httpClientOptions); $adapter = $client->getAdapter(); /* @var $adapter Curl */ $secure = $request->getUri()->getScheme() == 'https'; $adapter->connect($request->getUri()->getHost(), $request->getUri()->getPort(), $secure); $ch = $adapter->getHandle(); // Set URL curl_setopt($ch, CURLOPT_URL, $request->getUriString() . '?' . $request->getQuery()->toString()); // ensure correct curl call $curlValue = true; switch ($method) { case 'GET': $curlMethod = CURLOPT_HTTPGET; break; case 'POST': $curlMethod = CURLOPT_POST; break; case 'PUT': case 'PATCH': case 'DELETE': case 'OPTIONS': case 'TRACE': case 'HEAD': $curlMethod = CURLOPT_CUSTOMREQUEST; $curlValue = $method; break; default: // For now, through an exception for unsupported request methods throw new Exception("Method '{$method}' currently not supported"); } // mark as HTTP request and set HTTP method curl_setopt($ch, CURL_HTTP_VERSION_1_1, true); curl_setopt($ch, $curlMethod, $curlValue); // ensure actual response is returned curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // set callback function if ($this->getCallbackWriteFunction() instanceof \Closure) { curl_setopt($ch, CURLOPT_WRITEFUNCTION, $this->getCallbackWriteFunction()); } // ensure headers are also returned curl_setopt($ch, CURLOPT_HEADER, false); // set callback function if ($this->getCallbackHeaderFunction() instanceof \Closure) { curl_setopt($ch, CURLOPT_HEADERFUNCTION, $this->getCallbackHeaderFunction()); } // Treating basic auth headers in a special way if ($request->getHeaders() instanceof Headers) { $headersArray = $request->getHeaders()->toArray(); if (array_key_exists('Authorization', $headersArray) && 'Basic' == substr($headersArray['Authorization'], 0, 5)) { curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($ch, CURLOPT_USERPWD, base64_decode(substr($headersArray['Authorization'], 6))); unset($headersArray['Authorization']); } // set additional headers if (!isset($headersArray['Accept'])) { $headersArray['Accept'] = ''; } $curlHeaders = array(); foreach ($headersArray as $key => $value) { $curlHeaders[] = $key . ': ' . $value; } curl_setopt($ch, CURLOPT_HTTPHEADER, $curlHeaders); } // POST body switch ($method) { case 'POST': case 'PUT': case 'PATCH': curl_setopt($ch, CURLOPT_POSTFIELDS, $request->getPost()->toArray()); break; } $this->_handlers[uniqid()] = $ch; end($this->_handlers); return key($this->_handlers); }
private function getSearchNearbyPlaceRequest() { $req = new Request(); $req->setUri('https://maps.googleapis.com/maps/api/place/nearbysearch/json'); $req->setMethod(Request::METHOD_GET); $req->setQuery(new Parameters(['key' => 'AIzaSyDbJurRkujBxXxNxCNDW1LJ3c9HtQJ6yY8', 'radius' => 50000, 'name' => 'tennis', 'keyword' => 'tennis', 'language' => 'fr', 'location' => $this->location['latitude'] . ',' . $this->location['longitude']])); return $req; }
/** @test */ public function read_shouldReturnNullIfThereIsNoAccessToken() { $this->request->setQuery(new Parameters([])); $this->assertNull($this->storage->read()); }
/** * @group 2774 * @group 2745 */ public function testUsesProvidedArgSeparator() { $this->client->setArgSeparator(';'); $request = new Request(); $request->setUri('http://framework.zend.com'); $request->setQuery(array('foo' => 'bar', 'baz' => 'bat')); $this->client->send($request); $rawRequest = $this->client->getLastRawRequest(); $this->assertContains('?foo=bar;baz=bat', $rawRequest); }
/** * Call http method * * @param string $uri * @param string $method * @param array $data */ private function callHttpMethod($uri, $method, array $data = []) { $request = new Request(); $request->setUri($uri); if (!empty($data)) { switch ($method) { case Request::METHOD_GET: $request->setQuery(new Parameters($data)); break; case Request::METHOD_POST: case Request::METHOD_PUT: case Request::METHOD_PATCH: $request->setContent(json_encode($data)); break; } } $request->setMethod($method); $request->getHeaders()->addHeaders($this->getDefaultHeaders()); return json_decode($this->getHttpClient()->send($request)->getBody()); }
function getBOTHSATResult($gpa, $satcrm, $satwrt, $county, $state, $freelunch, $us, $major, $csize, $cpref, $allflag, $schoolname) { $request = new Request(); $request->getHeaders()->addHeaders(array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8')); if ($county == null) { $county = ""; } if ($major == "-1") { $major = null; } $url = ""; try { $request->setUri(Constants::BOTH_URI_SAT); $request->setMethod('GET'); if ($allflag == "1") { $request->setQuery(new Parameters(array('gpa' => $gpa, 'satcrm' => $satcrm, 'satwrt' => $satwrt, 'county' => $county, 'state' => $state, 'size' => $csize, 'style' => $cpref, 'lunch' => $freelunch, 'majors' => $major, "allcolleges" => 'true', 'school' => $schoolname))); } else { $request->setQuery(new Parameters(array('gpa' => $gpa, 'satcrm' => $satcrm, 'satwrt' => $satwrt, 'county' => $county, 'state' => $state, 'size' => $csize, 'style' => $cpref, 'lunch' => $freelunch, 'majors' => $major, 'school' => $schoolname))); } $url = Constants::BOTH_URI_SAT . '?' . $request->getQuery()->toString(); $client = new Client(); $response = $client->dispatch($request); $data = json_decode($response->getBody(), true); } catch (\Exception $e) { $data['exception'] = "URL not found"; $data['url'] = $url; } return $data; }
protected function getSubRequest($batchRequest, array $requestData) { $request = new Request(); $request->setMethod($requestData['method']); $request->setUri($requestData['uri']); $queryString = $request->getUri()->getQuery(); if ($queryString) { $query = []; parse_str($queryString, $query); $request->setQuery(new Parameters($query)); } $requestHeaders = [$batchRequest->getHeaders()->get('Accept'), $batchRequest->getHeaders()->get('Content-Type')]; if (isset($requestData['headers'])) { foreach ($requestData['headers'] as $name => $value) { $requestHeaders[] = GenericHeader::fromString($name . ': ' . $value); } } $request->getHeaders()->addHeaders($requestHeaders); if (isset($requestData['content'])) { $request->setContent(json_encode($requestData['content'])); } return $request; }
public function create($data) { $router = $this->serviceLocator->get('router'); $controllerLoader = $this->serviceLocator->get('controllerLoader'); foreach ($data as $key => $requestData) { $request = new Request(); $request->setMethod($requestData['method']); $request->setUri($requestData['uri']); $queryString = $request->getUri()->getQuery(); if ($queryString) { $query = []; parse_str($queryString, $query); $request->setQuery(new Parameters($query)); } if (isset($requestData['headers'])) { foreach ($requestData['headers'] as $name => $value) { $request->getHeaders()->addHeaderLine($name, $value); } } $request->getHeaders()->addHeaders([$this->request->getHeaders()->get('Accept'), $this->request->getHeaders()->get('Content-Type')]); if (isset($requestData['content'])) { $request->setContent(json_encode($requestData['content'])); } $response = new Response(); $event = new MvcEvent(); $event->setRequest($request); $event->setResponse($response); $match = $router->match($request); RouteListener::resolveController($match); $contentModel = null; if (!isset($match) || $match->getMatchedRouteName() != 'rest.' . $this->options->getManifestName()) { $contentModel = $this->createExceptionContentModel(new Exception\RuntimeException(sprintf('%s uri is not a rest route, so is not supported by batch controller.', $requestData['uri'])), $event); } else { try { $controller = $controllerLoader->get($match->getParam('controller')); } catch (\Zend\ServiceManager\Exception\ServiceNotFoundException $exception) { $contentModel = $this->createExceptionContentModel($exception, $event); $response->setStatusCode(404); } $event->setRouteMatch($match); $controller->setEvent($event); if (!isset($contentModel)) { try { $contentModel = $controller->dispatch($request, $response); } catch (\Exception $exception) { $contentModel = $this->createExceptionContentModel($exception, $event); } } } $headers = []; foreach ($response->getHeaders() as $header) { $headers[$header->getFieldName()] = $header->getFieldValue(); } $responseModel = new JsonModel(['status' => $response->getStatusCode(), 'headers' => $headers]); if ($contentModel instanceof ModelInterface) { $responseModel->addChild($contentModel, 'content'); } $this->model->addChild($responseModel, $key); } return $this->model; }
public function testRequestQueryParamsCanBeOverriden() { $this->request->setQuery(new Parameters(['one' => 'foo', 'another' => 'bar'])); $route = $this->helper->__invoke('route-name', [], ['query' => ['another' => 'overriden']], true); $this->assertEquals('/foo/bar?one=foo&another=overriden', $route); }
/** * Get the request object * * @return Request */ public function getRequest() { if (!$this->request instanceof Request) { $request = new HttpRequest(); $request->setQuery(new PhpEnvironment\GetContainer()) ->setPost(new PhpEnvironment\PostContainer()) ->setEnv(new Parameters($_ENV)) ->setServer(new Parameters($_SERVER)); if ($_COOKIE) { $request->headers()->addHeader(new Cookie($_COOKIE)); } if ($_FILES) { $request->setFile(new Parameters($_FILES)); } if (isset($_SERVER['REQUEST_METHOD'])) { $request->setMethod($_SERVER['REQUEST_METHOD']); } if (isset($_SERVER['REQUEST_URI'])) { $request->setUri($_SERVER['REQUEST_URI']); } $this->setRequest($request); } return $this->request; }
/** * Creates an MvcEvent object. * * @param null $lang * * @return MvcEvent */ protected function createMvcEvent($lang = null) { $e = new MvcEvent(); $e->setApplication($this->app); $e->setViewModel(new ViewModel()); $request = new Http\Request(); if (isset($lang)) { $request->setQuery(new Parameters(['lang' => $lang])); } $e->setRequest($request); return $e; }
/** * @group 3711 */ public function testPartRouteMarkedAsMayTerminateButWithQueryRouteChildWillMatchChildRoute() { $options = array('route' => array('type' => 'Zend\\Mvc\\Router\\Http\\Literal', 'options' => array('route' => '/resource', 'defaults' => array('controller' => 'ResourceController', 'action' => 'resource'))), 'route_plugins' => new RoutePluginManager(), 'may_terminate' => true, 'child_routes' => array('query' => array('type' => 'Zend\\Mvc\\Router\\Http\\Query', 'options' => array('defaults' => array('query' => 'string'))))); $route = Part::factory($options); $request = new Request(); $request->setUri('http://example.com/resource?foo=bar'); $query = new Parameters(array('foo' => 'bar')); $request->setQuery($query); $query = $request->getQuery(); $match = $route->match($request); $this->assertInstanceOf('Zend\\Mvc\\Router\\RouteMatch', $match); $this->assertEquals('string', $match->getParam('query')); $this->assertEquals('bar', $match->getParam('foo')); }
protected function dispatchRequestAndDecodeResponse($url, $method, $data = null) { $request = new Request(); $this->lastResponse = null; $request->getHeaders()->addHeaders(array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept' => 'application/json', 'User-Agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:37.0) Gecko/20100101 Firefox/37.0')); if (!empty($this->host)) { $request->getHeaders()->addHeaders(array('Host' => $this->host)); } if (!empty($this->key)) { $request->getHeaders()->addHeaders(array('Authorization' => 'Bearer ' . $this->key)); } $request->setUri($url); $request->setMethod($method); if (is_null($data)) { $data = array(); } if (isset($this->key)) { $data["auth"] = $this->key; } if ($method == "POST" || $method == "PUT") { $request->setPost(new Parameters($data)); if (isset($this->key)) { $request->setQuery(new Parameters(array('auth' => $this->key))); } } else { $request->setQuery(new Parameters($data)); } $this->lastResponse = $this->httpClient->send($request); if ($this->lastResponse->isSuccess()) { return json_decode($this->lastResponse->getBody(), true); } else { return array('error' => true, 'headers' => array("code" => $this->lastResponse->getStatusCode(), "reasons" => $this->lastResponse->getReasonPhrase()), 'body' => json_decode($this->lastResponse->getBody(), true)); } }
/** * @param $uri * @param string $method * @param array $postParams * @param array $queryParams * @return mixed */ protected function sendRequest($uri, $method = HttpRequest::METHOD_GET, $postParams = array(), $queryParams = array()) { $request = new HttpRequest(); $request->setUri(self::URI_BASE . $uri); $request->setMethod($method); $request->setQuery($this->prepareParameters($queryParams)); $request->setPost($this->prepareParameters($postParams)); $response = $this->httpClient->send($request); $this->checkErrors($response); return Json::decode($response->getBody(), JSON::TYPE_ARRAY); }
public function testCallHttpGetWithQueryParameters() { $queryData = ['query' => 'value']; $request = new Request(); $request->setUri('http://test.dev/testapi'); $request->setMethod(Request::METHOD_GET); $request->setQuery(new Parameters($queryData)); $request->getHeaders()->addHeaders(array('Accept' => 'application/json')); $response = new Response(); $responseData = ['id' => 17, 'testName' => 'testValue']; $response->setContent(json_encode($responseData)); $httpClient = $this->getMock('Zend\\Http\\Client', array('send')); $httpClient->expects($this->once())->method('send')->with($this->equalTo($request))->will($this->returnValue($response)); $client = new Client($httpClient, 'http://test.dev/', ['Accept' => 'application/json']); $this->assertEquals((object) $responseData, $client->call('/testapi', Request::METHOD_GET, $queryData)); }