Example #1
0
 public function provider()
 {
     $c = 'Guzzle\\Common\\Validation\\AnyMatch';
     if (!class_exists('Guzzle\\Service\\Inspector')) {
         $this->markTestSkipped('Inspector not present');
     }
     $i = Inspector::getInstance();
     return array(array($c, 'a', array('constraints' => 'type:string', 'inspector' => $i), true, null), array($c, 'a', array('type:string', 'inspector' => $i), true, null), array($c, 'foo', array('constraints' => 'type:string;type:numeric'), true, null), array($c, new \stdClass(), array('constraints' => 'type:string;type:numeric', 'inspector' => $i), 'Value type must match one of type:string OR type:numeric', null), array($c, 'foo', array('constraints' => 'type:numeric;type:boolean;ip;email', 'inspector' => $i), 'Value type must match one of type:numeric OR type:boolean OR ip OR email', null), array($c, 'http://www.example.com', array('constraints' => 'ip;url', 'inspector' => $i), true, null), array($c, '192.168.16.148', array('constraints' => 'ip;url', 'inspector' => $i), true, null), array($c, 'foo', array('constraints' => 'email;choice:foo,bar;ip;array', 'inspector' => $i), true, null), array($c, 'bar', array('constraints' => 'email;choice:foo,bar;ip;array', 'inspector' => $i), true, null), array($c, '192.168.16.48', array('constraints' => 'email;choice:foo,bar;ip;array', 'inspector' => $i), true, null), array($c, array(), array('constraints' => 'email;choice:foo,bar;ip;array', 'inspector' => $i), true, null), array($c, '*****@*****.**', array('constraints' => 'email;choice:foo,bar;ip;array', 'inspector' => $i), true, null), array($c, new \stdClass(), array('constraints' => 'type:object', 'inspector' => $i), true, null));
 }
 /**
  * Factory method to create a new OpenstackClient
  *
  * @static
  *
  * @param array|Collection $config Configuration data. Array keys:
  *                                 auth_url - Authentication service URL
  *                                 username - API username
  *                                 password - API password
  *                                 tenantName - API tenantName
  *
  * @return \Guzzle\Common\FromConfigInterface|OpenstackClient|\Guzzle\Service\Client
  */
 public static function factory($config = array())
 {
     $default = array('compute_type' => 'compute', 'identity_type' => 'identity', 'storage_type' => 'storage', 'region' => 'RegionOne');
     $required = array('auth_url');
     $config = Inspector::prepareConfig($config, $default, $required);
     $client = new self($config->get('auth_url'), $config->get('username'), $config->get('password'), $config->get('tenantName'));
     $client->setConfig($config);
     return $client;
 }
 /**
  * Factory method to create a new ComputeClient
  *
  * @static
  *
  *
  * @param array|Collection $config Configuration data. Array keys:
  *                                 base_url - Base URL of web service
  *                                 token - Authentication token
  *                                 tenant_id Tenant id
  *
  * @return \Guzzle\Common\FromConfigInterface|ComputeClient|\Guzzle\Service\Client
  */
 public static function factory($config = array())
 {
     $default = array();
     $required = array('base_url', 'token', 'tenant_id');
     $config = Inspector::prepareConfig($config, $default, $required);
     $client = new self($config->get('base_url'), $config->get('token'), $config->get('tenant_id'));
     $client->setConfig($config);
     $client->getEventDispatcher()->addSubscriber(new AuthenticationObserver());
     return $client;
 }
 public static function factory($config = array())
 {
     $default = array('base_url' => '{scheme}://blockchain.info/merchant/{guid}', 'scheme' => 'https');
     $required = array('base_url', 'guid', 'password');
     $config = Inspector::prepareConfig($config, $default, $required);
     $client = new self($config->get('base_url'), $config->get('guid'), $config->get('password'));
     $client->setConfig($config);
     // Uncomment the following two lines to use an XML service description
     $client->setDescription(ServiceDescription::factory(__DIR__ . '/' . 'client.xml'));
     return $client;
 }
Example #5
0
 public static function factory($config = array())
 {
     $default = array('base_url' => '{scheme}://mtgox.com/', 'scheme' => 'https');
     $required = array('base_url', 'api_key', 'api_secret');
     $config = Inspector::prepareConfig($config, $default, $required);
     $client = new self($config->get('base_url'), $config->get('api_key'), $config->get('api_secret'));
     $client->setConfig($config);
     // Uncomment the following two lines to use an XML service description
     $client->setDescription(ServiceDescription::factory(__DIR__ . '/' . 'client.xml'));
     return $client;
 }
 /**
  * Create an instance of the client
  * 
  * @param array $config
  * 
  * @return \GuzzleAmazonWebservices\ProductAdvertising
  */
 public static function factory($config = array())
 {
     $defaults = array('base_url' => '{{scheme}}://{{locale}}/onca/xml', 'scheme' => 'http', 'locale' => self::LOCALE_US, 'version' => self::VERSION);
     $required = array('access_key', 'secret_key', 'associate_tag');
     $config = Inspector::prepareConfig($config, $defaults, $required);
     $signature = new SignatureV2($config->get('access_key'), $config->get('secret_key'));
     $client = new self($config->get('base_url'), $config->get('access_key'), $config->get('secret_key'), $config->get('associate_tag'), $config->get('version'));
     $client->setConfig($config);
     $client->addSubscriber(new SignaturePlugin($signature, $config->get('version')));
     return $client;
 }
Example #7
0
 /**
  * Factory method to create a new SmsBoxClient
  *
  * @param array|Collection $config Configuration data. Array keys:
  *
  *    base_url - Base URL of the smsBox service endpoint
  *    username - API username
  *    password - API password
  *
  * @return SmsBoxClient
  */
 static function factory($config = array())
 {
     $default = array('test' => false);
     $required = array('base_url', 'username', 'password');
     $config = Inspector::prepareConfig($config, $default, $required);
     $client = new self($config->get('base_url'), $config->get('username'), $config->get('password'), $config->get('test'));
     $client->setConfig($config);
     // Add the XML service description to the client
     $description = ServiceDescription::factory(__DIR__ . DIRECTORY_SEPARATOR . 'guzzle_smsbox.xml');
     $client->setDescription($description);
     return $client;
 }
Example #8
0
 /**
  * @covers Guzzle\Service\Inspector::registerConstraint
  * @covers Guzzle\Service\Inspector::getConstraint
  * @covers Guzzle\Service\Inspector::getRegisteredConstraints
  */
 public function testRegistersCustomConstraints()
 {
     $constraintClass = 'Guzzle\\Common\\Validation\\Ip';
     Inspector::getInstance()->registerConstraint('mock', $constraintClass);
     Inspector::getInstance()->registerConstraint('mock_2', $constraintClass, array('version' => '4'));
     $this->assertArrayHasKey('mock', Inspector::getInstance()->getRegisteredConstraints());
     $this->assertArrayHasKey('mock_2', Inspector::getInstance()->getRegisteredConstraints());
     $this->assertInstanceOf($constraintClass, Inspector::getInstance()->getConstraint('mock'));
     $this->assertInstanceOf($constraintClass, Inspector::getInstance()->getConstraint('mock_2'));
     $this->assertTrue(Inspector::getInstance()->validateConstraint('mock', '192.168.16.121'));
     $this->assertTrue(Inspector::getInstance()->validateConstraint('mock_2', '10.1.1.0'));
 }
 /**
  * {@inheritdoc}
  */
 public function build($config, array $options = null)
 {
     if (!empty($config['types'])) {
         foreach ($config['types'] as $name => $type) {
             $default = array();
             if (!isset($type['class'])) {
                 throw new DescriptionBuilderException('Custom types require a class attribute');
             }
             foreach ($type as $key => $value) {
                 if ($key != 'name' && $key != 'class') {
                     $default[$key] = $value;
                 }
             }
             Inspector::getInstance()->registerConstraint($name, $type['class'], $default);
         }
     }
     $commands = array();
     if (!empty($config['commands'])) {
         foreach ($config['commands'] as $name => $command) {
             $name = $command['name'] = isset($command['name']) ? $command['name'] : $name;
             // Extend other commands
             if (!empty($command['extends'])) {
                 $originalParams = empty($command['params']) ? false : $command['params'];
                 $resolvedParams = array();
                 foreach ((array) $command['extends'] as $extendedCommand) {
                     if (empty($commands[$extendedCommand])) {
                         throw new DescriptionBuilderException("{$name} extends missing command {$extendedCommand}");
                     }
                     $toArray = $commands[$extendedCommand]->toArray();
                     $resolvedParams = empty($resolvedParams) ? $toArray['params'] : array_merge($resolvedParams, $toArray['params']);
                     $command = array_merge($toArray, $command);
                 }
                 $command['params'] = $originalParams ? array_merge($resolvedParams, $originalParams) : $resolvedParams;
             }
             // Use the default class
             $command['class'] = isset($command['class']) ? str_replace('.', '\\', $command['class']) : ServiceDescription::DEFAULT_COMMAND_CLASS;
             $commands[$name] = new ApiCommand($command);
         }
     }
     return new ServiceDescription($commands);
 }
 /**
  * {@inheritdoc}
  */
 protected function validateValue($value, array $options = array())
 {
     if (!isset($options['inspector'])) {
         $options['inspector'] = Inspector::getInstance();
     }
     $inspector = $options['inspector'];
     foreach (explode(';', $options['constraints']) as $constraint) {
         $constraint = trim($constraint);
         // Handle colon separated values
         if (strpos($constraint, ':')) {
             list($constraint, $args) = explode(':', $constraint, 2);
             $args = strpos($args, ',') !== false ? str_getcsv($args, ',', "'") : array($args);
         } else {
             $args = null;
         }
         if (true === $inspector->validateConstraint($constraint, $value, $args)) {
             return true;
         }
     }
     return 'Value type must match one of ' . implode(' OR ', explode(';', $options['constraints']));
 }
 /**
  * @covers Guzzle\Service\Description\XmlDescriptionBuilder
  * @covers Guzzle\Service\Description\ServiceDescription
  */
 public function testBuildsServiceUsingFile()
 {
     $x = new XmlDescriptionBuilder();
     $service = $x->build(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'TestData' . DIRECTORY_SEPARATOR . 'test_service.xml');
     $this->assertTrue($service->hasCommand('search'));
     $this->assertTrue($service->hasCommand('test'));
     $this->assertTrue($service->hasCommand('trends.location'));
     $this->assertTrue($service->hasCommand('geo.id'));
     $this->assertInstanceOf('Guzzle\\Service\\Description\\ApiCommand', $service->getCommand('search'));
     $this->assertInternalType('array', $service->getCommands());
     $this->assertEquals(7, count($service->getCommands()));
     $this->assertNull($service->getCommand('missing'));
     $command = $service->getCommand('test');
     $this->assertInstanceOf('Guzzle\\Service\\Description\\ApiCommand', $command);
     $this->assertEquals('test', $command->getName());
     $this->assertInternalType('array', $command->getParams());
     $this->assertEquals(array('name' => 'bucket', 'required' => true, 'location' => 'path', 'doc' => 'Bucket location'), array_filter($command->getParam('bucket')->toArray()));
     $this->assertEquals('DELETE', $command->getMethod());
     $this->assertEquals('{{ bucket }}/{{ key }}{{ format }}', $command->getUri());
     $this->assertEquals('Documentation', $command->getDoc());
     $this->assertArrayHasKey('custom_filter', Inspector::getInstance()->getRegisteredConstraints());
 }
 /**
  * {@inheritdoc}
  */
 public function build($data, array $options = null)
 {
     if (!empty($data['types'])) {
         foreach ($data['types'] as $name => $type) {
             $default = array();
             if (!isset($type['class'])) {
                 throw new DescriptionBuilderException('Custom types require a class attribute');
             }
             foreach ($type as $key => $value) {
                 if ($key != 'name' && $key != 'class') {
                     $default[$key] = $value;
                 }
             }
             Inspector::getInstance()->registerConstraint($name, $type['class'], $default);
         }
     }
     $commands = array();
     if (!empty($data['commands'])) {
         foreach ($data['commands'] as $name => $command) {
             $name = $command['name'] = isset($command['name']) ? $command['name'] : $name;
             // Extend other commands
             if (!empty($command['extends'])) {
                 if (empty($commands[$command['extends']])) {
                     throw new DescriptionBuilderException($name . ' extends missing command ' . $command['extends']);
                 }
                 $params = array_merge($commands[$command['extends']]->getParams(), !empty($command['params']) ? $command['params'] : array());
                 $command = array_merge($commands[$command['extends']]->toArray(), $command);
                 $command['params'] = $params;
             }
             // Use the default class
             $command['class'] = isset($command['class']) ? str_replace('.', '\\', $command['class']) : ServiceDescription::DEFAULT_COMMAND_CLASS;
             $commands[$name] = new ApiCommand($command);
         }
     }
     return new ServiceDescription($commands);
 }
 /**
  * Prepare the command for executing and create a request object.
  *
  * @return RequestInterface Returns the generated request
  * @throws CommandException if a client object has not been set previously
  *      or in the prepare()
  */
 public function prepare()
 {
     if (!$this->isPrepared()) {
         if (!$this->client) {
             throw new CommandException('A Client object must be associated with the command before it can be prepared.');
         }
         // Fail on missing required arguments
         if ($this->apiCommand) {
             Inspector::getInstance()->validateConfig($this->apiCommand->getParams(), $this, true);
         } else {
             Inspector::getInstance()->validateClass(get_class($this), $this, true);
         }
         $this->build();
         // Add custom request headers set on the command
         $headers = $this->get('headers');
         if ($headers && $headers instanceof Collection) {
             foreach ($headers as $key => $value) {
                 $this->request->setHeader($key, $value);
             }
         }
     }
     return $this->getRequest();
 }
 /**
  * @covers Guzzle\Service\Description\ArrayDescriptionBuilder::build
  */
 public function testRegistersCustomTypes()
 {
     ServiceDescription::factory(array('types' => array('foo' => array('class' => 'Guzzle\\Common\\Validation\\Regex', 'pattern' => '/[0-9]+/'))));
     $valid = Inspector::getInstance()->validateConstraint('foo', 'abc');
     $this->assertEquals('abc does not match the regular expression', $valid);
 }
Example #15
0
 /**
  * {@inheritdoc}
  * @throws ValidationException when validation errors occur
  */
 public function validate(Collection $config, Inspector $inspector = null)
 {
     $inspector = $inspector ?: Inspector::getInstance();
     $typeValidation = $inspector->getTypeValidation();
     $errors = array();
     foreach ($this->params as $name => $arg) {
         $currentValue = $config->get($name);
         $configValue = $arg->getValue($currentValue);
         // Inject configuration information into the config value
         if ($configValue && is_string($configValue)) {
             $configValue = $config->inject($configValue);
         }
         // Ensure that required arguments are set
         if ($arg->getRequired() && ($configValue === null || $configValue === '')) {
             $errors[] = 'Requires that the ' . $name . ' argument be supplied.' . ($arg->getDoc() ? '  (' . $arg->getDoc() . ').' : '');
             continue;
         }
         // Ensure that the correct data type is being used
         if ($typeValidation && $configValue !== null && ($argType = $arg->getType())) {
             $validation = $inspector->validateConstraint($argType, $configValue, $arg->getTypeArgs());
             if ($validation !== true) {
                 $errors[] = $name . ': ' . $validation;
                 $config->set($name, $configValue);
                 continue;
             }
         }
         $configValue = $arg->filter($configValue);
         // Update the config value if it changed
         if (!$configValue !== $currentValue) {
             $config->set($name, $configValue);
         }
         // Check the length values if validating data
         $argMinLength = $arg->getMinLength();
         if ($argMinLength && strlen($configValue) < $argMinLength) {
             $errors[] = 'Requires that the ' . $name . ' argument be >= ' . $arg->getMinLength() . ' characters.';
         }
         $argMaxLength = $arg->getMaxLength();
         if ($argMaxLength && strlen($configValue) > $argMaxLength) {
             $errors[] = 'Requires that the ' . $name . ' argument be <= ' . $arg->getMaxLength() . ' characters.';
         }
     }
     if (!empty($errors)) {
         $e = new ValidationException('Validation errors: ' . implode("\n", $errors));
         $e->setErrors($errors);
         throw $e;
     }
 }
Example #16
0
 /**
  * @covers Guzzle\Service\Command\AbstractCommand::setInspector
  * @covers Guzzle\Service\Command\AbstractCommand::getInspector
  */
 public function testInspectorCanBeInjected()
 {
     $instance = Inspector::getInstance();
     $command = new MockCommand();
     $refObject = new \ReflectionObject($command);
     $method = $refObject->getMethod('getInspector');
     $method->setAccessible(true);
     $this->assertSame($instance, $method->invoke($command));
     $newInspector = new Inspector();
     $command->setInspector($newInspector);
     $this->assertSame($newInspector, $method->invoke($command));
 }
 /**
  * @covers Guzzle\Service\Inspector::validateConfig
  */
 public function testSkipsFurtherValidationIfNotSet()
 {
     $i = Inspector::getInstance();
     // Ensure that the type is not validated
     $this->assertEquals(true, $i->validateConfig(array('data' => new ApiParam(array('type' => 'string'))), new Collection(), true));
 }
Example #18
0
 /**
  * Get the Inspector used with the Command
  *
  * @return Inspector
  */
 protected function getInspector()
 {
     if (!$this->inspector) {
         $this->inspector = Inspector::getInstance();
     }
     return $this->inspector;
 }
Example #19
0
 /**
  * @covers Guzzle\Service\Description\ApiCommand::validate
  */
 public function testTypeValidationCanBeDisabled()
 {
     $i = Inspector::getInstance();
     $i->setTypeValidation(false);
     $command = $this->getTestCommand();
     $command->validate(new Collection(array('data' => new \stdClass())), $i);
 }
Example #20
0
 /**
  * Factory method to create a new mock client
  *
  * @param array|Collection $config Configuration data. Array keys:
  *    base_url - Base URL of web service
  *    api_version - API version
  *    scheme - URI scheme: http or https
  *  * username - API username
  *  * password - API password
  *  * subdomain - Unfuddle account subdomain
  *
  * @return MockClient
  */
 public static function factory($config = array())
 {
     $config = Inspector::prepareConfig($config, array('base_url' => '{{scheme}}://127.0.0.1:8124/{{api_version}}/{{subdomain}}', 'scheme' => 'http', 'api_version' => 'v1'), array('username', 'password', 'subdomain'));
     return new self($config->get('base_url'), $config);
 }
Example #21
0
 /**
  * Create a new OAuth 1.0 plugin
  *
  * @param array $config Configuration array containing these parameters:
  *     - string 'consumer_key'         Consumer key
  *     - string 'consumer_secret'      Consumer secret
  *     - string 'token'                Token
  *     - string 'token_secret'         Token secret
  *     - string 'version'              OAuth version.  Defaults to 1.0
  *     - string 'signature_method'     Custom signature method
  *     - bool   'disable_post_params'  Set to true to prevent POST parameters from being signed
  *     - array|Closure 'signature_callback' Custom signature callback that accepts a string to sign and a signing key
  */
 public function __construct($config)
 {
     $this->config = Inspector::prepareConfig($config, array('version' => '1.0', 'consumer_key' => 'anonymous', 'consumer_secret' => 'anonymous', 'signature_method' => 'HMAC-SHA1', 'signature_callback' => function ($stringToSign, $key) {
         return hash_hmac('sha1', $stringToSign, $key, true);
     }), array('signature_method', 'signature_callback', 'version', 'consumer_key', 'consumer_secret'));
 }