public function onOpen(ConnectionInterface $from, RequestInterface $request = null) { echo "New HTTP connection!\n"; //Variables in URLs are not supported in Ratchet for now //See https://github.com/cboden/Ratchet/pull/143 $requestPath = $request->getPath(); $pathParts = explode('/', preg_replace('#^/peerjs/#', '', $requestPath)); //Remove /peerjs $action = array_pop($pathParts); $peerToken = array_pop($pathParts); $peerId = array_pop($pathParts); $key = array_pop($pathParts); $respStatus = 200; $respHeaders = array('X-Powered-By' => \Ratchet\VERSION, 'Access-Control-Allow-Origin' => '*'); $respBody = null; switch ($action) { case 'id': $respHeaders['Content-Type'] = 'text/html'; if ($peerId === null) { do { $peerId = substr(sha1(uniqid('', true) . mt_rand()), 0, self::PEERID_LENGTH); } while ($this->peerServer->peerIdExists($peerId)); } $respBody = $peerId; break; case 'peers': if (self::ALLOW_DISCOVERY) { $peers = $this->peerServer->listPeers(); $list = array(); foreach ($peers as $peer) { $list[] = $peer['id']; } $respBody = $list; } else { $respStatus = 401; // Access denied } break; case 'offer': case 'candidate': case 'answer': case 'leave': //TODO: start streaming? //TODO: start streaming? default: $respStatus = 400; //Bad request } if (is_array($respBody)) { // Encode to JSON $respHeaders['Content-Type'] = 'application/json'; $respBody = json_encode($respBody); } //Send response $response = new Response($respStatus, $respHeaders, (string) $respBody); $from->send((string) $response); $from->close(); }
/** * Simple exception factory for creating Intercom standardised exceptions * * @param RequestInterface $request The Request * @param Response $response The response * @return BadResponseException */ public static function factory(RequestInterface $request, Response $response) { if (!static::isValidIntercomError($response->json())) { $label = 'Unsuccessful response'; $class = __CLASS__; } elseif ($response->isClientError()) { $label = 'Client error response'; $class = __NAMESPACE__ . '\\ClientErrorResponseException'; } elseif ($response->isServerError()) { $label = 'Server error response'; $class = __NAMESPACE__ . '\\ServerErrorResponseException'; } else { $label = 'Unsuccessful response'; $class = __CLASS__; } $message = $label . PHP_EOL . implode(PHP_EOL, array('[status code] ' . $response->getStatusCode(), '[reason phrase] ' . $response->getReasonPhrase(), '[url] ' . $request->getUrl())); $e = new $class($message); $e->setResponse($response); $e->setRequest($request); // Sets the errors if the error response is the standard Intercom error type if (static::isValidIntercomError($response->json())) { $e->setErrors($response->json()['errors']); } return $e; }
/** * Simple exception factory for creating Intercom standardised exceptions * * @param RequestInterface $request The Request * @param Response $response The response * @return BadResponseException */ public static function factory(RequestInterface $request, Response $response) { $response_json = $response->json(); $intercom_unavailable_error = NULL; if (!static::isValidIntercomError($response_json)) { if ($response->isServerError()) { $label = 'Server error response'; $class = __NAMESPACE__ . '\\ServerErrorResponseException'; $intercom_unavailable_error = 'Service Unavailable: Back-end server is at capacity'; } else { $label = 'Unsuccessful response'; $class = __CLASS__; } } elseif ($response->isClientError()) { $label = 'Client error response'; $class = __NAMESPACE__ . '\\ClientErrorResponseException'; } elseif ($response->isServerError()) { $label = 'Server error response'; $class = __NAMESPACE__ . '\\ServerErrorResponseException'; } else { $label = 'Unsuccessful response'; $class = __CLASS__; } $message = $label . PHP_EOL . implode(PHP_EOL, array('[status code] ' . $response->getStatusCode(), '[reason phrase] ' . $response->getReasonPhrase(), '[url] ' . $request->getUrl())); $e = new $class($message); $e->setResponse($response); $e->setRequest($request); // Sets the errors if the error response is the standard Intercom error type if (static::isValidIntercomError($response_json)) { $e->setErrors($response_json['errors']); } elseif ($intercom_unavailable_error != NULL) { $e->setErrors(array('code' => 'service_unavailable', "message" => $intercom_unavailable_error)); } return $e; }
/** * Factory method to create a new Oauth exception. * * @param RequestInterface $request * @param Response $response * * @return OauthException */ public static function factory(RequestInterface $request, Response $response) { $message = 'Client error response' . PHP_EOL . implode(PHP_EOL, array('[status code] ' . $response->getStatusCode(), '[reason phrase] ' . $response->getReasonPhrase(), '[url] ' . $request->getUrl())); $e = new static($message); $e->setResponse($response); $e->setRequest($request); return $e; }
public function after(CommandInterface $command, RequestInterface $request) { $xml = null; if (isset($this->data[$command])) { $xml = $this->finishDocument($this->data[$command]); unset($this->data[$command]); } else { $operation = $command->getOperation(); if ($operation->getData('xmlAllowEmpty')) { $xmlWriter = $this->createRootElement($operation); $xml = $this->finishDocument($xmlWriter); } } if ($xml) { if ($this->contentType && !$request->hasHeader('Content-Type')) { $request->setHeader('Content-Type', $this->contentType); } $request->setBody($xml); } }
/** * Always add a x-amz-content-sha-256 for data integrity. */ public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { if (!$request->hasHeader('x-amz-content-sha256')) { $request->setHeader('x-amz-content-sha256', $this->getPresignedPayload($request)); } parent::signRequest($request, $credentials); }
public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value) { $this->fqname = $command->getName(); $query = array(); $this->customResolver($value, $param, $query, $param->getWireName()); $request->addPostFields($query); }
/** * Always add a x-amz-content-sha-256 for data integrity. */ public function signRequest(RequestInterface $request, CredentialsInterface $credentials) { if ($request instanceof EntityEnclosingRequestInterface && $request->getBody() && !$request->hasHeader('x-amz-content-sha256')) { $request->setHeader('X-Amz-Content-Sha256', $this->getPresignedPayload($request)); } parent::signRequest($request, $credentials); }
/** * {@inheritdoc} */ public function getCacheKey(RequestInterface $request) { // See if the key has already been calculated $key = $request->getParams()->get(self::CACHE_KEY); if (!$key) { $cloned = clone $request; $cloned->removeHeader('Cache-Control'); // Check to see how and if the key should be filtered foreach (explode(';', $request->getParams()->get(self::CACHE_KEY_FILTER)) as $part) { $pieces = array_map('trim', explode('=', $part)); if (isset($pieces[1])) { foreach (array_map('trim', explode(',', $pieces[1])) as $remove) { if ($pieces[0] == 'header') { $cloned->removeHeader($remove); } elseif ($pieces[0] == 'query') { $cloned->getQuery()->remove($remove); } } } } $raw = (string) $cloned; $key = 'GZ' . md5($raw); $request->getParams()->set(self::CACHE_KEY, $key)->set(self::CACHE_KEY_RAW, $raw); } return $key; }
/** * @param RequestInterface $request * * @return RequestInterface */ private function setHeaders(RequestInterface $request) { foreach ($this->headers as $name => $value) { $request->setHeader($name, $value); } return $request; }
private function addQueryString(array $queryString, RequestInterface $request) { ksort($queryString); foreach ($queryString as $key => $value) { $request->getQuery()->set($key, $value); } }
/** * {@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); } }
/** * {@inheritdoc} */ public function visit(CommandInterface $command, RequestInterface $request, $key, $value) { if ($value instanceof PostFileInterface) { $request->addPostFile($value); } else { $request->addPostFile($key, $value); } }
protected function handle200Response(RequestInterface $request, Response $validateResponse) { $request->setResponse($validateResponse); if ($this->canCache->canCacheResponse($validateResponse)) { $this->storage->cache($request, $validateResponse); } return false; }
/** * {@inheritdoc} */ public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value) { if ($value instanceof PostFileInterface) { $request->addPostFile($value); } else { $request->addPostFile($param->getWireName(), $value); } }
private function sendRequest(RequestInterface $request) { try { return $request->send(); } catch (\Exception $e) { throw new GithubException('Unexpected response.', 0, $e); } }
public function onOpen(ConnectionInterface $conn, RequestInterface $request = null) { $this->log('open', $conn); $response = new Response(200, array('Content-type' => 'text/javascript', 'Content-Length' => $this->getFilesize($request->getPath()))); $response->setBody($this->getContent($request->getPath())); $conn->send((string) $response); $conn->close(); }
/** * @param RequestInterface $httpRequest * @return EchoResponse */ private function sendAndProcessResponse(RequestInterface $httpRequest) { $httpResponse = $httpRequest->send(); $data = $httpResponse->json(); $response = new EchoResponse($this, $data); $response->setVerifier($this->getVerifier()); return $response; }
public function it_raises_no_exception_on_ok_response(RequestInterface $request) { $response = new Response(200, null, '{"ok":true,"error":"something_good"}'); $event = new Event(); $event['request'] = $request->getWrappedObject(); $event['response'] = $response; $this->shouldNotThrow('\\Guzzle\\Http\\Exception\\BadResponseException')->duringOnRequestSent($event); }
protected function updateForHandle(RequestInterface $request) { $that = $this; $request->getEventDispatcher()->addListener('request.sent', function (Event $e) use($that) { $that->requestHandle = $e['handle']; }); return $request; }
/** * @param RequestInterface $request * @param \Guzzle\Http\EntityBodyInterface|string $body * @param array $options * @return mixed */ public static function setBody(RequestInterface $request, $body, $options) { $type = isset($options['request_type']) ? $options['request_type'] : 'raw'; $header = null; if ($type == 'raw') { // Raw body return $request->setBody($body, $header); } }
/** @dataProvider provideEntityEnclosingInterfaceMethods */ public function testEntityEnclosingInterfaceMethods($method, array $params = []) { $this->wrappedEntityEnclosingRequest->expects($this->once())->method($method)->will($this->returnValue('ENTITY_ENCL_REQ'))->getMatcher()->parametersMatcher = new ParametersMatcher($params); $this->assertSame('ENTITY_ENCL_REQ', call_user_func_array([$this->unifiedEnclosingEntityRequest, $method], $params)); $this->wrappedRequest->expects($this->any())->method('getMethod')->will($this->returnValue('METHOD')); $this->wrappedRequest->expects($this->any())->method('getPath')->will($this->returnValue('/foo')); $this->setExpectedException('BadMethodCallException', sprintf('Cannot call method "%s" on a request that does not enclose an entity. Did you expect a POST/PUT request instead of METHOD /foo?', $method)); call_user_func_array([$this->unifiedRequest, $method], $params); }
protected function setUp() { $this->mockRequest = $this->getMock('\\Guzzle\\Http\\Message\\RequestInterface'); $this->mockResponse = $this->getMock('\\Guzzle\\Http\\Message\\Response', array(), array(), '', false); $this->mockRequest->expects($this->any())->method('send')->will($this->returnValue($this->mockResponse)); $this->mockHttpClient = $this->getMock('\\Guzzle\\Http\\ClientInterface'); $this->mockAuth = $this->getMock('\\Thismoment\\Signature', array(), array('secret')); $this->object = new \Thismoment\Api('cloud', 'key', 'secret', $this->mockHttpClient, $this->mockAuth); }
/** * Create a new response object from a Clickatell request and response. * * @param \Guzzle\Http\Message\RequestInterface $request The request object * associated with the response. * @throws \UnexpectedValueException when the request does not have a response. */ public function __construct($request) { $response = $request->getResponse(); if (!$response) { throw new \UnexpectedValueException('Request must have have a response.'); } $this->request = $request; $this->parsedResponse = $this->parseBody($response->getBody()); }
private function request(RequestInterface $request) { try { $response = $request->send(); } catch (BadResponseException $e) { throw new Exception(sprintf('7digital API responded with an error %d.', $e->getResponse()->getStatusCode()), 0, $e); } return $this->getContent($response); }
/** * {@inheritdoc} */ public function onOpen(ConnectionInterface $conn, RequestInterface $request = null) { $header = (string) $request->getHeader('Origin'); $origin = parse_url($header, PHP_URL_HOST) ?: $header; if (!in_array($origin, $this->allowedOrigins)) { return $this->close($conn, 403); } return $this->_component->onOpen($conn, $request); }
/** * Add a request to the history * * @param RequestInterface $request Request to add * * @return HistoryPlugin */ public function add(RequestInterface $request) { if ($request->getResponse()) { $this->requests[] = $request; if (count($this->requests) > $this->getlimit()) { array_shift($this->requests); } } return $this; }
/** * {@inheritdoc} */ public function onOpen(ConnectionInterface $conn, RequestInterface $request = null) { $header = (string) $request->getHeader('Origin'); $origin = parse_url($header, PHP_URL_HOST) ?: $header; if (!in_array($origin, $this->allowedOrigins)) { $this->eventDispatcher->dispatch(Events::CLIENT_REJECTED, new ClientRejectedEvent($origin, $request)); return $this->close($conn, 403); } return $this->_component->onOpen($conn, $request); }
/** * Add a prefixed array of headers to the request * * @param RequestInterface $request Request to update * @param Parameter $param Parameter object * @param array $value Header array to add * * @throws InvalidArgumentException */ protected function addPrefixedHeaders(RequestInterface $request, Parameter $param, $value) { if (!is_array($value)) { throw new InvalidArgumentException('An array of mapped headers expected, but received a single value'); } $prefix = $param->getSentAs(); foreach ($value as $headerName => $headerValue) { $request->setHeader($prefix . $headerName, $headerValue); } }
/** * {@inheritdoc} */ public function visit(CommandInterface $command, RequestInterface $request, Parameter $param, $value) { $entityBody = EntityBody::factory($value); $request->setBody($entityBody); $this->addExpectHeader($request, $entityBody, $param->getData('expect_header')); // Add the Content-Encoding header if one is set on the EntityBody if ($encoding = $entityBody->getContentEncoding()) { $request->setHeader('Content-Encoding', $encoding); } }