コード例 #1
0
 /**
  * @covers Guzzle\Service\Description\ServiceDescription
  * @covers Guzzle\Service\Description\ServiceDescription::__construct
  * @covers Guzzle\Service\Description\ServiceDescription::getCommands
  * @covers Guzzle\Service\Description\ServiceDescription::getCommand
  */
 public function testConstructor()
 {
     $service = new ServiceDescription($this->serviceData);
     $this->assertEquals(1, count($service->getCommands()));
     $this->assertFalse($service->hasCommand('foobar'));
     $this->assertTrue($service->hasCommand('test_command'));
 }
コード例 #2
0
 /**
  * {@inheritdoc}
  */
 public function factory($name, array $args = array())
 {
     if ($this->description->hasCommand($name)) {
         $command = $this->description->getCommand($name);
         $class = $command->getConcreteClass();
         return new $class($args, $command);
     }
 }
コード例 #3
0
 public function testAllowsRawResponses()
 {
     $description = new ServiceDescription(array('operations' => array('foo' => array('responseClass' => 'bar', 'responseType' => 'model')), 'models' => array('bar' => array())));
     $op = new OperationCommand(array(OperationCommand::RESPONSE_PROCESSING => OperationCommand::TYPE_RAW), $description->getOperation('foo'));
     $op->setClient(new Client());
     $request = $op->prepare();
     $response = new Response(200, array('Content-Type' => 'application/xml'), '<Foo><Baz>Bar</Baz></Foo>');
     $request->setResponse($response, true);
     $this->assertSame($response, $op->execute());
 }
コード例 #4
0
 /**
  * {@inheritdoc}
  */
 public function factory($name, array $args = array())
 {
     $command = $this->description->getOperation($name);
     // If an inflector was passed, then attempt to get the command using snake_case inflection
     if (!$command && $this->inflector) {
         $command = $this->description->getOperation($this->inflector->snake($name));
     }
     if ($command) {
         $class = $command->getClass();
         return new $class($args, $command, $this->description);
     }
 }
コード例 #5
0
 protected function getMockedClient(Response $response)
 {
     $operation = new Operation(array('httpMethod' => 'GET', 'name' => 'Mock'));
     $service = new ServiceDescription();
     $service->addOperation($operation);
     $plugin = new MockPlugin();
     $plugin->addResponse($response);
     $client = new Client();
     $client->setDescription($service);
     $client->addSubscriber($plugin);
     return $client;
 }
コード例 #6
0
 public static function factory($config = array())
 {
     if (isset($config['developer_mode']) && is_bool($config['developer_mode'])) {
         $developerMode = $config['developer_mode'];
     } else {
         $developerMode = false;
     }
     $baseUrl = array('https://api.auspost.com.au', 'https://devcentre.auspost.com.au/myapi');
     // Ignore unnecessary user-specified configuration values
     if ($developerMode) {
         unset($config['email_address']);
         unset($config['password']);
     }
     unset($config['base_url']);
     $default = array('developer_mode' => $developerMode, 'base_url' => $baseUrl[$developerMode], 'email_address' => '*****@*****.**', 'password' => 'password');
     $required = array('developer_mode', 'base_url', 'email_address', "password");
     $config = Collection::fromConfig($config, $default, $required);
     $client = new self($config->get('base_url'), $config);
     $client->getConfig()->setPath('request.options/headers/Authorization', 'Basic ' . base64_encode($config->get('email_address') . ':' . $config->get('password')));
     $client->setDescription(ServiceDescription::factory(__DIR__ . '/service.json'));
     $client->setSslVerification(false);
     $client->getEventDispatcher()->addListener('request.before_send', function (Event $event) {
         $request = $event['request'];
         $request->addCookie('OBBasicAuth', 'fromDialog');
     });
     return $client;
 }
コード例 #7
0
 protected function getClient()
 {
     $service = ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'TestData' . DIRECTORY_SEPARATOR . 'test_service.xml');
     $client = new Client('http://www.google.com/');
     $client->setDescription($service);
     return $client;
 }
コード例 #8
0
ファイル: TogglClient.php プロジェクト: SirLamer/guzzle-toggl
 /**
  * Factory method to create a new TogglClient
  *
  * The following array keys and values are available options:
  * - base_url: Base URL of web service
  * - username: username or API key
  * - password: password (if empty, then username is a API key)
  *
  * See https://www.toggl.com/public/api#api_token for more information on the api token
  *
  * @param array|Collection $config Configuration data
  *
  * @return self
  */
 public static function factory($config = array())
 {
     $default = array('base_url' => 'https://www.toggl.com/api/{apiVersion}', 'debug' => false, 'apiVersion' => 'v8', 'api_key' => '', 'username' => '', 'password' => '');
     $required = array('api_key', 'username', 'password', 'base_url', 'apiVersion');
     $config = Collection::fromConfig($config, $default, $required);
     $client = new self($config->get('base_url'), $config);
     // Attach a service description to the client
     if ($config->get('apiVersion') == 'v8') {
         $description = ServiceDescription::factory(__DIR__ . '/services_v8.json');
     } else {
         die('Only v8 is supported at this time');
     }
     $client->setDescription($description);
     $client->setDefaultHeaders(array("Content-type" => "application/json"));
     if (!empty($config->get('api_key'))) {
         $config->set('username', $config->get('api_key'));
         $config->set('password', 'api_token');
     }
     if (empty($config->get('password'))) {
         $config->set('password', 'api_token');
     }
     $authPlugin = new CurlAuthPlugin($config->get('username'), $config->get('password'));
     $client->addSubscriber($authPlugin);
     if ($config->get('debug')) {
         $client->addSubscriber(LogPlugin::getDebugPlugin());
     }
     return $client;
 }
コード例 #9
0
 /**
  * @param array $config
  * @return \Guzzle\Service\Client|ImageRelayClient
  * @throws \Guzzle\Common\Exception\InvalidArgumentException
  */
 public static function factory($config = array())
 {
     $default = array('base_url' => 'https://{imagerelay_url}/api/v2/', 'imagerelay_url' => 'subdomain.imagerelay.com');
     $config = Collection::fromConfig($config, $default);
     $client = new self($config->get('base_url'), $config);
     if ($config['auth'] === 'http') {
         if (!isset($config['username'], $config['password'])) {
             throw new InvalidArgumentException("Username and password required when using http auth.");
         }
         $authorization = 'Basic ' . base64_encode($config['username'] . ':' . $config['password']);
     }
     if ($config['auth'] === 'oauth') {
         if (!isset($config['token'])) {
             throw new InvalidArgumentException("Access token required when using oauth.");
         }
         $authorization = sprintf('Bearer %s', $config['token']);
     }
     if (!isset($authorization)) {
         throw new InvalidArgumentException("Must use either http or oauth authentication method.");
     }
     // Attach a service description to the client
     $description = ServiceDescription::factory(__DIR__ . '/Resources/api.php');
     $client->setDescription($description);
     // Set required User-Agent
     $client->setUserAgent(sprintf('%s (%s)', $config['app_name'], $config['app_contact']));
     $client->getEventDispatcher()->addListener('request.before_send', function (Event $event) use($authorization) {
         $event['request']->addHeader('Authorization', $authorization);
     });
     return $client;
 }
コード例 #10
0
 /**
  * {@inheritdoc}
  */
 public static function factory($config = array())
 {
     $default = array('url' => false, 'munchkin_id' => false, 'version' => 1, 'bulk' => false);
     $required = array('client_id', 'client_secret', 'version');
     $config = Collection::fromConfig($config, $default, $required);
     $url = $config->get('url');
     if (!$url) {
         $munchkin = $config->get('munchkin_id');
         if (!$munchkin) {
             throw new \Exception('Must provide either a URL or Munchkin code.');
         }
         $url = sprintf('https://%s.mktorest.com', $munchkin);
     }
     $grantType = new Credentials($url, $config->get('client_id'), $config->get('client_secret'));
     $auth = new Oauth2Plugin($grantType);
     if ($config->get('bulk') === true) {
         $restUrl = sprintf('%s/bulk/v%d', rtrim($url, '/'), $config->get('version'));
     } else {
         $restUrl = sprintf('%s/rest/v%d', rtrim($url, '/'), $config->get('version'));
     }
     $client = new self($restUrl, $config);
     $client->addSubscriber($auth);
     $client->setDescription(ServiceDescription::factory(__DIR__ . '/service.json'));
     $client->setDefaultOption('headers/Content-Type', 'application/json');
     return $client;
 }
コード例 #11
0
ファイル: BasecampClient.php プロジェクト: bigset1/blueridge
 /**
  * @param array $config
  * @return \Guzzle\Service\Client|BasecampClient
  * @throws \Guzzle\Common\Exception\InvalidArgumentException
  */
 public static function factory($config = array())
 {
     $default = array('base_url' => 'https://basecamp.com/', 'version' => 'v1', 'token' => null, 'user_agent' => null, 'auth_method' => 'oauth');
     $required = [];
     $config = Collection::fromConfig($config, $default, $required);
     $client = new self($config->get('base_url'), $config);
     if (empty($config['token'])) {
         throw new InvalidArgumentException("Config must contain token when using oath");
     }
     $authorization = sprintf('Bearer %s', $config['token']);
     if (!isset($authorization)) {
         throw new InvalidArgumentException("Config must contain valid authentication method");
     }
     // Attach a service description to the client
     $description = ServiceDescription::factory(__DIR__ . '/Resources/service.php');
     $client->setDescription($description);
     // Set required User-Agent
     $client->setUserAgent($config['user_agent']);
     $client->getEventDispatcher()->addListener('request.before_send', function (Event $event) use($authorization) {
         $event['request']->addHeader('Authorization', $authorization);
     });
     // Add cache plugin
     $cachePlugin = new CachePlugin(['storage' => new DefaultCacheStorage(new DoctrineCacheAdapter(new ApcCache()))]);
     $client->addSubscriber($cachePlugin);
     return $client;
 }
コード例 #12
0
 public static function factory($config = array(), $required = array())
 {
     if (!defined('static::ENDPOINT')) {
         throw new Exception\ServiceEndpointException('A client must have an endpoint');
     }
     $default = array('base_url' => '{scheme}://{domain}/' . static::ENDPOINT);
     $required = array_merge(array('scheme', 'domain', 'base_url'), $required);
     $config = Collection::fromConfig($config, $default, $required);
     $client = new static($config->get('base_url'), $config);
     $refClass = new \ReflectionClass(get_called_class());
     $serviceDefinitionPath = dirname($refClass->getFileName());
     $classNamePieces = explode('\\', get_called_class());
     $serviceDefinitionFile = array_pop($classNamePieces) . '.json';
     switch (true) {
         case is_readable(dirname($serviceDefinitionPath) . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . $serviceDefinitionFile):
             $serviceDefinition = $serviceDefinitionPath . DIRECTORY_SEPARATOR . 'Resources' . DIRECTORY_SEPARATOR . $serviceDefinitionFile;
             break;
         case is_readable($serviceDefinitionPath . DIRECTORY_SEPARATOR . $serviceDefinitionFile):
             $serviceDefinition = $serviceDefinitionPath . DIRECTORY_SEPARATOR . $serviceDefinitionFile;
             break;
         default:
             throw new Exception\ClientConfigurationException('A client must have a service definition. Could not read the file "' . $serviceDefinition . '"');
     }
     $description = ServiceDescription::factory($serviceDefinition);
     $client->setDescription($description);
     return $client;
 }
コード例 #13
0
 /**
  * Loads the service description from the service description file
  *
  * @param string $description_file The service description file
  * @return ServiceDescription
  * @throws InvalidArgumentException If the description file doesn't exist or cannot be read
  */
 public function getServiceDescriptionFromFile($description_file)
 {
     if (!file_exists($description_file) || !is_readable($description_file)) {
         throw new InvalidArgumentException('Unable to read API definition schema');
     }
     return ServiceDescription::factory($description_file);
 }
コード例 #14
0
 public function setUp()
 {
     $mockError = 'Guzzle\\Tests\\Mock\\ErrorResponseMock';
     $description = ServiceDescription::factory(array('operations' => array('works' => array('httpMethod' => 'GET', 'errorResponses' => array(array('code' => 500, 'class' => $mockError), array('code' => 503, 'reason' => 'foo', 'class' => $mockError), array('code' => 200, 'reason' => 'Error!', 'class' => $mockError))), 'bad_class' => array('httpMethod' => 'GET', 'errorResponses' => array(array('code' => 500, 'class' => 'Does\\Not\\Exist'))), 'does_not_implement' => array('httpMethod' => 'GET', 'errorResponses' => array(array('code' => 500, 'class' => __CLASS__))), 'no_errors' => array('httpMethod' => 'GET'), 'no_class' => array('httpMethod' => 'GET', 'errorResponses' => array(array('code' => 500))))));
     $this->client = new Client($this->getServer()->getUrl());
     $this->client->setDescription($description);
 }
コード例 #15
0
 /**
  * @param array $config
  * @return \Guzzle\Service\Client|BasecampClient
  * @throws \Guzzle\Common\Exception\InvalidArgumentException
  */
 public static function factory($config = array())
 {
     $default = array('base_url' => 'https://basecamp.com/{user_id}/api/{version}/', 'version' => 'v1', 'auth' => 'http', 'token' => null, 'username' => null, 'password' => null);
     $required = array('user_id', 'app_name', 'app_contact');
     $config = Collection::fromConfig($config, $default, $required);
     $client = new self($config->get('base_url'), $config);
     if ($config['auth'] === 'http') {
         if (!isset($config['username'], $config['password'])) {
             throw new InvalidArgumentException("Config must contain username and password when using http auth");
         }
         $authorization = 'Basic ' . base64_encode($config['username'] . ':' . $config['password']);
     }
     if ($config['auth'] === 'oauth') {
         if (!isset($config['token'])) {
             throw new InvalidArgumentException("Config must contain token when using oauth");
         }
         $authorization = sprintf('Bearer %s', $config['token']);
     }
     if (!isset($authorization)) {
         throw new InvalidArgumentException("Config must contain valid authentication method");
     }
     // Attach a service description to the client
     $description = ServiceDescription::factory(__DIR__ . '/Resources/service.php');
     $client->setDescription($description);
     // Set required User-Agent
     $client->setUserAgent(sprintf('%s (%s)', $config['app_name'], $config['app_contact']));
     $client->getEventDispatcher()->addListener('request.before_send', function (Event $event) use($authorization) {
         $event['request']->addHeader('Authorization', $authorization);
     });
     return $client;
 }
コード例 #16
0
 /**
  * {@inheritdoc}
  */
 public function build($config, array $options = null)
 {
     if (!$this->loader) {
         $this->loader = new JsonLoader();
     }
     return ServiceDescription::factory($this->loader->parseJsonFile($config));
 }
コード例 #17
0
 /**
  * Class constructor
  *
  * Call parent constructor and attach an event listener that in turn will attach listeners to
  * the request based on the command being called.
  *
  * @param string $baseUrl The base URL to Imbo
  * @param array|Collection $config Client configuration
  */
 public function __construct($baseUrl, $config)
 {
     parent::__construct($baseUrl, $config);
     if (empty($config['serverUrls'])) {
         $config['serverUrls'] = array($baseUrl);
     }
     $this->setServerUrls($config['serverUrls']);
     $this->setDescription(ServiceDescription::factory(__DIR__ . '/service.php'));
     $this->setUserAgent('ImboClient/' . Version::VERSION, true);
     // Attach event listeners that handles the signing of write operations and the appending of
     // access tokens to requests that require this
     $dispatcher = $this->getEventDispatcher();
     $dispatcher->addSubscriber(new EventSubscriber\AccessToken());
     $dispatcher->addSubscriber(new EventSubscriber\Authenticate());
     $dispatcher->addSubscriber(new EventSubscriber\PublicKey());
     $client = $this;
     $dispatcher->addListener('command.before_send', function ($event) use($client) {
         $client->currentCommand = $event['command']->getName();
     });
     $dispatcher->addListener('request.error', function ($event) use($client) {
         if ($client->currentCommand === 'GetServerStatus') {
             // Stop propagation of the event when there is an error with the server status
             $event->stopPropagation();
             $client->currentCommand = null;
         }
     });
 }
コード例 #18
0
ファイル: Sdata.php プロジェクト: cviebrock/sdata-laravel
 public static function factory($config = array())
 {
     // The following values are required when creating the client
     $required = array('base_url', 'username', 'password');
     // Merge in default settings and validate the config
     $config = Collection::fromConfig($config, array(), $required);
     // Create a new sData client
     $client = new self($config->get('base_url'), $config);
     // JSON by default
     $client->setDefaultOption('query/format', 'json');
     // Authentication
     $client->setDefaultOption('auth', array($config->get('username'), $config->get('password'), 'Basic'));
     // Strip the BOM from results
     $client->addSubscriber(new StripBomPlugin());
     // Optional logging
     if ($config->get('log')) {
         $client->getEventDispatcher()->addListener('request.before_send', function (Event $event) {
             $req = $event['request'];
             \Log::info('sData', ['request' => $req->getMethod() . ' ' . $req->getResource()]);
         });
     }
     // Set the service description
     $services = \Config::get('sdata::services');
     if (!empty($services)) {
         $client->setDescription(ServiceDescription::factory($services));
     }
     // Done
     return $client;
 }
コード例 #19
0
ファイル: TwuzzleClient.php プロジェクト: parkji/twuzzle
 /**
  * @param string $serviceDescription
  * @param array $config
  * @return \Guzzle\Service\Client
  */
 public static function factory($config = array())
 {
     if (!isset($config['serviceDescription'])) {
         throw new \Exception("Cannot create a twuzzle client without a service description");
     }
     $oauthConfig = array();
     if (!isset($config['consumerKey'])) {
         throw new \Exception("Cannot create an twuzzle client without a consumer key");
     } else {
         $oauthConfig['consumer_key'] = $config['consumerKey'];
     }
     if (!isset($config['consumerSecret'])) {
         throw new \Exception("Cannot create an twuzzle client without a consumer secret");
     } else {
         $oauthConfig['consumer_secret'] = $config['consumerSecret'];
     }
     if (isset($config['token']) && !empty($config['token'])) {
         $oauthConfig['token'] = $config['token'];
     }
     if (isset($config['tokenSecret']) && !empty($config['tokenSecret'])) {
         $oauthConfig['token_secret'] = $config['tokenSecret'];
     }
     $client = new self();
     $client->setDescription(ServiceDescription::factory($config['serviceDescription']));
     $oauth = new OauthPlugin($oauthConfig);
     $client->addSubscriber($oauth);
     return $client;
 }
コード例 #20
0
 /**
  *  Set Guzzle Securepass services description file
  */
 protected function setServiceDescription()
 {
     // load service description file
     $serviceDescriptionFile = __DIR__ . '/Resources/services.json';
     // set service description
     $descriptions = ServiceDescription::factory($serviceDescriptionFile);
     $this->client->setDescription($descriptions);
 }
コード例 #21
0
ファイル: Client.php プロジェクト: rfink/edmunds-php-api
 /**
  * {@inheritDoc}
  */
 public static function factory($config = array())
 {
     $config = self::prepareConfig($config);
     $client = new static($config->get('base_url'), $config->get('api_key'), $config->get('version'));
     $description = ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'service.json');
     $client->setDescription($description);
     return $client;
 }
コード例 #22
0
ファイル: Client.php プロジェクト: uniplaces/fastc
 /**
  * @param string|array $config  File to build or array of operation information
  * @param array        $options Service description factory options
  *
  * @return GuzzleServiceDescription
  */
 protected function getServiceDescription($config, array $options = array())
 {
     // Adds support for YML
     if (is_string($config) && pathinfo($config, PATHINFO_EXTENSION) === 'yml') {
         $config = static::readYaml($config);
     }
     return GuzzleServiceDescription::factory($config, $options);
 }
コード例 #23
0
 /**
  * Initializes initializer
  *
  * @param Client $client
  * @param array  $parameters
  */
 public function __construct(Client $client, array $parameters)
 {
     $this->client = $client;
     $this->parameters = $parameters;
     if (!empty($parameters['service_descriptions'])) {
         $this->client->setDescription(ServiceDescription::factory($parameters['service_descriptions']));
     }
 }
コード例 #24
0
ファイル: Client.php プロジェクト: janiv/shelf
 /**
  * Factory method to create the client, add the service description, and set
  * the user again
  *
  * @param array $config
  *
  * @return Client
  */
 public static function factory($config = array())
 {
     $client = new self();
     $description = ServiceDescription::factory(__DIR__ . '/Config/endpoints.json');
     $client->setDescription($description);
     $client->setUserAgent('Shelf/' . Version::VERSION, true);
     return $client;
 }
コード例 #25
0
 public function getServiceDescription()
 {
     $description = json_decode($this->getFileContents(), true);
     if ($description && isset($description['apiVersion'])) {
         return ServiceDescription::factory($description);
     }
     return null;
 }
コード例 #26
0
 public function __construct($description_path, $baseUrl = '', $config = null)
 {
     parent::__construct($baseUrl, $config);
     $this->setDescription(ServiceDescription::factory($description_path));
     $adapter = new DoctrineCacheAdapter(new ArrayCache());
     $cache = new CachePlugin($adapter, true);
     $this->addSubscriber($cache);
 }
コード例 #27
0
 public function __construct(LoggerInterface $logger, GClient $client, $account_name = '')
 {
     $this->facters = array();
     $this->logger = $logger;
     $this->account_name = $account_name;
     $this->client = $client;
     $this->client->setDescription(ServiceDescription::factory(__DIR__ . '/InventoryService.json'));
 }
コード例 #28
0
ファイル: Qiita.php プロジェクト: cocoiti/qiita-php
 /**
  * Constructor
  *
  * @param string $accessToken
  */
 public function __construct($accessToken)
 {
     $this->accessToken = $accessToken;
     $this->client = new Client();
     $this->client->setDescription(ServiceDescription::factory(__DIR__ . '/Resources/config/service.json'));
     $this->client->getEventDispatcher()->addListener('client.create_request', [$this, 'onClientCreateRequest']);
     $this->client->getEventDispatcher()->addListener('request.error', [$this, 'onRequestError']);
 }
コード例 #29
0
    public static function factory($config = array()) {
        $client = new self(null, $config);

        $description = ServiceDescription::factory(__DIR__ . '/descriptor.php');
        $client->setDescription($description);

        return $client;
    }
コード例 #30
0
 /**
  * Build the Kinvey API client.
  *
  * @return Guzzle\Service\Client
  */
 public function buildKinveyAPIClient()
 {
     require __DIR__ . '/Client/Service/APIV2Description.php';
     require __DIR__ . '/Client/Service/ServiceBuilder.php';
     $client = ServiceBuilder::factory($serviceBuilder)->get('KinveyClient');
     $client->setDescription(ServiceDescription::factory($APIV2Description));
     return $client;
 }