/** * Factory method that instantiates an object from a Response object. * * @param Response $response * @param ServiceInterface $service * @return static */ public static function fromResponse(Response $response, ServiceInterface $service) { $self = parent::fromResponse($response, $service); $segments = Url::factory($response->getEffectiveUrl())->getPathSegments(); $self->name = end($segments); return $self; }
public function testCreatesPresignedUrlsWithStrtotime() { /** @var $client S3Client */ $client = $this->getServiceBuilder()->get('s3'); $url = Url::factory($client->createPresignedUrl($client->get('/foobar'), '10 minutes')); $this->assertTrue(time() < $url->getQuery()->get('Expires')); }
/** * Get description URL * * @return Url */ public function getDescriptionUrl() { if (is_null($this->descriptionUrl)) { return Url::factory(SsdpInterface::DEFAULT_DESCRIPTION_URL); } return $this->descriptionUrl; }
/** * {@inheritdoc} * @throws \UnexpectedValueException If a controller is not \Ratchet\Http\HttpServerInterface */ public function onOpen(ConnectionInterface $conn, RequestInterface $request = null) { if (null === $request) { throw new \UnexpectedValueException('$request can not be null'); } $context = $this->_matcher->getContext(); $context->setMethod($request->getMethod()); $context->setHost($request->getHost()); try { $route = $this->_matcher->match($request->getPath()); } catch (MethodNotAllowedException $nae) { return $this->close($conn, 403); } catch (ResourceNotFoundException $nfe) { return $this->close($conn, 404); } if (is_string($route['_controller']) && class_exists($route['_controller'])) { $route['_controller'] = new $route['_controller'](); } if (!$route['_controller'] instanceof HttpServerInterface) { throw new \UnexpectedValueException('All routes must implement Ratchet\\Http\\HttpServerInterface'); } $parameters = array(); foreach ($route as $key => $value) { if (is_string($key) && '_' !== substr($key, 0, 1)) { $parameters[$key] = $value; } } $url = Url::factory($request->getPath()); $url->setQuery($parameters); $request->setUrl($url); $conn->controller = $route['_controller']; $conn->controller->onOpen($conn, $request); }
/** * {@inheritdoc} */ public function onOpen(ConnectionInterface $conn, RequestInterface $request = null) { if (null === $request) { throw new \UnexpectedValueException('$request can not be null'); } $context = $this->_matcher->getContext(); $context->setMethod($request->getMethod()); $context->setHost($request->getHost()); try { $parameters = $this->_matcher->match($request->getPath()); } catch (MethodNotAllowedException $nae) { return $this->close($conn, 403); } catch (ResourceNotFoundException $nfe) { return $this->close($conn, 404); } if ($parameters['_controller'] instanceof ServingCapableInterface) { $parameters['_controller']->serve($conn, $request, $parameters); } else { $query = array(); foreach ($query as $key => $value) { if (is_string($key) && '_' !== substr($key, 0, 1)) { $query[$key] = $value; } } $url = Url::factory($request->getPath()); $url->setQuery($query); $request->setUrl($url); $conn->controller = $parameters['_controller']; $conn->controller->onOpen($conn, $request); } }
/** * @param string $baseUrl * @param ConsumerCredentials $consumer * @param TokenCredentials $tokenCredentials */ public function __construct($baseUrl, ConsumerCredentials $consumerCredentials, TokenCredentials $tokenCredentials = null) { // @todo check type of $baseUrl $this->baseUrl = Url::factory($baseUrl); $this->consumerCredentials = $consumerCredentials; $this->tokenCredentials = $tokenCredentials; }
public function testEstimatingTemplateCostMarshalsDataCorrectly() { self::log('Estimate a template\'s cost.'); $result = $this->client->estimateTemplateCost(array('TemplateBody' => file_get_contents(__DIR__ . '/template.json'), 'Parameters' => array(array('ParameterKey' => 'KeyName', 'ParameterValue' => 'keypair-name')))); $url = Url::factory($result->get('Url')); $this->assertEquals('calculator.s3.amazonaws.com', $url->getHost()); }
/** * Returns the URL of the metadata (key or block) * * @return string * @param string $subresource not used; required for strict compatibility * @throws ServerUrlerror */ public function getUrl($path = null, array $query = array()) { if (!isset($this->url)) { throw new Exceptions\ServerUrlError('Metadata has no URL (new object)'); } return Url::factory($this->url)->addPath($this->key); }
private function generateUrl($pathfile, array $entry) { $path = substr($pathfile, strlen($entry['directory'])); $hexTime = dechex(time() + 3600); $token = md5($entry['passphrase'] . $path . $hexTime); return Url::factory($entry['mount-point'] . '/' . $token . "/" . $hexTime . $path); }
/** * @dataProvider cookieParserDataProvider */ public function testParseCookie($cookie, $parsed, $url = null) { $c = $this->cookieParserClass; $parser = new $c(); $request = null; if ($url) { $url = Url::factory($url); $host = $url->getHost(); $path = $url->getPath(); } else { $host = ''; $path = ''; } foreach ((array) $cookie as $c) { $p = $parser->parseCookie($c, $host, $path); // Remove expires values from the assertion if they are relatively equal by allowing a 5 minute difference if ($p['expires'] != $parsed['expires']) { if (abs($p['expires'] - $parsed['expires']) < 300) { unset($p['expires']); unset($parsed['expires']); } } if (is_array($parsed)) { foreach ($parsed as $key => $value) { $this->assertEquals($parsed[$key], $p[$key], 'Comparing ' . $key . ' ' . var_export($value, true) . ' : ' . var_export($parsed, true) . ' | ' . var_export($p, true)); } foreach ($p as $key => $value) { $this->assertEquals($p[$key], $parsed[$key], 'Comparing ' . $key . ' ' . var_export($value, true) . ' : ' . var_export($parsed, true) . ' | ' . var_export($p, true)); } } else { $this->assertEquals($parsed, $p); } } }
protected function createRedirectRequest(RequestInterface $request, $statusCode, $location, RequestInterface $original) { $redirectRequest = null; $strict = $original->getParams()->get(self::STRICT_REDIRECTS); if ($request instanceof EntityEnclosingRequestInterface && ($statusCode == 303 || !$strict && $statusCode <= 302)) { $redirectRequest = RequestFactory::getInstance()->cloneRequestWithMethod($request, 'GET'); } else { $redirectRequest = clone $request; } $redirectRequest->setIsRedirect(true); $redirectRequest->setResponseBody($request->getResponseBody()); $location = Url::factory($location); if (!$location->isAbsolute()) { $originalUrl = $redirectRequest->getUrl(true); $originalUrl->getQuery()->clear(); $location = $originalUrl->combine((string) $location, true); } $redirectRequest->setUrl($location); $redirectRequest->getEventDispatcher()->addListener('request.before_send', $func = function ($e) use(&$func, $request, $redirectRequest) { $redirectRequest->getEventDispatcher()->removeListener('request.before_send', $func); $e['request']->getParams()->set(RedirectPlugin::PARENT_REQUEST, $request); }); if ($redirectRequest instanceof EntityEnclosingRequestInterface && $redirectRequest->getBody()) { $body = $redirectRequest->getBody(); if ($body->ftell() && !$body->rewind()) { throw new CouldNotRewindStreamException('Unable to rewind the non-seekable entity body of the request after redirecting. cURL probably ' . 'sent part of body before the redirect occurred. Try adding acustom rewind function using on the ' . 'entity body of the request using setRewindFunction().'); } } return $redirectRequest; }
/** * @param string $url * @param string $username * @param string $password * @throws NuxeoClientException */ public function __construct($url = 'http://localhost:8080/nuxeo', $username = '******', $password = '******') { try { $this->baseUrl = Url::factory($url); $this->httpClient = new Client($url, array( Client::REQUEST_OPTIONS => array( 'headers' => array( 'Content-Type' => 'application/json+nxrequest' ) ) )); } catch(GuzzleException $ex) { throw NuxeoClientException::fromPrevious($ex); } $this->httpClient->setRequestFactory(new RequestFactory()); $self = $this; /** * @param RequestInterface $request */ $this->interceptors[] = function($request) use ($self, $username, $password) { try { $request->setAuth($username, $password); } catch(GuzzleException $ex) { throw NuxeoClientException::fromPrevious($ex); } }; }
/** * Create response from string * * @param string $string * * @return $this */ public static function fromString($string) { /** @var Discover $message */ $message = new static(); foreach (explode(PHP_EOL, trim($string)) as $line) { $tuple = explode(':', trim($line), 2); if (2 == count($tuple)) { $value = trim(array_pop($tuple)); switch (strtoupper(array_pop($tuple))) { case 'CACHE-CONTROL': $message->setLifetime(intval(substr($value, strpos($value, '=') + 1))); break; case 'DATE': $message->setDate(new DateTime($value)); break; case 'LOCATION': $message->setDescriptionUrl(Url::factory($value)); break; case 'SERVER': $message->setServerString($value); break; case 'ST': $message->setSearchTarget(SearchTarget::fromString($value)); break; case 'USN': $message->setUniqueServiceName(UniqueServiceName::fromString($value)); break; } } } return $message; }
public function testCreatesPutRequests() { // Test using a string $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, 'Data'); $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); $this->assertEquals('PUT', $request->getMethod()); $this->assertEquals('http', $request->getScheme()); $this->assertEquals('http://www.google.com/path?q=1&v=2', $request->getUrl()); $this->assertEquals('www.google.com', $request->getHost()); $this->assertEquals('/path', $request->getPath()); $this->assertEquals('/path?q=1&v=2', $request->getResource()); $this->assertInstanceOf('Guzzle\\Http\\EntityBody', $request->getBody()); $this->assertEquals('Data', (string) $request->getBody()); unset($request); // Test using an EntityBody $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, EntityBody::factory('Data')); $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); $this->assertEquals('Data', (string) $request->getBody()); // Test using a resource $resource = fopen('php://temp', 'w+'); fwrite($resource, 'Data'); $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, $resource); $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); $this->assertEquals('Data', (string) $request->getBody()); // Test using an object that can be cast as a string $request = RequestFactory::getInstance()->create('PUT', 'http://www.google.com/path?q=1&v=2', null, Url::factory('http://www.example.com/')); $this->assertInstanceOf('Guzzle\\Http\\Message\\EntityEnclosingRequest', $request); $this->assertEquals('http://www.example.com/', (string) $request->getBody()); }
public function __construct($uri = NULL) { if (empty($uri)) { $uri = $this::DEFAULT_URI; } $this->uri = Url::factory($uri); }
public function getStringToSign(RequestInterface $request, $timestamp, $nonce) { $params = $this->getParamsToSign($request, $timestamp, $nonce); $params = $this->prepareParameters($params); $parameterString = new QueryString($params); $url = Url::factory($request->getUrl())->setQuery('')->setFragment(null); return strtoupper($request->getMethod()) . '&' . rawurlencode($url) . '&' . rawurlencode((string) $parameterString); }
/** * Return a authorize url. */ public function getAuthorizeUrl($request_token, $callback_uri = NULL, $state = NULL) { $request_token = array('oauth_token' => is_array($request_token) ? $request_token['oauth_token'] : $request_token); // authorize $url = Url::factory($this->getConfig('base_url')); $url->addPath($this->getConfig('authorize_path')); $url->setQuery($request_token); return (string) $url; }
public function testCreatesSignedUrlsWithCustomPolicy() { /** @var $client \Aws\CloudFront\CloudFrontClient */ $client = $this->getServiceBuilder()->get('cloudfront'); if ($client->getConfig('private_key') == 'change_me') { $this->markTestSkipped('CloudFront private_key not set'); } $url = $client->getSignedUrl(array('url' => 'http://abc.cloudfront.net/images/image.jpg', 'policy' => '{}')); $policy = Url::factory($url)->getQuery()->get('Policy'); $this->assertRegExp('/^[0-9a-zA-Z-_~]+$/', $policy); }
/** * Return the URL as a string * * @return string */ public function __toString() { $asString = parent::__toString(); if ($this->privateKey) { $accessToken = hash_hmac('sha256', urldecode($asString), $this->privateKey); $url = GuzzleUrl::factory($asString); $url->getQuery()->set('accessToken', $accessToken); return (string) $url; } return $asString; }
protected function filterRequest(Request $request) { $server = $request->getServer(); $uri = Url::factory($request->getUri()); $server['HTTP_HOST'] = $uri->getHost(); $port = $uri->getPort(); if ($port !== null && $port !== 443 && $port != 80) { $server['HTTP_HOST'] .= ':' . $port; } return new Request($request->getUri(), $request->getMethod(), $request->getParameters(), $request->getFiles(), $request->getCookies(), $server, $request->getContent()); }
/** * Ensures that the client marshals correctly * * @example Aws\CloudFormation\CloudFormationClient::estimateTemplateCost */ public function testEstimatesTemplateCosts() { self::log('Estimate a template\'s cost.'); $client = $this->client; $templateBody = file_get_contents(__DIR__ . '/template.json'); // @begin $result = $client->estimateTemplateCost(array('TemplateBody' => $templateBody, 'Parameters' => array(array('ParameterKey' => 'KeyName', 'ParameterValue' => 'keypair-name')))); echo 'Result URL: ' . $result['Url'] . "\n"; // @end $url = Url::factory($result['Url']); $this->assertEquals('calculator.s3.amazonaws.com', $url->getHost()); }
public function __construct(RequestInterface $request) { $url = Url::factory($request->getUrl()); $url->setUsername($request->getUsername()); $url->setPassword($request->getPassword()); $this->url = $url; $this->request = $request; $this->finalRequest = array(); $this->method = 'POST'; $this->iterationNumber = 0; $this->blobList = null; $this->NXVoidOperation = 'true'; }
/** * {@inheritdoc} */ protected function build() { if (!$this->apiCommand->getUri()) { $url = $this->getClient()->getBaseUrl(); } else { // Get the path values and use the client config settings $variables = $this->getClient()->getConfig()->getAll(); foreach ($this->apiCommand->getParams() as $name => $arg) { $configValue = $this->get($name); if (is_scalar($configValue)) { $variables[$name] = $arg->getPrepend() . $configValue . $arg->getAppend(); } } // Expand the URI template using the URI values $template = new UriTemplate($this->apiCommand->getUri()); $uri = $template->expand($variables); // Merge the client's base URL with the URI template $url = Url::factory($this->getClient()->getBaseUrl()); $url->combine($uri); $url = (string) $url; } // Inject path and base_url values into the URL $this->request = $this->getClient()->createRequest($this->apiCommand->getMethod(), $url); // Add arguments to the request using the location attribute foreach ($this->apiCommand->getParams() as $name => $arg) { $configValue = $this->get($name); $location = $arg->getLocation(); if (!$configValue || !$location) { continue; } // Create the value based on prepend and append settings $value = $arg->getPrepend() . $configValue . $arg->getAppend(); // Determine the location and key setting location[:key] $parts = explode(':', $location); $place = $parts[0]; // If a key is specified (using location:key), use it $key = isset($parts[1]) ? $parts[1] : $name; // Add the parameter to the request switch ($place) { case 'body': $this->request->setBody(EntityBody::factory($value)); break; case 'header': $this->request->setHeader($key, $value); break; case 'query': $this->request->getQuery()->set($key, $value); break; } } }
public function build() { // Resolve configuration $config = Collection::fromConfig($this->config, array_merge(self::$commonConfigDefaults, $this->configDefaults), $this->configRequirements); $endpoint = $config['endpoint'] ?: $config[Options::BASE_URL]; // Make sure endpoint is correctly set if (!$endpoint) { throw new InvalidArgumentException('You must provide the endpoint for the CloudSearch domain.'); } if (strpos($endpoint, 'http') !== 0) { $endpoint = $config[Options::SCHEME] . '://' . $endpoint; $config['endpoint'] = $endpoint; $config[Options::BASE_URL] = $endpoint; } // Determine the region from the endpoint $endpoint = Url::factory($endpoint); list(, $region) = explode('.', $endpoint->getHost()); $config[Options::REGION] = $config[Options::SIGNATURE_REGION] = $region; // Create dependencies $exceptionParser = new JsonQueryExceptionParser(); $description = ServiceDescription::factory(sprintf($config->get(Options::SERVICE_DESCRIPTION), $config->get(Options::VERSION))); $signature = $this->getSignature($description, $config); $credentials = $this->getCredentials($config); // Resolve backoff strategy $backoff = $config->get(Options::BACKOFF); if ($backoff === null) { $backoff = new BackoffPlugin(new TruncatedBackoffStrategy(3, new ThrottlingErrorChecker($exceptionParser, new CurlBackoffStrategy(null, new HttpBackoffStrategy(array(500, 503, 509), new ExponentialBackoffStrategy()))))); $config->set(Options::BACKOFF, $backoff); } if ($backoff) { $this->addBackoffLogger($backoff, $config); } // Create client $client = new CloudSearchDomainClient($credentials, $signature, $config); $client->setDescription($description); // Add exception marshaling so that more descriptive exception are thrown $client->addSubscriber(new ExceptionListener(new NamespaceExceptionFactory($exceptionParser, __NAMESPACE__ . '\\Exception', __NAMESPACE__ . '\\Exception\\CloudSearchDomainException'))); // Add the UserAgentPlugin to append to the User-Agent header of requests $client->addSubscriber(new UserAgentListener()); // Filters used for the cache plugin $client->getConfig()->set('params.cache.key_filter', 'header=date,x-amz-date,x-amz-security-token,x-amzn-authorization'); // Disable parameter validation if needed if ($config->get(Options::VALIDATION) === false) { $params = $config->get('command.params') ?: array(); $params['command.disable_validation'] = true; $config->set('command.params', $params); } return $client; }
public function testCreatesSignedUrlsForHttp() { $ts = time() + 1000; $client = $this->getServiceBuilder()->get('cloudfront'); /** @var $client \Aws\CloudFront\CloudFrontClient */ $url = $client->getSignedUrl(array('url' => 'http://abc.cloudfront.net/images/image.jpg?color=red', 'expires' => $ts)); $urlObject = Url::factory($url); $kp = $client->getConfig('key_pair_id'); $this->assertStringStartsWith("http://abc.cloudfront.net/images/image.jpg?color=red&Expires={$ts}&Signature=", $url); $signature = $urlObject->getQuery('Signature'); $this->assertNotContains('?', $signature); $this->assertNotContains('=', $signature); $this->assertNotContains('/', $signature); $this->assertNotContains('&', $signature); $this->assertNotContains('+', $signature); }
/** * @dataProvider urlProvider */ public function testValidateFailsWhenCertUrlDoesNotMatchAws($url, $throws) { $validator = new MessageValidator(); $m = new \ReflectionMethod($validator, 'validateUrl'); $m->setAccessible(true); try { $m->invoke($validator, Url::factory($url)); if ($throws) { $this->fail('URL was invalid but did not fail the test'); } } catch (CertificateFromUnrecognizedSourceException $e) { if (!$throws) { $this->fail('URL was supposed to be valid, but failed test'); } } }
/** * {@inheritdoc} * * Magento doesn't understand running on alternate ports. Therefore we have * to strip the port. WTF. * * @see http://stackoverflow.com/a/14693714/870667 */ public function getStringToSign(RequestInterface $request, $timestamp, $nonce) { $params = $this->getParamsToSign($request, $timestamp, $nonce); // Convert booleans to strings. $params = $this->prepareParameters($params); // Build signing string from combined params $parameterString = new QueryString($params); // Remove the port to get around the Magento bug. // @see http://stackoverflow.com/a/14693714/870667 $requestUrl = $request->getUrl(true); if (preg_match('@/oauth/(initiate|token)$@', $requestUrl->getPath())) { $requestUrl->setPort(''); } $url = Url::factory($requestUrl->setQuery('')->setFragment(null)); return strtoupper($request->getMethod()) . '&' . rawurlencode($url) . '&' . rawurlencode((string) $parameterString); }
/** * Add the requisite Mixpanel authentication parameters to the request's query string * @param Event $event * @return array */ public function onRequestBeforeSend(Event $event) { /** * @var \Guzzle\Http\Message\Request $request */ $request = $event['request']; $params = $request->getQuery()->getAll(); $params['api_key'] = $this->apiKey; $params['expire'] = time() + $this->expire; // Default 10 minutes $params['sig'] = $this->signature($params); $url = Url::factory($request->getUrl())->setQuery('')->setFragment(NULL); $queryString = new QueryString($params); $request->setUrl($url . '?' . $queryString); return $params; }
/** * Searchs the configuration values provided and attempts to build a suitable URL for authentication. * * @return \Guzzle\Http\Url */ private function extractAuthEndpoint() { $auth = empty($this->config['auth_endpoint']) ? self::DEFAULT_AUTH_ENDPOINT : $this->config['auth_endpoint']; switch ($auth) { case Endpoint::UK: $endpoint = Rackspace::UK_IDENTITY_ENDPOINT; break; case Endpoint::US: $endpoint = Rackspace::US_IDENTITY_ENDPOINT; break; default: $endpoint = $auth; break; } return Url::factory($endpoint); }
public function testCanChangeRegions() { /** @var $s3 \Aws\S3\S3Client */ $s3 = $this->getServiceBuilder()->get('s3', true); $scheme = $s3->getConfig(Options::SCHEME); // Switch to 3 different regions and validate that each switch worked foreach (array(Region::US_EAST_1, Region::EU_WEST_1, Region::AP_NORTHEAST_1) as $region) { $s3->setRegion($region); $endpoint = Url::factory(AbstractClient::getEndpoint($s3->getDescription(), $region, 'https')); $command = $s3->getCommand('ListBuckets'); $request = $command->prepare(); $this->assertEquals((string) $endpoint, $request->getScheme() . '://' . $request->getHost()); $this->assertEquals((string) $endpoint, $s3->getConfig(Options::BASE_URL)); $this->assertEquals($region, $s3->getConfig(Options::REGION)); $this->assertEquals(200, $command->getResponse()->getStatusCode()); } }