Client PHP Class Code Examples

This page contains top rated real world PHP examples of class Client extracted from open source projects. You can rate examples to help us improve the quality of examples

Example #1
Show file File: FailoverTest.php Project: microAlex/PSRedis
0
 public function testThatFailoverIsInitiatedAndFailingCommandsAreRetried()
 {
     // we need a factory to create the clients
     $clientFactory = new PredisClientCreator();
     // we need an adapter for each sentinel client too!
     $clientAdapter = new PredisClientAdapter($clientFactory, Client::TYPE_SENTINEL);
     $sentinel1 = new Client('192.168.50.40', '26379', $clientAdapter);
     $clientAdapter = new PredisClientAdapter($clientFactory, Client::TYPE_SENTINEL);
     $sentinel2 = new Client('192.168.50.41', '26379', $clientAdapter);
     $clientAdapter = new PredisClientAdapter($clientFactory, Client::TYPE_SENTINEL);
     $sentinel3 = new Client('192.168.50.30', '26379', $clientAdapter);
     // configure how to back-off on reconnection attempts
     $backoffStrategy = new Incremental(500000, 2);
     $backoffStrategy->setMaxAttempts(10);
     // now we can start configuring the sentinel in the master discovery object
     $masterDiscovery = new MasterDiscovery('integrationtests');
     $masterDiscovery->setBackoffStrategy($backoffStrategy);
     $masterDiscovery->addSentinel($sentinel1);
     $masterDiscovery->addSentinel($sentinel2);
     $masterDiscovery->addSentinel($sentinel3);
     // configure the HAClient that we'll use to talk to the redis master as a proxy
     $HAClient = new HAClient($masterDiscovery);
     // simulate a segfault in 5s
     $this->debugSegfaultToMaster();
     for ($i = 1; $i <= 30; $i++) {
         $HAClient->incr(__METHOD__);
     }
     $this->assertEquals(30, $HAClient->get(__METHOD__), 'Test that all increment calls were executed');
 }
Example #2
Show file File: ClientTest.php Project: EarthTeam/earthteam.net
0
 public function testUsesProxyEnvironmentVariables()
 {
     $http = getenv('HTTP_PROXY');
     $https = getenv('HTTPS_PROXY');
     $client = new Client();
     $this->assertNull($client->getDefaultOption('proxy'));
     putenv('HTTP_PROXY=127.0.0.1');
     $client = new Client();
     $this->assertEquals(['http' => '127.0.0.1'], $client->getDefaultOption('proxy'));
     putenv('HTTPS_PROXY=127.0.0.2');
     $client = new Client();
     $this->assertEquals(['http' => '127.0.0.1', 'https' => '127.0.0.2'], $client->getDefaultOption('proxy'));
     putenv("HTTP_PROXY={$http}");
     putenv("HTTPS_PROXY={$https}");
 }
Example #3
Show file File: AddStatementsToTransaction.php Project: MobilityMaster/neo4jphp
0
 /**
  * Set the transaction and statements to use
  *
  * @param Client $client
  * @param Transaction $transaction
  * @param array $statements
  * @param boolean $commit
  */
 public function __construct(Client $client, Transaction $transaction, $statements = array(), $commit = false)
 {
     parent::__construct($client);
     $this->transaction = $transaction;
     $this->statements = $statements;
     $this->commit = $commit;
 }
Example #4
Show file File: ThruwayWorkerCommand.php Project: trajedy/ThruwayBundle
0
 /**
  * {@inheritdoc}
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     try {
         echo "Making a go at starting a Thruway worker.\n";
         $name = $input->getArgument('name');
         $config = $this->getContainer()->getParameter('voryx_thruway');
         $loop = $this->getContainer()->get('voryx.thruway.loop');
         $kernel = $this->getContainer()->get('wamp_kernel');
         $workerAnnotation = $kernel->getResourceMapper()->getWorkerAnnotation($name);
         if ($workerAnnotation) {
             $realm = $workerAnnotation->getRealm() ?: $config['realm'];
             $url = $workerAnnotation->getUrl() ?: $config['url'];
         } else {
             $realm = $config['realm'];
             $url = $config['url'];
         }
         $transport = new PawlTransportProvider($url);
         $client = new Client($realm, $loop);
         $client->addTransportProvider($transport);
         $kernel->setProcessName($name);
         $kernel->setClient($client);
         $kernel->setProcessInstance($input->getArgument('instance'));
         $client->start();
     } catch (\Exception $e) {
         $logger = $this->getContainer()->get('logger');
         $logger->addCritical("EXCEPTION:" . $e->getMessage());
         $output->writeln("EXCEPTION:" . $e->getMessage());
     }
 }
Example #5
Show file File: TransactionTest.php Project: hoa32811/wp_thanhtrung_hotel
0
 /**
  * Tests the getters and setters of the model
  * @test
  */
 public function setGetTest()
 {
     $amount = "4200";
     $originAmount = 4200;
     $status = "closed";
     $description = "Test Desc";
     $livemode = false;
     $refunds = null;
     $currency = "EUR";
     $responseCode = 200000;
     $shortId = "This is a short string?!";
     $invoices = array();
     $payment = new Response\Payment();
     $client = new Response\Client();
     $preAuth = new Response\Preauthorization();
     $fees = array();
     $this->_transaction->setAmount($amount)->setOriginAmount($originAmount)->setStatus($status)->setDescription($description)->setLivemode($livemode)->setRefunds($refunds)->setCurrency($currency)->setResponseCode($responseCode)->setShortId($shortId)->setInvoices($invoices)->setPayment($payment)->setClient($client)->setPreauthorization($preAuth)->setFees($fees);
     $this->assertEquals($this->_transaction->getAmount(), $amount);
     $this->assertEquals($this->_transaction->getOriginAmount(), $originAmount);
     $this->assertEquals($this->_transaction->getStatus(), $status);
     $this->assertEquals($this->_transaction->getDescription(), $description);
     $this->assertEquals($this->_transaction->getLivemode(), $livemode);
     $this->assertEquals($this->_transaction->getRefunds(), $refunds);
     $this->assertEquals($this->_transaction->getCurrency(), $currency);
     $this->assertEquals($this->_transaction->getResponseCode(), $responseCode);
     $this->assertEquals($this->_transaction->getShortId(), $shortId);
     $this->assertEquals($this->_transaction->getInvoices(), $invoices);
     $this->assertEquals($this->_transaction->getPayment(), $payment);
     $this->assertEquals($this->_transaction->getClient(), $client);
     $this->assertEquals($this->_transaction->getPreauthorization(), $preAuth);
     $this->assertEquals($this->_transaction->getFees(), $fees);
 }
Example #6
Show file File: upload.php Project: strrife/backuper
0
 public function upload($file)
 {
     $authStuff = json_decode(file_get_contents($this->getAuthFilePath()));
     $dbxClient = new \Dropbox\Client($authStuff->token, "PHP-Example/1.0");
     $f = fopen($file, "rb");
     $dbxClient->uploadFile('/' . basename($file), \Dropbox\WriteMode::force(), $f);
 }
Example #7
Show file File: tikilib.php Project: rjsmelo/tiki
0
 /**
  * @param bool $url
  * @return mixed|Zend\Http\Client
  */
 function get_http_client($url = false)
 {
     global $prefs;
     $config = array('timeout' => 10, 'keepalive' => true);
     if ($prefs['use_proxy'] == 'y') {
         $config['adapter'] = 'Zend\\Http\\Client\\Adapter\\Proxy';
         $config["proxy_host"] = $prefs['proxy_host'];
         $config["proxy_port"] = $prefs['proxy_port'];
         if ($prefs['proxy_user'] || $prefs['proxy_pass']) {
             $config["proxy_user"] = $prefs['proxy_user'];
             $config["proxy_pass"] = $prefs['proxy_pass'];
         }
     }
     if (strpos($url, 'https://') === 0) {
         $config['sslverifypeer'] = false;
         // zf2 only
     }
     $client = new Zend\Http\Client(null, $config);
     if ($url) {
         $client = $this->prepare_http_client($client, $url);
         $client->setUri($this->urlencode_accent($url));
         // Zend\Http\Client seems to fail with accents in urls (jb june 2011)
     }
     return $client;
 }
Example #8
Show file File: OauthExtensionSpec.php Project: puterakahfi/FriendlyContexts
0
 function it_set_up_a_client_oauth_plugin_subscriber(Client $client, RequestBuilder $builder, $factory, $plugin)
 {
     $builder->getCredentials()->willReturn(['some builder credentials']);
     $factory->create(['some builder credentials'])->shouldBeCalled()->willReturn($plugin);
     $client->addSubscriber($plugin)->shouldBeCalled();
     $this->secureClient($client, $builder);
 }
Example #9
Show file File: updatelib.php Project: lonelywoolf/hypervm
0
function update_main()
{
    global $argc, $argv;
    global $gbl, $sgbl, $login, $ghtml;
    debug_for_backend();
    $program = $sgbl->__var_program_name;
    $login = new Client(null, null, 'upgrade');
    $opt = parse_opt($argv);
    print "Getting Version Info from the Server...\n";
    if (isset($opt['till-version']) && $opt['till-version'] || lxfile_exists("__path_slave_db")) {
        $sgbl->slave = true;
        $upversion = findNextVersion($opt['till-version']);
        $type = 'slave';
    } else {
        $sgbl->slave = false;
        $upversion = findNextVersion();
        $type = 'master';
    }
    print "Connecting... Please wait....\n";
    if ($upversion) {
        do_upgrade($upversion);
        print "Upgrade Done.. Executing Cleanup....\n";
        flush();
    } else {
        print "{$program} is the latest version\n";
    }
    if (is_running_secondary()) {
        print "Not running Update Cleanup, because this is running secondary \n";
        exit;
    }
    lxfile_cp("htmllib/filecore/php.ini", "/usr/local/lxlabs/ext/php/etc/php.ini");
    $res = pcntl_exec("/bin/sh", array("../bin/common/updatecleanup.sh", "--type={$type}"));
    print "Done......\n";
}
Example #10
Show file File: SBTOAuth2Endpoint.php Project: ItemConsulting/SocialSDK
0
 /**
  * Makes the request to the server.
  *
  * @param string $server
  * @param string $service		The rest service to access e.g. /connections/communities/all
  * @param string $method		GET, POST or PUT
  * @param string $body
  * @param string $headers
  */
 public function makeRequest($server, $service, $method, $options, $body = null, $headers = null, $endpointName = "connections")
 {
     $store = SBTCredentialStore::getInstance();
     $token = $store->getOAuthAccessToken($endpointName);
     $store = SBTCredentialStore::getInstance();
     $settings = new SBTSettings();
     $response = null;
     if ($options == null) {
         $options = array();
     }
     try {
         $client = new Client($server);
         $request = $client->createRequest($method, $service, $headers, $body, $options);
         $request->addHeader('authorization', 'Bearer ' . $token);
         if ($settings->forceSSLTrust($endpointName)) {
             $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYHOST, false);
             $request->getCurlOptions()->set(CURLOPT_SSL_VERIFYPEER, false);
         }
         if ($method == 'POST' && isset($_FILES['file']['tmp_name'])) {
             $request->addPostFile('file', $_FILES['file']['tmp_name']);
         }
         $response = $request->send();
     } catch (Guzzle\Http\Exception\BadResponseException $e) {
         $response = $e->getResponse();
     }
     return $response;
 }
Example #11
Show file File: ClientTest.php Project: mahersafadi/joindin-api
0
 public function testUsesProxyEnvironmentVariables()
 {
     $client = new Client();
     $this->assertNull($client->getDefaultOption('proxy'));
     putenv('HTTP_PROXY=127.0.0.1');
     $client = new Client();
     $this->assertEquals(['http' => '127.0.0.1'], $client->getDefaultOption('proxy'));
     putenv('HTTPS_PROXY=127.0.0.2');
     $client = new Client();
     $this->assertEquals(['http' => '127.0.0.1', 'https' => '127.0.0.2'], $client->getDefaultOption('proxy'));
     putenv('HTTP_PROXY=');
     putenv('HTTPS_PROXY=');
 }
Example #12
Show file File: LoadClientData.php Project: rsmakota/ortofit_backoffice
0
 /**
  * Load data fixtures with the passed EntityManager
  *
  * @param ObjectManager $manager
  */
 public function load(ObjectManager $manager)
 {
     $client = new Client();
     $client->setMsisdn('380670000000');
     $client->setName('Гордей');
     $client->setCountry($this->getReference('country:ua'));
     $client->setClientDirection($this->getReference('clientDirection:internet'));
     $client->setGender(Client::GENDER_MALE);
     $manager->persist($client);
     $this->addReference('client:00', $client);
     $client = new Client();
     $client->setMsisdn('380671111111');
     $client->setName('Андрей');
     $client->setCountry($this->getReference('country:ua'));
     $client->setClientDirection($this->getReference('clientDirection:friends'));
     $client->setGender(Client::GENDER_MALE);
     $manager->persist($client);
     $this->addReference('client:01', $client);
     $client = new Client();
     $client->setMsisdn('3806722222222');
     $client->setName('Инна');
     $client->setCountry($this->getReference('country:ua'));
     $client->setClientDirection($this->getReference('clientDirection:return'));
     $client->setGender(Client::GENDER_FEMALE);
     $manager->persist($client);
     $this->addReference('client:02', $client);
     $manager->flush();
 }
Example #13
Show file File: bootstrap.php Project: andytan2624/andytan.net
0
function getHandler(array $mockResponses = [])
{
    if (class_exists('GuzzleHttp\\HandlerStack')) {
        $mock = new \GuzzleHttp\Handler\MockHandler($mockResponses);
        $handler = \GuzzleHttp\HandlerStack::create($mock);
        $client = new \GuzzleHttp\Client(['handler' => $handler]);
        return new \Google\Auth\HttpHandler\Guzzle6HttpHandler($client);
    }
    $client = new \GuzzleHttp\Client();
    $client->getEmitter()->attach(new \GuzzleHttp\Subscriber\Mock($mockResponses));
    return new \Google\Auth\HttpHandler\Guzzle5HttpHandler($client);
}
Example #14
Show file File: BatchCommandTransferTest.php Project: Frinstio/AlfredWorkflow.com
0
 /**
  * @expectedException Guzzle\Service\Exception\InconsistentClientTransferException
  */
 public function testEnsuresAllCommandsUseTheSameClient()
 {
     $batch = new BatchCommandTransfer(2);
     $client1 = new Client('http://www.example.com');
     $client2 = new Client('http://www.example.com');
     $command1 = new Mc();
     $command1->setClient($client1);
     $command2 = new Mc();
     $command2->setClient($client2);
     $batch->transfer(array($command1, $command2));
 }
Example #15
Show file File: AuthController.php Project: viniciusdacal/satellizer
0
 /**
  * Login with Twitter.
  */
 public function twitter(Request $request)
 {
     $stack = GuzzleHttp\HandlerStack::create();
     // Part 1 of 2: Initial request from Satellizer.
     if (!$request->input('oauth_token') || !$request->input('oauth_verifier')) {
         $stack = GuzzleHttp\HandlerStack::create();
         $requestTokenOauth = new Oauth1(['consumer_key' => Config::get('app.twitter_key'), 'consumer_secret' => Config::get('app.twitter_secret'), 'callback' => $request->input('redirectUri'), 'token' => '', 'token_secret' => '']);
         $stack->push($requestTokenOauth);
         $client = new GuzzleHttp\Client(['handler' => $stack]);
         // Step 1. Obtain request token for the authorization popup.
         $requestTokenResponse = $client->request('POST', 'https://api.twitter.com/oauth/request_token', ['auth' => 'oauth']);
         $oauthToken = array();
         parse_str($requestTokenResponse->getBody(), $oauthToken);
         // Step 2. Send OAuth token back to open the authorization screen.
         return response()->json($oauthToken);
     } else {
         $accessTokenOauth = new Oauth1(['consumer_key' => Config::get('app.twitter_key'), 'consumer_secret' => Config::get('app.twitter_secret'), 'token' => $request->input('oauth_token'), 'verifier' => $request->input('oauth_verifier'), 'token_secret' => '']);
         $stack->push($accessTokenOauth);
         $client = new GuzzleHttp\Client(['handler' => $stack]);
         // Step 3. Exchange oauth token and oauth verifier for access token.
         $accessTokenResponse = $client->request('POST', 'https://api.twitter.com/oauth/access_token', ['auth' => 'oauth']);
         $accessToken = array();
         parse_str($accessTokenResponse->getBody(), $accessToken);
         $profileOauth = new Oauth1(['consumer_key' => Config::get('app.twitter_key'), 'consumer_secret' => Config::get('app.twitter_secret'), 'oauth_token' => $accessToken['oauth_token'], 'token_secret' => '']);
         $stack->push($profileOauth);
         $client = new GuzzleHttp\Client(['handler' => $stack]);
         // Step 4. Retrieve profile information about the current user.
         $profileResponse = $client->request('GET', 'https://api.twitter.com/1.1/users/show.json?screen_name=' . $accessToken['screen_name'], ['auth' => 'oauth']);
         $profile = json_decode($profileResponse->getBody(), true);
         // Step 5a. Link user accounts.
         if ($request->header('Authorization')) {
             $user = User::where('twitter', '=', $profile['id']);
             if ($user->first()) {
                 return response()->json(['message' => 'There is already a Twitter account that belongs to you'], 409);
             }
             $token = explode(' ', $request->header('Authorization'))[1];
             $payload = (array) JWT::decode($token, Config::get('app.token_secret'), array('HS256'));
             $user = User::find($payload['sub']);
             $user->twitter = $profile['id'];
             $user->displayName = $user->displayName ?: $profile['screen_name'];
             $user->save();
             return response()->json(['token' => $this->createToken($user)]);
         } else {
             $user = User::where('twitter', '=', $profile['id']);
             if ($user->first()) {
                 return response()->json(['token' => $this->createToken($user->first())]);
             }
             $user = new User();
             $user->twitter = $profile['id'];
             $user->displayName = $profile['screen_name'];
             $user->save();
             return response()->json(['token' => $this->createToken($user)]);
         }
     }
 }
Example #16
Show file File: Shipment.php Project: gpichurov/ittalents_season5
0
 /**
  * Shipment constructor.
  * @param $sender
  * @param $receiver
  * @param $description
  * @param $status
  */
 public function __construct(Client $sender, Client $receiver, $description, $status = false)
 {
     //$this->number = self::$number++;
     $this->sender = $sender;
     $this->receiver = $receiver;
     $this->createdAt = date('Y-m-d H:i:s');
     $this->description = $description;
     $this->status = $status;
 }
Example #17
Show file File: BaseController.php Project: carlosqueiroz/nosh-core
0
 protected function github_single($sha)
 {
     $client = new \Github\Client(new \Github\HttpClient\CachedHttpClient(array('cache_dir' => '/tmp/github-api-cache')));
     $client = new \Github\HttpClient\CachedHttpClient();
     $client->setCache(new \Github\HttpClient\Cache\FilesystemCache('/tmp/github-api-cache'));
     $client = new \Github\Client($client);
     $result = $commit = $client->api('repo')->commits()->show('shihjay2', 'nosh-core', $sha);
     return $result;
 }
Example #18
Show file File: MasterDiscoveryTest.php Project: hemingw/PSRedis
0
 public function testDiscoveryWithBackoffFailsWhenSentinelsStayOffline()
 {
     $this->setExpectedException('\\PSRedis\\Exception\\ConnectionError', 'All sentinels are unreachable');
     // disable sentinel on all nodes
     $this->disableSentinelAt('192.168.50.40');
     $this->disableSentinelAt('192.168.50.41');
     $this->disableSentinelAt('192.168.50.30');
     // we need a factory to create the clients
     $clientFactory = new PredisClientCreator();
     // we need an adapter for each sentinel client too!
     $clientAdapter = new PredisClientAdapter($clientFactory, Client::TYPE_SENTINEL);
     $sentinel1 = new Client('192.168.50.40', '26379', $clientAdapter);
     $clientAdapter = new PredisClientAdapter($clientFactory, Client::TYPE_SENTINEL);
     $sentinel2 = new Client('192.168.50.41', '26379', $clientAdapter);
     $clientAdapter = new PredisClientAdapter($clientFactory, Client::TYPE_SENTINEL);
     $sentinel3 = new Client('192.168.50.30', '26379', $clientAdapter);
     // now we can start discovering where the master is
     $masterDiscovery = new MasterDiscovery('integrationtests');
     $masterDiscovery->addSentinel($sentinel1);
     $masterDiscovery->addSentinel($sentinel2);
     $masterDiscovery->addSentinel($sentinel3);
     // configure a backoff strategy
     $incrementalBackoff = new Incremental(500, 1.5);
     $incrementalBackoff->setMaxAttempts(5);
     $masterDiscovery->setBackoffStrategy($incrementalBackoff);
     // try to discover the master
     $master = $masterDiscovery->getMaster();
 }
Example #19
Show file File: remotelib.php Project: soar-team/kloxo
0
function remote_main()
{
    global $gbl, $sgbl, $login, $ghtml, $g_dbf;
    global $argv;
    ob_start();
    $args = parse_opt($argv);
    $gbl->is_master = false;
    $gbl->is_slave = false;
    if (isset($args['install-type']) && $args['install-type'] === 'master') {
        $login = new Client(null, null, 'master');
        $gbl->is_master = true;
        $login->get();
    } else {
        $login = new Client(null, null, 'slave');
        //$login->initThisDef();
        $gbl->is_slave = true;
        $rmt = unserialize(lfile_get_contents("__path_slave_db"));
        $login->password = $rmt->password;
    }
    $login->cttype = 'admin';
    // This is to prevent the socket already used error. If use a strict single interface, the socket operations happen through our own functions, and we can set the reuse option.
    $rmt = unserialize(base64_decode($ghtml->frm_rmt));
    $res = do_remote($rmt);
    print_time('full', 'timing');
    $res->message = ob_get_contents();
    $val = base64_encode(serialize($res));
    while (@ob_end_clean()) {
    }
    print $val;
    exit;
}
Example #20
Show file File: BaseTestCase.php Project: mledwards/marketing-cloud-php-sdk
0
 protected function getClient($auth = 'wsse', $authenticate = true)
 {
     switch ($auth) {
         case 'wsse':
             $this->initializeWsseFromGlobals();
             $options = $this->getOptionsFromGlobals();
             $client = new Client(new Curl($options));
             if ($authenticate) {
                 $client->authenticate($options['username'], $options['secret']);
             }
             break;
         case 'soap':
             $this->initializeWsseFromGlobals();
             $options = $this->getOptionsFromGlobals();
             $client = new Client(new SoapClient($options));
             if ($authenticate) {
                 $client->authenticate($options['username'], $options['secret']);
             }
             break;
         case 'oauth':
             $this->initializeOAuthFromGlobals();
             $options = $this->getOptionsFromGlobals();
             $client = new Client(new Curl($options));
             if ($authenticate) {
                 $client->setAuthService(new OAuth2())->authenticate($options['client_id'], $options['client_secret']);
             }
             break;
     }
     return $client;
 }
Example #21
Show file File: lxserverlib.php Project: soar-team/kloxo
0
function lxserver_main()
{
    global $gbl, $sgbl, $login, $ghtml;
    global $argv, $argc;
    if ($argv[1] === 'slave') {
        $login = new Client(null, null, 'slave');
        $gbl->is_slave = true;
        $gbl->is_master = false;
        $rmt = unserialize(lfile_get_contents("__path_slave_db"));
        $login->password = $rmt->password;
        $argv[1] = "Running as Slave";
    } else {
        if ($argv[1] === 'master') {
            $login = new Client(null, null, 'admin');
            $gbl->is_master = true;
            $gbl->is_slave = false;
            $login->get();
            $argv[1] = "Running as Master";
        } else {
            print "Wrong arguments\n";
            exit;
        }
    }
    $login->cttype = 'admin';
    // Set php script execution timer to unlimited
    set_time_limit(0);
    // Start internal socket for remote
    some_server();
}
Example #22
Show file File: SetGroupState.php Project: bendspoons/Phue
0
 /**
  * Send command
  *
  * @param Client $client Phue Client
  */
 public function send(Client $client)
 {
     // Get params
     $params = $this->getActionableParams($client);
     // Send request
     $client->getTransport()->sendRequest("/api/{$client->getUsername()}" . $params['address'], $params['method'], $params['body']);
 }
Frequently Used Methods