php Zend-Http-Request类(方法)实例源码

下面列出了php Zend-Http-Request 类(方法)源码代码实例,从而了解它的用法。

作者:andreas-serl    项目:athene   
public function forwardAction()
 {
     $alias = $this->params('alias');
     $instance = $this->getInstanceManager()->getInstanceFromRequest();
     try {
         $location = $this->aliasManager->findCanonicalAlias($alias, $instance);
         $this->redirect()->toUrl($location);
         $this->getResponse()->setStatusCode(301);
         return false;
     } catch (CanonicalUrlNotFoundException $e) {
     }
     try {
         $source = $this->aliasManager->findSourceByAlias($alias);
     } catch (AliasNotFoundException $e) {
         $this->getResponse()->setStatusCode(404);
         return false;
     }
     $router = $this->getServiceLocator()->get('Router');
     $request = new Request();
     $request->setMethod(Request::METHOD_GET);
     $request->setUri($source);
     $routeMatch = $router->match($request);
     if ($routeMatch === null) {
         $this->getResponse()->setStatusCode(404);
         return false;
     }
     $this->getEvent()->setRouteMatch($routeMatch);
     $params = $routeMatch->getParams();
     $controller = $params['controller'];
     $return = $this->forward()->dispatch($controller, ArrayUtils::merge($params, ['forwarded' => true]));
     return $return;
 }

作者:arb    项目:MyCod   
/**
  * @param $ipString
  * @return IdentityInformation
  * @throws \Zend\Validator\Exception\InvalidArgumentException
  */
 public function getIpInfo($ipString)
 {
     $ipValidator = new Ip();
     if (!$ipValidator->isValid($ipString)) {
         throw new InvalidArgumentException();
     }
     // creating request object
     $request = new Request();
     $request->setUri($this->endPoint . $ipString . '/json');
     $client = new Client();
     $adapter = new Client\Adapter\Curl();
     $adapter->setCurlOption(CURLOPT_TIMEOUT_MS, 500);
     $client->setAdapter($adapter);
     $response = $client->send($request);
     $data = $response->getBody();
     $dataArray = json_decode($data);
     $identityInformation = new IdentityInformation();
     $identityInformation->setCountry(isset($dataArray->country) ? $dataArray->country : '');
     $identityInformation->setRegion(isset($dataArray->region) ? $dataArray->region : '');
     $identityInformation->setCity(isset($dataArray->city) ? $dataArray->city : '');
     $identityInformation->setLocation(isset($dataArray->loc) ? $dataArray->loc : '');
     $identityInformation->setProvider(isset($dataArray->org) ? $dataArray->org : '');
     $identityInformation->setHostName(isset($dataArray->hostname) ? $dataArray->hostname : '');
     return $identityInformation;
 }

作者:Edenci    项目:GeonamesServe   
/**
  * Send request elasticsearch like this :
  * curl -X{$httpMethod} http://host/type/index/{$elasticMethod} -d '{json_decode($content)}'
  * @param int $httpMethod
  * @param string $elasticMethod
  * @param string $content
  *
  * @return Stdlib\ResponseInterface
  */
 public function sendRequest($httpMethod = Request::METHOD_GET, $elasticMethod = null, $content = null)
 {
     $request = new Request();
     $request->setUri($this->url . $elasticMethod)->setMethod($httpMethod)->setContent($content);
     $client = new Client();
     return $client->dispatch($request);
 }

作者:aaron4    项目:zf2-mailchim   
public function callServer($method, $params)
 {
     // Get the URI and Url Elements
     $apiUrl = $this->generateUrl($method);
     $requestUri = $apiUrl['uri'];
     // Convert the params to something MC can understand
     $params = $this->processParams($params);
     $params["apikey"] = $this->getConfig('apiKey');
     $request = new Request();
     $request->setMethod(Request::METHOD_POST);
     $request->setUri($requestUri);
     $request->getHeaders()->addHeaders(array('Host' => $apiUrl['host'], 'User-Agent' => 'MCAPI/' . $this->getConfig('apiVersion'), 'Content-type' => 'application/x-www-form-urlencoded'));
     $client = new Client();
     $client->setRequest($request);
     $client->setParameterPost($params);
     $result = $client->send();
     if ($result->getHeaders()->get('X-MailChimp-API-Error-Code')) {
         $error = unserialize($result->getBody());
         if (isset($error['error'])) {
             throw new MailchimpException('The mailchimp API has returned an error (' . $error['code'] . ': ' . $error['error'] . ')');
             return false;
         } else {
             throw new MailchimpException('There was an unspecified error');
             return false;
         }
     }
     return $result->getBody();
 }

作者:omusic    项目:mostad-social-gran   
/**
  * {@inheritDoc}
  */
 public function createTokenResponse(Request $request, Client $client = null, TokenOwnerInterface $owner = null)
 {
     $token = $request->getPost('access_token');
     $scope = $request->getPost('scope');
     if (null === $token) {
         throw OAuth2Exception::invalidRequest('Missing parameter access_token');
     }
     $owner = $this->getOwner($token);
     if (!$owner instanceof TokenOwnerInterface) {
         throw OAuth2Exception::accessDenied('Unable to load user from this token');
     }
     /**
      * @var AccessToken       $accessToken
      * @var null|RefreshToken $refreshToken
      * */
     $accessToken = new AccessToken();
     $refreshToken = null;
     // Generate token
     $this->populateToken($accessToken, $client, $owner, $scope);
     $accessToken = $this->accessTokenService->createToken($accessToken);
     // Before generating a refresh token, we must make sure the authorization server supports this grant
     if ($this->authorizationServer->hasGrant(RefreshTokenGrant::GRANT_TYPE)) {
         $refreshToken = new RefreshToken();
         $this->populateToken($refreshToken, $client, $owner, $scope);
         $refreshToken = $this->refreshTokenService->createToken($refreshToken);
     }
     return $this->prepareTokenResponse($accessToken, $refreshToken);
 }

作者:netglu    项目:sendgrid-webhoo   
public function receiveRequest(HttpRequest $request)
 {
     /**
      * Iterate over all events found in the body of the request
      * and for each of these trigger an event containing the event data
      */
     $eventData = json_decode($request->getContent(), true);
     $manager = $this->getEventManager();
     $params = ['requestBody' => $request->getContent(), 'error' => false];
     /**
      * Make sure that we have an array of Send Grid events
      */
     if (!is_array($eventData)) {
         $params['message'] = 'Invalid JSON Body, or unable to decode JSON payload';
         $params['error'] = true;
         $manager->trigger(self::EVENT_UNEXPECTED_FORMAT, $this, $params);
         return;
     }
     /**
      * Iterate over each Send Grid Event and trigger internal event for each
      */
     foreach ($eventData as $event) {
         $event['event'] = !isset($event['event']) ? null : $event['event'];
         $eventName = $this->resolveEventName($event['event']);
         $eventParams = $params;
         if ($eventName === self::EVENT_UNEXPECTED_TYPE) {
             $eventParams['error'] = true;
             $eventParams['message'] = 'Unexpected Event Type';
         }
         $eventParams['data'] = $event;
         $manager->trigger($eventName, $this, $eventParams);
     }
 }

作者:cos    项目:bnetli   
/**
  * @inheritdoc
  */
 public function request(array $params)
 {
     try {
         $request = new Request();
         $headers = $request->getHeaders();
         $request->setUri($params['url']);
         $headers->addHeaderLine('Accept-Encoding', 'gzip,deflate');
         if ($params['config']->isAuthenticationPossible() === true && $this->option['keys']['public'] !== null && $this->option['keys']['private'] !== null) {
             /**
              * Note: DATE_RFC1123 my not be RFC 1123 compliant, depending on your platform.
              * @link http://www.php.net/manual/de/function.gmdate.php#25031
              */
             $date = gmdate('D, d M Y H:i:s \\G\\M\\T');
             $path = $request->getUri()->getPath();
             $headers->addHeaderLine('Date', $date);
             $headers->addHeaderLine('Authorization', $this->signRequest('GET', $date, $path));
         }
         if (isset($params['lastmodified'])) {
             $headers->addHeaderLine('If-Modified-Since', $params['lastmodified']);
         }
         $response = $this->client->send($request);
         $body = $response->getBody();
         $headers = null;
         if ($this->option['responseheader']) {
             $headers = $response->getHeaders()->toArray();
             $this->lastResponseHeaders = $headers;
         }
     } catch (\Exception $e) {
         throw new ClientException('Client exception catched, use getPrevious().', 0, $e);
     }
     return $this->createResponse($params['config']->isJson(), $response->getStatusCode(), $body, $headers);
 }

作者:alexb-u    项目:ZendServerSD   
public function pharAction()
 {
     $client = $this->serviceLocator->get('zendServerClient');
     $client = new Client();
     if (defined('PHAR')) {
         // the file from which the application was started is the phar file to replace
         $file = $_SERVER['SCRIPT_FILENAME'];
     } else {
         $file = dirname($_SERVER['SCRIPT_FILENAME']) . '/zs-client.phar';
     }
     $request = new Request();
     $request->setMethod(Request::METHOD_GET);
     $request->setHeaders(Headers::fromString('If-Modified-Since: ' . gmdate('D, d M Y H:i:s T', filemtime($file))));
     $request->setUri('https://github.com/zendtech/ZendServerSDK/raw/master/bin/zs-client.phar');
     //$client->getAdapter()->setOptions(array('sslcapath' => __DIR__.'/../../../certs/'));
     $client->setAdapter(new Curl());
     $response = $client->send($request);
     if ($response->getStatusCode() == 304) {
         return 'Already up-to-date.';
     } else {
         ErrorHandler::start();
         rename($file, $file . '.' . date('YmdHi') . '.backup');
         $handler = fopen($file, 'w');
         fwrite($handler, $response->getBody());
         fclose($handler);
         ErrorHandler::stop(true);
         return 'The phar file was updated successfully.';
     }
 }

作者:benivald    项目:zf2-na-pratic   
/**
  * @dataProvider routeProvider
  * @param        Query $route
  * @param        string   $path
  * @param        integer  $offset
  * @param        array    $params
  */
 public function testMatching(Query $route, $path, $offset, array $params = null)
 {
     $request = new Request();
     $request->setUri('http://example.com?' . $path);
     $match = $route->match($request, $offset);
     $this->assertInstanceOf('Zend\Mvc\Router\RouteMatch', $match);
 }

作者:gstearmi    项目:EshopVegeTabl   
public function testOnRenderErrorCreatesAnApiProblemResponse()
 {
     $response = new Response();
     $request = new Request();
     $request->getHeaders()->addHeaderLine('Accept', 'application/json');
     $event = new MvcEvent();
     $event->setError(Application::ERROR_EXCEPTION);
     $event->setRequest($request);
     $event->setResponse($response);
     $this->listener->onRenderError($event);
     $this->assertTrue($event->propagationIsStopped());
     $this->assertSame($response, $event->getResponse());
     $this->assertEquals(406, $response->getStatusCode());
     $headers = $response->getHeaders();
     $this->assertTrue($headers->has('Content-Type'));
     $this->assertEquals('application/problem+json', $headers->get('content-type')->getFieldValue());
     $content = json_decode($response->getContent(), true);
     $this->assertArrayHasKey('status', $content);
     $this->assertArrayHasKey('title', $content);
     $this->assertArrayHasKey('describedBy', $content);
     $this->assertArrayHasKey('detail', $content);
     $this->assertEquals(406, $content['status']);
     $this->assertEquals('Not Acceptable', $content['title']);
     $this->assertContains('www.w3.org', $content['describedBy']);
     $this->assertContains('accept', $content['detail']);
 }

作者:andreas-serl    项目:athene   
public function matchUri($uri)
 {
     $request = new Request();
     $request->setUri($uri);
     $request->setMethod('post');
     return $this->getRouter()->match($request);
 }

作者:shivap8    项目:cos   
function PlanJSONManager($action, $url, $requestjson, $uid)
 {
     $request = new Request();
     $request->getHeaders()->addHeaders(array('Content-Type' => 'application/json; charset=UTF-8'));
     //$url="";
     try {
         $request->setUri($url);
         $request->setMethod($action);
         $client = new Client();
         if ($action == 'PUT' || $action == 'POST') {
             $client->setUri($url);
             $client->setMethod($action);
             $client->setRawBody($requestjson);
             $client->setEncType('application/json');
             $response = $client->send();
             return $response;
         } else {
             $response = $client->dispatch($request);
             //var_dump(json_decode($response->getBody(),true));
             return $response;
         }
     } catch (\Exception $e) {
         $e->getTrace();
     }
     return null;
 }

作者:visinoi    项目:WarehouseTas   
public function init(Request $request)
 {
     if (!$request->isXmlHttpRequest() || !$request->isPost()) {
         $this->noAccess();
     }
     $this->post = $request->getPost();
 }

作者:cross-solutio    项目:yawi   
/**
  * @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);
 }

作者:gridguy    项目:facebooklogi   
/**
  * Login
  *
  * @param \Zend\Http\Request $request
  * @param \Zend\Http\Response $response
  * @return null|array|\Zend\Http\Response
  */
 public function login(array $options, HttpRequest $request, HttpResponse $response = null)
 {
     if (null === $response) {
         $response = new PhpResponse();
     }
     $session = $this->getSessionContainer();
     $code = $request->getQuery('code');
     if (empty($options['redirect_uri'])) {
         $options['redirect_uri'] = $request->getUri()->getScheme() . '://' . $this->getSiteInfo()->getFulldomain() . $request->getRequestUri();
     }
     if (empty($code)) {
         $session['state'] = String::generateRandom(32);
         $session['redirect_uri'] = $options['redirect_uri'];
         $response->setContent('')->setStatusCode(302)->getHeaders()->clearHeaders()->addHeaderLine('Location', static::DIALOG_URI . '?' . http_build_query(array('client_id' => $options['client_id'], 'redirect_uri' => $options['redirect_uri'], 'state' => $session['state'], 'scope' => 'email')));
         if ($response instanceof PhpResponse) {
             $response->send();
             exit;
         } else {
             return $response;
         }
     }
     $state = $request->getQuery('state');
     if (empty($session['state']) || $state !== $session['state']) {
         return null;
     }
     $client = $this->getHttpClient();
     $params = null;
     @parse_str($client->setMethod('GET')->setUri(static::ACCESS_URI)->setParameterGet(array('client_id' => $options['client_id'], 'redirect_uri' => $session['redirect_uri'], 'client_secret' => $options['client_secret'], 'code' => $code))->send()->getBody(), $params);
     unset($session['state']);
     unset($session['redirect_uri']);
     if (empty($params['access_token'])) {
         return null;
     }
     return @json_decode($client->setMethod('GET')->setUri(static::API_URI)->setParameterGet(array('access_token' => $params['access_token']))->send()->getBody(), true);
 }

作者:51system    项目:zf2-extension   
public function testToUriStringMultiQueryOverwrite()
 {
     $request = new Request();
     $request->setUri('http://google.ca/test.html?foo=bar');
     $request->getQuery()->set('foo', 'value');
     $this->assertEquals('http://google.ca/test.html?foo=value', RequestUtils::toUriString($request));
 }

作者:jbarentse    项目:dr   
public function testProcessGetRequest()
    {
        $moduleManager  = $this->getMockBuilder('Zend\ModuleManager\ModuleManager')
                               ->disableOriginalConstructor()
                               ->getMock();
        $moduleManager->expects($this->any())
                      ->method('getLoadedModules')
                      ->will($this->returnValue(array('ZFTest\Apigility\Admin\Model\TestAsset\Bar' => new BarModule)));

        $moduleResource = new ModuleModel($moduleManager, array(), array());
        $controller     = new SourceController($moduleResource);

        $request = new Request();
        $request->setMethod('get');
        $request->getQuery()->module = 'ZFTest\Apigility\Admin\Model\TestAsset\Bar';
        $request->getQuery()->class = 'ZFTest\Apigility\Admin\Model\TestAsset\Bar\Module';

        $controller->setRequest($request);
        $result = $controller->sourceAction();

        $this->assertTrue($result->getVariable('source') != '');
        $this->assertTrue($result->getVariable('file') != '');
        $this->assertEquals($result->getVariable('module'), $request->getQuery()->module);
        $this->assertEquals($result->getVariable('class'), $request->getQuery()->class);
    }

作者:gstearmi    项目:EshopVegeTabl   
/**
  * @dataProvider uploadMethods
  */
 public function testDoesNotMarkUploadFileAsInvalidForPutAndPatchHttpRequests($method)
 {
     $request = new HttpRequest();
     $request->setMethod($method);
     $this->validator->setRequest($request);
     $file = ['name' => basename(__FILE__), 'tmp_name' => realpath(__FILE__), 'size' => filesize(__FILE__), 'type' => 'application/x-php', 'error' => UPLOAD_ERR_OK];
     $this->assertTrue($this->validator->isValid($file), var_export($this->validator->getMessages(), 1));
 }

作者:eschwart    项目:ZfAut   
public static function create(HttpRequest $request)
 {
     $queryParams = $request->getQuery()->toArray();
     $postParams = $request->getPost()->toArray();
     $files = $request->getFiles()->toArray();
     $cookies = ($c = $request->getCookie()) ? [$c] : [];
     return new OAuth2Request($queryParams, $postParams, [], $cookies, $files, $_SERVER);
 }

作者:pnaq5    项目:zf2dem   
/**
  * @dataProvider routeProvider
  * @param    HttpMethod $route
  * @param    $verb
  * @internal param string $path
  * @internal param int $offset
  * @internal param bool $shouldMatch
  */
 public function testMatching(HttpMethod $route, $verb)
 {
     $request = new Request();
     $request->setUri('http://example.com');
     $request->setMethod($verb);
     $match = $route->match($request);
     $this->assertInstanceOf('Zend\\Mvc\\Router\\Http\\RouteMatch', $match);
 }


问题


面经


文章

微信
公众号

扫码关注公众号