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;
 }
Exemple #2
0
 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;
 }
    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);
    }
Exemple #4
0
 /**
  * {@inheritdoc}
  */
 public function sendRequest(RequestInterface $request)
 {
     $request = $this->sanitizeRequest($request);
     $headers = new Headers();
     foreach ($request->getHeaders() as $key => $value) {
         $headers->addHeader(new GenericHeader($key, $request->getHeaderLine($key)));
     }
     $zendRequest = new Request();
     $zendRequest->setMethod($request->getMethod());
     $zendRequest->setUri((string) $request->getUri());
     $zendRequest->setHeaders($headers);
     $zendRequest->setContent($request->getBody()->getContents());
     $options = ['httpversion' => $request->getProtocolVersion()];
     if (extension_loaded('curl')) {
         $options['curloptions'] = [CURLOPT_HTTP_VERSION => $this->getProtocolVersion($request->getProtocolVersion())];
     }
     $this->client->setOptions($options);
     if ($this->client->getAdapter() instanceof ZendClient\Adapter\Curl && $request->getMethod()) {
         $request = $request->withHeader('Content-Length', '0');
     }
     try {
         $zendResponse = $this->client->send($zendRequest);
     } catch (RuntimeException $exception) {
         throw new NetworkException($exception->getMessage(), $request, $exception);
     }
     return $this->responseFactory->createResponse($zendResponse->getStatusCode(), $zendResponse->getReasonPhrase(), $zendResponse->getHeaders()->toArray(), $zendResponse->getContent(), $zendResponse->getVersion());
 }
Exemple #5
0
 public function matchUri($uri)
 {
     $request = new Request();
     $request->setUri($uri);
     $request->setMethod('post');
     return $this->getRouter()->match($request);
 }
 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.';
     }
 }
Exemple #7
0
 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();
 }
 /**
  * Prepare a Zend Request by Operation with $parameters
  *
  * @param Operation $operation
  * @param array $parameters
  * @param int $options BitMask of options to skip or something else
  * @return Request
  * @throws \InvalidArgumentException
  * @throws \RuntimeException
  */
 public function makeRequestByOperation(Operation $operation, array $parameters = [], $options = 0)
 {
     $request = new Request();
     $path = $operation->path;
     if ($operation->parameters) {
         foreach ($operation->parameters as $parameter) {
             if (isset($parameters[$parameter->name])) {
                 switch ($parameter->in) {
                     case 'path':
                         $path = str_replace('{' . $parameter->name . '}', $parameters[$parameter->name], $path);
                         break;
                     case 'query':
                         $request->getQuery()->set($parameter->name, $parameters[$parameter->name]);
                         break;
                     case 'formData':
                         $request->getPost()->set($parameter->name, $parameters[$parameter->name]);
                         break;
                     default:
                         throw new RuntimeException(sprintf('Parameter "%s" with ->in = "%s" is not supported', $parameter->parameter, $parameter->in));
                 }
             } elseif ($parameter->required && !($options & SwaggerWrapper::SKIP_REQUIRED)) {
                 throw new InvalidArgumentException(sprintf('Parameter "%s" is required, please pass value for this in $parameters', $parameter->name));
             }
         }
     }
     $request->setUri($path);
     $request->setMethod($operation->method);
     return $request;
 }
Exemple #9
0
 public function findRegion($country, $query)
 {
     $request = new Request();
     $request->setMethod(Request::METHOD_GET);
     foreach ($query as $key => $value) {
         $request->getQuery()->set($key, $value);
     }
     $request->getHeaders()->addHeaderLine('Accept', 'application/json');
     switch ($country) {
         case 'CH':
             $request->setUri($this->config['url'] . '/ch-region');
             break;
         default:
             $request->setUri($this->config['url'] . '/ch-region');
             break;
     }
     $client = new Client();
     $response = $client->send($request);
     $body = $response->getBody();
     $result = json_decode($body, true);
     if ($result) {
         return $result['_embedded']['ch_region'];
     }
     /*echo "<textarea cols='100' rows='30' style='position:relative; z-index:10000; width:inherit; height:200px;'>";
       print_r($body);
       echo "</textarea>";
       die();*/
     return null;
 }
 /**
  *
  * @param MvcEvent $event            
  * @return bool
  */
 public function isGranted(MvcEvent $event)
 {
     $request = $event->getRequest();
     if (!$request instanceof HttpRequest) {
         return true;
     }
     if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
         $clientIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
     } else {
         $clientIp = $_SERVER['REMOTE_ADDR'];
     }
     if (array_key_exists($clientIp, $this->users)) {
         $user = $this->users[$clientIp];
         if ($this->auth->hasIdentity()) {
             // do nothing
         } else {
             $adapter = $this->auth->getAdapter();
             $request = new HttpRequest();
             $request->setMethod(HttpRequest::METHOD_POST);
             $request->getPost()->identity = $user['user'];
             $request->getPost()->credential = $user['password'];
             $request->setContent($request->getPost()->toString());
             $result = $adapter->prepareForAuthentication($request);
             $authenticate = $this->auth->authenticate($adapter);
             if (!$authenticate->isValid()) {
                 error_log('FAIL');
             }
         }
     }
     return true;
 }
 /**
  * @param string $method
  * @param string $url
  *
  * @return null|string
  */
 public function match($method, $url)
 {
     $request = new Request();
     $request->setMethod($method);
     $request->setUri($url);
     $routeMatch = $this->router->match($request);
     return $routeMatch instanceof RouteMatch ? $routeMatch->getMatchedRouteName() : null;
 }
 /**
  * @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));
 }
Exemple #13
0
 /**
  * @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);
 }
 /**
  * Creates and configures a HTTP request based on the provided base URL and the Perun request object.
  * 
  * @param string $baseUrl
  * @param PerunRequest $perunRequest
  * @param HttpRequest $httpRequest
  * @return \Zend\Http\Request
  */
 public function createRequest($baseUrl, PerunRequest $perunRequest)
 {
     /* @var $httpRequest \Zend\Http\Request */
     $httpRequest = new HttpRequest();
     $httpRequest->setUri($this->constructUrl($baseUrl, $perunRequest));
     if ($perunRequest->isChangeState()) {
         $serializedParams = $this->serializer->serialize($perunRequest->getPayload());
         $httpRequest->setMethod(HttpRequest::METHOD_POST);
         $httpRequest->setContent($serializedParams);
         $httpRequest->getHeaders()->addHeaders(array('Content-Type' => $this->serializer->getMimeType()));
     } else {
         $params = $perunRequest->getPayload()->getParams();
         $httpRequest->setMethod(HttpRequest::METHOD_GET);
         $httpRequest->getQuery()->fromArray($params);
     }
     return $httpRequest;
 }
Exemple #15
0
 /**
  * Setup for tests
  *
  * @return null
  */
 public function setUp()
 {
     $config = ['Rcm\\Api\\Page\\Check' => ['type' => 'Segment', 'options' => ['route' => '/rcm/page/check[/:pageType]/:pageId', 'defaults' => ['controller' => 'Rcm\\Controller\\PageCheckController']]]];
     $this->mockPageValidator = $this->getMockBuilder('\\Rcm\\Validator\\Page')->disableOriginalConstructor()->getMock();
     $serviceManager = new ServiceManager();
     $serviceManager->setService('Rcm\\Validator\\Page', $this->mockPageValidator);
     /** @var \Rcm\Service\LayoutManager $mockLayoutManager */
     $this->controller = new PageCheckController($serviceManager);
     $this->request = new Request();
     $this->request->setMethod('GET');
     $this->routeMatch = new RouteMatch(['controller' => 'Rcm\\Controller\\PageCheckController']);
     $this->event = new MvcEvent();
     $routerConfig = $config;
     $router = HttpRouter::factory($routerConfig);
     $this->event->setRouter($router);
     $this->event->setRouteMatch($this->routeMatch);
     $this->controller->setEvent($this->event);
 }
Exemple #16
0
 public function testRequestHttpGet()
 {
     $client = new HTTPClient();
     $request = new Request();
     $request->setUri($this->baseuri);
     $request->setMethod(Request::METHOD_GET);
     $response = $client->send($request);
     $this->assertTrue($response->isSuccess());
 }
Exemple #17
0
 public function testIsActiveReturnsFalseOnNonMatchingRequestUri()
 {
     $page = new Page\Uri(array('label' => 'foo', 'uri' => '/bar'));
     $request = new Request();
     $request->setUri('/baz');
     $request->setMethod('GET');
     $page->setRequest($request);
     $this->assertFalse($page->isActive());
 }
Exemple #18
0
 private function preparePostRequest($post)
 {
     $postRequest = new Request();
     $postRequest->setMethod(Request::METHOD_POST);
     $postRequest->setPost($post);
     $postRequest->setUri($this->url);
     $postRequest->getHeaders()->addHeaders(['Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8']);
     return $postRequest;
 }
 /**
  * @dataProvider requestMethodsWithRequestBodies
  */
 public function testBodyAccessTokenProxiesOAuthServer($method)
 {
     $token = ['user_id' => 'test'];
     $this->setupMockOAuth2Server($token);
     $this->request->setMethod($method);
     $this->request->getHeaders()->addHeaderLine('Content-Type', 'application/x-www-form-urlencoded');
     $this->request->getPost()->set('access_token', 'TOKEN');
     $identity = $this->listener->__invoke($this->mvcAuthEvent);
     $this->assertIdentityMatchesToken($token, $identity);
 }
 public function testNotOverride()
 {
     $request = new Request();
     $request->setMethod('POST');
     $request->getHeaders()->addHeaderLine(HttpMethodOverrideService::OVERRIDE_HEADER, 'GET');
     $event = new MvcEvent();
     $event->setRequest($request);
     $this->listener->override($event);
     $this->assertSame('POST', $request->getMethod());
 }
 public function testImmediatelyReturnResponseForPreflightCorsRequest()
 {
     $mvcEvent = new MvcEvent();
     $request = new HttpRequest();
     $response = new HttpResponse();
     $request->setMethod('OPTIONS');
     $request->getHeaders()->addHeaderLine('Origin', 'http://example.com');
     $request->getHeaders()->addHeaderLine('Access-Control-Request-Method', 'POST');
     $mvcEvent->setRequest($request)->setResponse($response);
     $this->assertInstanceOf('Zend\\Http\\Response', $this->corsListener->onCorsPreflight($mvcEvent));
 }
 /**
  * @dataProvider httpMethods
  */
 public function testHttpMethodOverrideListenerReturnsProblemResponseForIllegalOverrideValue($method)
 {
     $listener = $this->listener;
     $request = new HttpRequest();
     $request->setMethod('POST');
     $request->getHeaders()->addHeaderLine('X-HTTP-Method-Override', $method);
     $event = new MvcEvent();
     $event->setRequest($request);
     $result = $listener->onRoute($event);
     $this->assertInstanceOf(ApiProblemResponse::class, $result);
     $problem = $result->getApiProblem();
     $this->assertEquals(400, $problem->status);
     $this->assertContains(sprintf('Illegal override method %s in X-HTTP-Method-Override header', $method), $problem->detail);
 }
 /**
  * @param  Request  $request
  * @return Response
  */
 public function request(Request $request)
 {
     $headers = new Headers();
     $headers->addHeaders($request->getHeaders());
     $zendRequest = new ZendRequest();
     $zendRequest->setVersion($request->getProtocolVersion());
     $zendRequest->setMethod($request->getMethod());
     $zendRequest->setUri((string) $request->getUrl());
     $zendRequest->setHeaders($headers);
     $zendRequest->setContent($request->getContent());
     /** @var ZendResponse $zendResponse */
     $zendResponse = $this->client->send($zendRequest);
     return new Response((string) $zendResponse->getVersion(), $zendResponse->getStatusCode(), $zendResponse->getReasonPhrase(), $zendResponse->getHeaders()->toArray(), $zendResponse->getContent());
 }
 /**
  * @param array   $routes
  * @param string  $route
  * @param boolean $expectedResult
  * @param array   $params
  * @param string  $httpMethod
  * @dataProvider shouldCacheProvider
  */
 public function testShouldCache($routes, $route, $expectedResult, $params = array(), $httpMethod = null)
 {
     $this->strategy->setRoutes($routes);
     $routeMatch = new RouteMatch($params);
     $routeMatch->setMatchedRouteName($route);
     $request = new Request();
     if ($httpMethod !== null) {
         $request->setMethod($httpMethod);
     }
     $mvcEvent = new MvcEvent();
     $mvcEvent->setRouteMatch($routeMatch);
     $mvcEvent->setRequest($request);
     $this->assertEquals($expectedResult, $this->strategy->shouldCache($mvcEvent));
 }
 /**
  * @dataProvider uploadMethods
  */
 public function testMoveUploadedFileSucceedsOnPutAndPatchHttpRequests($method)
 {
     $target = $this->targetDir . '/uploaded.txt';
     $file = $this->createUploadFile();
     $request = new HttpRequest();
     $request->setMethod($method);
     $filter = new RenameUpload($target);
     $filter->setRequest($request);
     $result = $filter->filter($file);
     $this->assertInternalType('array', $result);
     $this->assertArrayHasKey('tmp_name', $result);
     $this->assertEquals($target, $result['tmp_name']);
     $this->assertTrue(file_exists($target));
     $this->assertFalse(file_exists($file['tmp_name']));
 }
 public function send($url)
 {
     $request = new Request();
     $request->getHeaders()->addHeaders(array('Content-Type: application/xml; charset=ISO-8859-1'));
     $request->setUri($url);
     $request->setMethod(Request::METHOD_GET);
     // $request->setContent($checkout->parseXML());
     $client = new Client();
     $client->setOptions(array('sslverifypeer' => false));
     $response = $client->dispatch($request);
     if ($response->getBody() == 'Unauthorized') {
         throw new \Exception('Unauthorized access to PagSeguro');
     }
     return simplexml_load_string($response->getBody());
 }
 /**
  * Creates a HTTP request based on the userinfo request.
  * 
  * @param Request $request
  * @param Http\Request $httpRequest
  * @return Http\Request
  */
 public function buildHttpRequest(Request $request, Http\Request $httpRequest = null)
 {
     if (null === $httpRequest) {
         $httpRequest = new Http\Request();
     }
     $clientInfo = $request->getClientInfo();
     if (!$clientInfo instanceof ClientInfo) {
         throw new InvalidRequestException('No client info in request');
     }
     $endpointUri = $clientInfo->getUserInfoEndpoint();
     $httpRequest->setUri($endpointUri);
     $httpRequest->setMethod(Http\Request::METHOD_GET);
     $httpRequest->getHeaders()->addHeaders(array($this->authHeaderName => sprintf("%s %s", $this->tokenType, $request->getAccessToken())));
     return $httpRequest;
 }
 /**
  * Appel web service pour récupérer toutes les rubriques
  * @return array
  */
 public function fetchAll()
 {
     $request = new Request();
     //ajoute des headers et modifie la requête
     $request->getHeaders()->addHeaders(array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'));
     $request->setUri('http://localhost/rest/web/index.php/categories');
     //URL du webservice en dehors du projet
     $request->setMethod('GET');
     //$request->setPost(new Parameters(array('someparam' => 'salut')));
     $client = new Client();
     $response = $client->send($request);
     //envoie la requête au service REST
     $data = json_decode($response->getBody(), true);
     //json -> array php
     return $data;
 }
 /**
  * @param null $id
  * @param array $queryParams
  * @return mixed
  */
 protected function requestGet($id = null, $queryParams = array())
 {
     $uri = $this->getApiPath();
     if (!empty($id)) {
         $uri .= '/' . $id;
     }
     if (!empty($queryParams)) {
         $uri .= '?' . http_build_query($queryParams);
     }
     $request = new Request();
     $request->setMethod(Request::METHOD_GET);
     $request->setUri($uri);
     $request->getHeaders()->addHeaders(array('Accept' => 'application/json', 'Authorization' => $this->getTokenType() . ' ' . $this->getAccessToken()));
     $client = new \Zend\Http\Client(null, array('adapter' => 'Zend\\Http\\Client\\Adapter\\Curl', 'curloptions' => array(CURLOPT_SSL_VERIFYHOST => false, CURLOPT_SSL_VERIFYPEER => false)));
     return $client->send($request);
 }
Exemple #30
0
 public static function run(Service\ServiceAbstract $service)
 {
     $request = new Request();
     $client = new Client();
     $adapter = new Adapter\Curl();
     $request->setMethod('GET');
     $client->setAdapter($adapter);
     foreach ($service as $url) {
         if (!is_string($url)) {
             continue;
         }
         $client->setUri($url);
         $response = $client->send($client->getRequest());
         echo $url . " --> " . $response->getStatusCode();
     }
 }