示例#1
1
 /**
  * @param string $uri
  * @return bool
  */
 private function delete($uri)
 {
     try {
         $this->httpClient->delete($uri)->send();
     } catch (Exception $e) {
         echo $e->getMessage();
         return false;
     }
     return true;
 }
示例#2
0
 /**
  * Send Delete Customer Request
  * @param $id
  * @return Response
  */
 public function deleteCustomer($id)
 {
     try {
         $response = $this->client->delete('/api/v1/customers/' . $id, null, null, array('auth' => $this->auth))->send();
     } catch (RequestException $e) {
         $response = $e->getResponse();
     }
     return new Response($response->getStatusCode(), $response->getReasonPhrase());
 }
示例#3
0
 private function request($method, $path, $params = array())
 {
     $url = $this->api . rtrim($path, '/') . '/';
     // Using Guzzle library ---------------------------------
     $client = new Client($url, array('ssl.certificate_authority' => false, 'curl.options' => array('CURLOPT_CONNECTTIMEOUT' => 30)));
     // headers
     $headers = array('Connection' => 'close', 'User-Agent' => 'PHPPlivo');
     if (!strcmp($method, "POST")) {
         $request = $client->post('', $headers, json_encode($params));
         $request->setHeader('Content-type', 'application/json');
     } else {
         if (!strcmp($method, "GET")) {
             $request = $client->get('', $headers, $params);
             $request->getQuery()->merge($params);
         } else {
             if (!strcmp($method, "DELETE")) {
                 $request = $client->delete('', $headers, $params);
                 $request->getQuery()->merge($params);
             }
         }
     }
     $request->setAuth($this->auth_id, $this->auth_token);
     $response = $request->send();
     $responseData = $response->json();
     $status = $response->getStatusCode();
     return array("status" => $status, "response" => $responseData);
 }
示例#4
0
 /**
  * @param string $id
  */
 public function delete($id)
 {
     $url = $this->getConnectionUrl($id);
     $request = $this->client->delete($this->client->getBaseUrl() . $url, $this->HEADERS);
     $response = $request->send();
     $this->statusCodeValidator->validate(200, $url, $request, $response);
 }
示例#5
0
 /**
  * Stop running the node.js server
  */
 public function stop()
 {
     if (!$this->isRunning()) {
         return false;
     }
     $this->running = false;
     $this->client->delete('guzzle-server')->send();
 }
 /**
  * Stop running the node.js server
  *
  * @return bool Returns TRUE on success or FALSE on failure
  * @throws RuntimeException
  */
 public function stop()
 {
     if (!$this->isRunning()) {
         return false;
     }
     $this->running = false;
     return $this->client->delete('guzzle-server')->send()->getStatusCode() == 200;
 }
示例#7
0
 /**
  * Performs an HTTP DELETE on a URI. The result can be read from
  * $this->response* variables.
  *
  * This method is named httpDelete() to avoid a name clash with objects that inherit
  * from this one, which usually have a delete() method.
  *
  * @param string $uri
  * @param string $accept
  * @param array $custom_headers
  * @param array $options
  */
 public function httpDelete($uri = null, $accept = 'application/json; charset=utf-8', array $custom_headers = array(), array $options = array())
 {
     $headers = array('accept' => $accept);
     foreach ($custom_headers as $key => $value) {
         $headers[strtolower($key)] = $value;
     }
     $request = $this->client->delete($uri, $headers, null, $options);
     $this->exec($request);
 }
 /**
  * @inheritdoc
  */
 public function request($url, $http_headers = array(), $method = 'GET', $post_data = '')
 {
     // Remove oauth parameters from query string. They are not used by the
     // CultuurNet webservices and only clutter our debug log.
     //preg_match_all('/(?<=[?|&])oauth_.*?[&$]/', $url, $matches);
     $url = preg_replace('/(?<=[?|&])oauth_.*?[&$]/', '', $url);
     switch ($method) {
         case 'GET':
             $request = $this->client->get($url);
             break;
         case 'POST':
             if (is_array($post_data)) {
                 // $post_data contains file multipart/form-data, including file data.
                 // Unfortunately the interfaces of Guzzle\Http and CultureFeed_HttpClient are
                 // incompatible here, so we need to fall back to CultureFeed_HttpClient behavior.
                 return parent::request($url, $http_headers, $method, $post_data);
             } else {
                 $request = $this->client->post($url, null, $post_data);
             }
             break;
         case 'DELETE':
             $request = $this->client->delete($url);
             break;
         default:
             throw new Exception('Unsupported HTTP method ' . $method);
     }
     $request->getQuery()->useUrlEncoding(true);
     foreach ($http_headers as $header) {
         list($name, $value) = explode(':', $header, 2);
         $request->addHeader($name, $value);
     }
     // Ensure by default we indicate a Content-Type of
     // application/x-www-form-urlencoded for requests containing a body.
     if ($request instanceof EntityEnclosingRequestInterface && !$request->hasHeader('Content-Type') && empty($request->getPostFiles())) {
         $request->setHeader('Content-Type', 'application/x-www-form-urlencoded');
     }
     try {
         $response = $request->send();
     } catch (BadResponseException $e) {
         $response = $e->getResponse();
     }
     $culturefeedResponse = new CultureFeed_HttpResponse($response->getStatusCode(), $response->getBody(true));
     return $culturefeedResponse;
 }
 public function testErrorHandling()
 {
     $this->client->delete('/_all')->send();
     $response = $this->client->post('/_expectation', null, ['matcher' => ''])->send();
     $this->assertSame(417, $response->getStatusCode());
     $this->assertSame('POST data key "matcher" must be a serialized list of closures', (string) $response->getBody());
     $response = $this->client->post('/_expectation', null, ['matcher' => ['foo']])->send();
     $this->assertSame(417, $response->getStatusCode());
     $this->assertSame('POST data key "matcher" must be a serialized list of closures', (string) $response->getBody());
     $response = $this->client->post('/_expectation', null, [])->send();
     $this->assertSame(417, $response->getStatusCode());
     $this->assertSame('POST data key "response" not found in POST data', (string) $response->getBody());
     $response = $this->client->post('/_expectation', null, ['response' => ''])->send();
     $this->assertSame(417, $response->getStatusCode());
     $this->assertSame('POST data key "response" must be a serialized Symfony response', (string) $response->getBody());
     $response = $this->client->post('/_expectation', null, ['response' => serialize(new Response()), 'limiter' => 'foo'])->send();
     $this->assertSame(417, $response->getStatusCode());
     $this->assertSame('POST data key "limiter" must be a serialized closure', (string) $response->getBody());
 }
示例#10
0
 /**
  * {@inheritdoc}
  */
 public function makeRequest()
 {
     $client = new Client();
     $request = $client->delete($this->url);
     $response = $request->send();
     if (!in_array($response->getStatusCode(), array(200))) {
         throw new \ErrorException($response->getMessage());
     }
     return true;
 }
示例#11
0
 /**
  * Remove the reasoner program with the given name from the Marmotta knowledge base.
  * @param $name
  */
 public function deleteProgram($name)
 {
     $client = new Client();
     $request = $client->delete($this->getServiceUrl($name), array("User-Agent" => "Marmotta Client Library (PHP)"));
     // set authentication if given in configuration
     if (!is_null($this->config->getUsername())) {
         $request->setAuth($this->config->getUsername(), $this->config->getPassword());
     }
     $response = $request->send();
 }
 public function send(Postmaster_TransportModel $model)
 {
     if (!empty($this->settings->url)) {
         $headers = $this->settings->headers;
         try {
             $client = new Client();
             switch ($this->settings->action) {
                 case 'get':
                     $request = $client->get($this->settings->url, $headers);
                     $query = $request->getQuery();
                     foreach ($this->settings->postVars as $var) {
                         $query->add($var['name'], $var['value']);
                     }
                     break;
                 case 'post':
                     $request = $client->post($this->settings->url, $this->settings->getHeaders(), $this->settings->getRequestVars());
                     break;
                 case 'put':
                     $request = $client->put($this->settings->url, $this->settings->getHeaders(), $this->settings->getRequestVars());
                     break;
                 case 'delete':
                     $request = $client->delete($this->settings->url, $this->settings->getHeaders());
                     break;
             }
             $response = $request->send();
             $model->addData('responseString', (string) $response->getBody());
             $model->addData('responseJson', json_decode($model->getData('responseString')));
             return $this->success($model);
         } catch (ClientErrorResponseException $e) {
             $response = (string) $e->getResponse()->getBody();
             $json = json_decode($response);
             $model->addData('responseString', $response);
             if (is_object($json) && isset($json->errors)) {
                 if (!is_array($json->errors)) {
                     $json->errors = (array) $json->errors;
                 }
                 $model->addData('responseJson', $json);
                 return $this->failed($model, 400, $json->errors);
             } else {
                 $model->addData('responseJson', array($response));
                 return $this->failed($model, 400, array($response));
             }
         } catch (\Exception $e) {
             $error = $e->getMessage();
             $json = !is_array($error) ? array('title' => $error) : $error;
             $model->addData('responseString', $error);
             $model->addData('responseJson', $json);
             return $this->failed($model, 400, $json);
         }
     }
     return $this->failed($model, 400, array(\Craft::t('The ping url is empty.')));
 }
 public static function destroyData(Event $event)
 {
     $io = $event->getIO();
     if (!$event->isDevMode()) {
         $io->write('This script is only supported in development mode. Exiting.');
         return;
     }
     $destroy_data = $io->askConfirmation('<options=bold>Are you sure you want to destroy all local data? [y,N]: </>', false);
     if (true === $destroy_data) {
         $client = new Client();
         $client->setDefaultOption('exceptions', false);
         $es_indices = self::DEFAULT_PROJECT_NAME . '.*';
         $couch_event_db = self::DEFAULT_PROJECT_NAME . '%2Bdomain_events';
         $couch_process_db = self::DEFAULT_PROJECT_NAME . '%2Bprocess_states';
         $io->write('-> deleting Elasticsearch indices "' . $es_indices . '"');
         $client->delete('http://localhost:9200/' . $es_indices)->send();
         $io->write('-> deleting CouchDb database "' . $couch_event_db . '"');
         $client->delete('http://127.0.0.1:5984/' . $couch_event_db)->send();
         $io->write('-> deleting CouchDb database "' . $couch_process_db . '"');
         $client->delete('http://127.0.0.1:5984/' . $couch_process_db)->send();
     }
     return $destroy_data;
 }
示例#14
0
 /**
  * Send signed HTTP requests to the API server.
  *
  * @param string $method HTTP method (GET, POST, PUT or DELETE)
  * @param string $path   Request path
  * @param array  $params Additional request parameters
  *
  * @return string The API server's response
  *
  * @throws ApiException  if an API error occurs
  * @throws HttpException if the request fails
  */
 private function request($method, $path, array $params)
 {
     // sign the request parameters
     $signer = PandaSigner::getInstance($this->cloudId, $this->account);
     $params = $signer->signParams($method, $path, $params);
     // ensure to use relative paths
     if (0 === strpos($path, '/')) {
         $path = substr($path, 1);
     }
     // append request parameters to the URL
     if ('GET' === $method || 'DELETE' === $method) {
         $path .= '?' . http_build_query($params);
     }
     // prepare the request
     $request = null;
     switch ($method) {
         case 'GET':
             $request = $this->guzzleClient->get($path);
             break;
         case 'DELETE':
             $request = $this->guzzleClient->delete($path);
             break;
         case 'PUT':
             $request = $this->guzzleClient->put($path, null, $params);
             break;
         case 'POST':
             $request = $this->guzzleClient->post($path, null, $params);
             break;
     }
     // and execute it
     try {
         $response = $request->send();
     } catch (\Exception $e) {
         // throw an exception if the http request failed
         throw new HttpException($e->getMessage(), $e->getCode());
     }
     // throw an API exception if the API response is not valid
     if ($response->getStatusCode() < 200 || $response->getStatusCode() > 207) {
         $decodedResponse = json_decode($response->getBody(true));
         $message = $decodedResponse->error . ': ' . $decodedResponse->message;
         throw new ApiException($message, $response->getStatusCode());
     }
     return $response->getBody(true);
 }
示例#15
0
 private function request($url, array $body = array(), $method)
 {
     $json = json_encode($body);
     $client = new Client($this->baseUrl);
     switch ($method) {
         case 'GET':
             $request = $client->get($url, NULL, $json);
             break;
         case 'PUT':
             $request = $client->put($url, NULL, $json);
             break;
         case 'POST':
             $request = $client->post($url, NULL, $json);
             break;
         case "DELETE":
             $request = $client->delete($url, NULL, $json);
             break;
     }
     $request = $request->setAuth($this->apiEmail, $this->apiKey);
     try {
         $response = $request->send();
         $body = $response->getBody();
         $headers = $response->getHeaders();
     } catch (HttpException $e) {
         $response = json_decode($e->getResponse()->getBody(), true);
         throw new APIException($response['error']['message'], $response['error']['code'], isset($response['error']['reason']) ? $response['error']['reason'] : '', $e);
     }
     return new ApiResponse($headers, json_decode($body, true));
 }
示例#16
0
 /**
  * Empty the inbox.
  */
 public function clearMessages()
 {
     $this->mailcatcher->delete('/messages');
 }
 public function restoreAlertCouchDbState()
 {
     $baseUrl = HCA_ServiceManager::getInstance()->getContainer()->getParameter('couchDbBaseUrl');
     $couchDbAlert = HCA_ServiceManager::getInstance()->getContainer()->getParameter('couchDbAlert');
     if ($couchDbAlert != 'fixtures_alerts') {
         throw new \Exception("You must use `fixtures_alerts` couch database for testing instead of `{$couchDbAlert}`");
     }
     try {
         $client = new Client($baseUrl);
         $response = $client->delete($couchDbAlert)->send();
     } catch (\Exception $e) {
         //echo $e->getMessage();
     }
     return $this;
 }
 /**
  * @param string $endpoint
  * @param array $options
  * @return \Guzzle\Http\Message\Response
  */
 protected function executeDeleteRequest($endpoint, $options = array())
 {
     $response = $this->restClient->delete($endpoint, $this->headers, $options)->send();
     return $response;
 }
示例#19
0
 private function sendRequest($method, $URL, $postBody = "")
 {
     $client = new Client();
     $request = null;
     if ($method == "POST") {
         $request = $client->post($URL);
     } else {
         if ($method == "PUT") {
             $request = $client->put($URL);
         } else {
             if ($method == "DELETE") {
                 $request = $client->delete($URL);
             } else {
                 $request = $client->get($URL);
             }
         }
     }
     if ($method == "POST" || $method == "PUT" || $method == "DELETE") {
         if (!empty($postBody)) {
             $request->setBody($postBody, 'application/json');
         }
     }
     $response = $request->send();
     return array($response->getHeaderLines(), $response->getBody());
 }
 public function testClientHasHelperMethodsForCreatingRequests()
 {
     $url = $this->getServer()->getUrl();
     $client = new Client($url . 'base');
     $this->assertEquals('GET', $client->get()->getMethod());
     $this->assertEquals('PUT', $client->put()->getMethod());
     $this->assertEquals('POST', $client->post()->getMethod());
     $this->assertEquals('HEAD', $client->head()->getMethod());
     $this->assertEquals('DELETE', $client->delete()->getMethod());
     $this->assertEquals('OPTIONS', $client->options()->getMethod());
     $this->assertEquals('PATCH', $client->patch()->getMethod());
     $this->assertEquals($url . 'base/abc', $client->get('abc')->getUrl());
     $this->assertEquals($url . 'zxy', $client->put('/zxy')->getUrl());
     $this->assertEquals($url . 'zxy?a=b', $client->post('/zxy?a=b')->getUrl());
     $this->assertEquals($url . 'base?a=b', $client->head('?a=b')->getUrl());
     $this->assertEquals($url . 'base?a=b', $client->delete('/base?a=b')->getUrl());
 }
示例#21
0
            $app['session']->set('error', $e->getResponse()->getStatusCode() . ": " . $e->getResponse()->getReasonPhrase());
            return $app->redirect('../../ui/error');
        }
    }
    return $app->redirect('../../ui/package');
})->value('url', '');
$app->match('/ui/resource/functions{url}', function (Request $request) use($app, $hostname) {
    // if you want to remove a resource
    if ($request->get("remove") != null) {
        $client = new Client();
        try {
            $path = $hostname . "tdtadmin/resources/" . $request->get('path');
            // controlling if once in a time a username and password is given to authorise for deleting
            // if not, try without authentication
            if ($app['session']->get('userrm') == null || $app['session']->get('pswdrm') == null) {
                $request = $client->delete($path);
            } else {
                $request = $client->delete($path)->setAuth($app['session']->get('userrm'), $app['session']->get('pswdrm'));
            }
            $response = $request->send();
        } catch (ClientErrorResponseException $e) {
            // if tried with authentication and it failed
            // or when tried without authentication and authentication is needed
            if ($e->getResponse()->getStatusCode() == 401) {
                // necessary information is stored in the session object, needed to redo the request after authentication
                $app['session']->set('method', 'remove');
                $app['session']->set('path', $path);
                $app['session']->set('redirect', $hostname . 'ui/package');
                $app['session']->set('referer', $hostname . 'ui/resource/functions');
                return $app->redirect('../../ui/authentication');
            } else {
示例#22
0
 public function deleteResource($uri)
 {
     $client = new Client();
     $request = $client->delete($this->getServiceUrl($uri), array("User-Agent" => "Marmotta Client Library (PHP)"));
     // set authentication if given in configuration
     if (!empty($this->config->getUsername())) {
         $request->setAuth($this->config->getUsername(), $this->config->getPassword());
     }
     $response = $request->send();
     if ($response->getStatusCode() >= 400) {
         throw new Exception("could not delete resource {$uri}; " . $response->getReasonPhrase());
     }
 }
 /**
  * Remove the configuration with the given key.
  *
  * @param key
  * @throws IOException
  * @throws MarmottaClientException
  */
 public function deleteConfiguration($key)
 {
     try {
         $client = new Client();
         $request = $client->delete($this->getServiceUrl("/data/" . urlencode($key)), array("User-Agent" => "Marmotta Client Library (PHP)"));
         // set authentication if given in configuration
         if (!is_null($this->config->getUsername())) {
             $request->setAuth($this->config->getUsername(), $this->config->getPassword());
         }
         $response = $request->send();
     } catch (BadResponseException $ex) {
         throw new MarmottaClientException("could not delete configuration with key {$key}; " . $ex->getResponse()->getReasonPhrase());
     }
 }
 /**
  * @param string $uri
  * @param array $headers
  * @param array $body
  * @param array $options
  * @return \Guzzle\Http\Message\EntityEnclosingRequestInterface|\Guzzle\Http\Message\RequestInterface
  */
 public function delete($uri, $headers = [], $body = null, $options = [])
 {
     $this->request = $this->client->delete($uri, $headers, $body, $options);
     $this->response = $this->request->send();
     return $this->response;
 }
示例#25
0
 /**
  * @param string $id
  * @return mixed
  */
 private function dropCredentialsRequest($id)
 {
     $request = $this->client->delete($this->getBackend() . "/" . $id, $this->getHeaders());
     return $this->sendRequest($request);
 }
示例#26
0
<?php

require 'vendor/autoload.php';
use Guzzle\Http\Client;
$user = getenv('user');
$pass = getenv('pass');
$db = getenv('db');
echo "{$user} {$pass} {$db}\n";
$baseUrl = "https://{$user}:{$pass}@{$user}.cloudant.com/{$db}";
$client = new Client($baseUrl);
$client->setDefaultOption('exceptions', false);
$putDbRequest = $client->put('');
$putDbResponse = $putDbRequest->send();
$doc = array('name' => 'john', 'age' => 35);
$postDocRequest = $client->post('', array("Content-Type" => "application/json"), json_encode($doc));
$postDocResponse = $postDocRequest->send();
$rev1 = json_decode($postDocResponse->getBody())->{'rev'};
$id = json_decode($postDocResponse->getBody())->{'id'};
echo "The new document's id is {$id} and the first revision is {$rev1}.\n";
$doc['age'] = 36;
$doc['_rev'] = $rev1;
$putDocRequest = $client->put("{$id}", array(), json_encode($doc));
$putDocResponse = $putDocRequest->send();
echo $putDocRequest;
echo $putDocResponse;
$rev2 = json_decode($putDocResponse->getBody())->{'rev'};
echo "The second revision is {$rev2}.\n";
echo "Now we will delete the document. This is the response we got:\n";
$deleteRequest = $client->delete("{$id}?rev={$rev2}");
$deleteResponse = $deleteRequest->send();
echo $deleteResponse->getBody();
示例#27
0
 /**
  * @param $facilityId
  * @param $doctorId
  * @param $doctorServiceId
  *
  * @return DeleteDoctorServiceResponse
  */
 public function deleteDoctorService($facilityId, $doctorId, $doctorServiceId)
 {
     $request = $this->client->delete(['facilities/{facilityId}/doctors/{doctorId}/services/{doctorServiceId}', ['facilityId' => $facilityId, 'doctorId' => $doctorId, 'doctorServiceId' => $doctorServiceId]]);
     $response = $this->authorizedRequest($request, DeleteDoctorServiceResponse::class);
     return $response;
 }
示例#28
0
 /**
  * MailCatcher のメッセージをすべて削除する.
  */
 protected function cleanUpMailCatcherMessages()
 {
     try {
         $client = new Client();
         $request = $client->delete(self::MAILCATCHER_URL . 'messages');
         $request->send();
     } catch (\Exception $e) {
         $this->app->log('[' . get_class() . '] ' . $e->getMessage());
     }
 }
示例#29
0
文件: authentication.php 项目: tdt/ui
 }
 if ('POST' == $request->getMethod()) {
     $form->bind($request);
     if ($form->isValid()) {
         // When the form is posted, keep the referer url in session for validation of user/pass combination
         $app['session']->set('formerreferer', $internalreferer);
         // getting the data from the form
         $formdata = $form->getData();
         $client = new Client();
         // if a delete request must be authorized
         if ($app['session']->get('method') == 'remove') {
             $title = $title . "for deleting";
             $app['session']->set('userrm', $formdata['Username']);
             $app['session']->set('pswdrm', $formdata['Password']);
             try {
                 $request = $client->delete($app['session']->get('path'))->setAuth($formdata['Username'], $formdata['Password']);
                 $response = $request->send();
             } catch (ClientErrorResponseException $e) {
                 if ($e->getResponse()->getStatusCode() == 401) {
                     return $app->redirect($hostname . 'ui/authentication');
                 } else {
                     $app['session']->set('error', $e->getResponse()->getStatusCode() . ": " . $e->getResponse()->getReasonPhrase());
                     return $app->redirect('../../ui/error');
                 }
             }
         } elseif ($app['session']->get('method') == 'getFile') {
             $title = $title . "for getting File";
             $app['session']->set('userget', $formdata['Username']);
             $app['session']->set('pswdget', $formdata['Password']);
             try {
                 $request = $client->get($app['session']->get('path'))->setAuth($formdata['Username'], $formdata['Password']);
示例#30
0
 /**
  * @param $endpointUrl
  * @return \stdClass
  * @throws GenericHTTPError
  * @throws InvalidCredentials
  * @throws MissingEndpoint
  * @throws MissingRequiredParameters
  */
 public function delete($endpointUrl)
 {
     $request = $this->mgClient->delete($endpointUrl);
     $response = $request->send();
     return $this->responseHandler($response);
 }