Related
I have an api call that amongst it has Url's that are recalled in it's returned JSON.
I need to find those returned urls that have in them the string used for the original get request and have statuses of 200. I tried using the strpos method, but that didn't seem to work.
public function getCompanyData() {
$client = new Client();
$response = $client->request('GET', 'https://api.github.com/orgs/fakename');
$statusCode = $response->getStatusCode();
$body = $response->getBody()->getContents();
$confirmed = strpos($body,'api.github.com/orgs/fakename');
if($statusCode === 200 && $confirmed !== false) {
return $body;
}
else {
return $statusCode." Error";
}
}
Returned JSON -
{
"login": "fakename",
"id": 1214096,
"node_id": "***=",
"url": "https://api.github.com/orgs/fakename",
"repos_url": "https://api.github.com/orgs/fakename/repos",
"events_url": "https://api.github.com/orgs/fakename/events",
"hooks_url": "https://api.github.com/orgs/fakename/hooks",
"issues_url": "https://api.github.com/orgs/fakename/issues",
"members_url": "https://api.github.com/orgs/fakename/members{/member}",
"public_members_url": "https://api.github.com/orgs/fakename/public_members{/member}",
"avatar_url": "https://avatars3.githubusercontent.com/u/****?v=4",
"description": "",
"name": "fakename",
"company": null,
"blog": "fakename.com",
"location": null,
"email": null,
"twitter_username": null,
"is_verified": false,
"has_organization_projects": true,
"has_repository_projects": true,
"public_repos": 41,
"public_gists": 0,
"followers": 0,
"following": 0,
"html_url": "https://github.com/fakename",
"created_at": "2011-11-22T21:48:43Z",
"updated_at": "2020-09-11T23:05:04Z"
}
One approach would be as follows:
<?php
class SomeClass
{
/**
* #var int The status code of the last http request
*/
private $statusCode;
/**
* Get an array of decoded data from the given url.
* #param $url
* #return array
*/
public function getDataFromUrl($url) {
$client = new Client();
$response = $client->request('GET', $url);
$this->statusCode = $response->getStatusCode();
$body = $response->getBody()->getContents();
return $this->statusCode === 200 ? json_decode($body, true) : [];
}
/**
* Get all data for a given organization including nested ancillary data
* #param string $orgName
* #return array
*/
public function getCompanyData($orgName) {
$mainUrl = "https://api.github.com/orgs/$orgName";
$mainData = $this->getDataFromUrl($mainUrl);
if ($mainData && $this->statusCode === 200) {
$ancillaryUrls = $this->getAncillaryUrlsFromData($mainData, $orgName);
foreach ($ancillaryUrls as $property => $url) {
$ancillaryData = $this->getDataFromUrl($url);
$mainData[$property] = $ancillaryData;
}
}
return $mainData;
}
/**
* Get a JSON string containing all data for a given organization including nested ancillary data
* #param string $orgName
* #return array|mixed
*/
public function getCompanyDataAsJson($orgName) {
return json_encode($this->getCompanyData($orgName));
}
/**
* From the provided array of data, return an new array containing the ancillary urls
* which also need to be requested
* #param array $data
* #param string $orgName
* #return array
*/
public function getAncillaryUrlsFromData($data, $orgName) {
$urls = [];
if (is_array($data)) {
$targetUrl = "api.github.com/orgs/$orgName";
foreach ($data as $property => $value) {
// if property has '_url' and value is like our url, add it to our array of urls
if (strpos($property, '_url') !== false && strpos($value, $targetUrl) !== false) {
$cleanProp = str_replace('_url', '', $property);
$urls[$cleanProp] = $targetUrl;
}
}
}
return $urls;
}
}
Now, if you want the result as an array, you can call:
$someClass = new SomeClass();
$arrayOfData = $someClass->getCompanyData('fakename');
Or, if you want the result as a JSON string, you can call:
$someClass = new SomeClass();
$jsonData = $someClass->getCompanyDataAsJson('fakename');
And the response will have the following keys (in addition to the original main data) "repos", "events", "hooks", "issues", "members", "public_members" all filled with the responses from their individual calls.
Given a set of test data files
test001.txt
test002.txt
etc.
and expected results data files
expected001.txt
expected002.txt
etc.
I am using phpunit to test the data processing functionality:
public function test001()
{
$fn = "test001.txt";
$data = file_get_contents($fn);
// code to perform the test, and create $processedData from $data
$fn = "expected001.txt";
$expestedData = file_get_contents($fn);
$this->assertEquals($expestedData, $processedData);
}
The process code is exactly the same for all pairs of test data files and corresponding result data files.
Therefore, to apply the test on all the files I can make a loop:
public function test001to213()
{
for ($k = 0; $k < 213; $k++) {
$fn = "test".sprintf('%03d', $k).".txt";
$data = file_get_contents($fn);
// data process code to create $processedData from $data
$fn = "expected".sprintf('%03d', $k).".txt";
$expectedData = file_get_contents($fn);
$this->assertEquals($expectedData, $processedData);
}
}
However, this way I have 213 assertions in one test, and I loose the following benefits:
I cannot know what tests numbers failed/passed, since the test stops for first failed assertion.
On the second execution, I cannot run only the failed tests.
I cannot choose a specific test number x - to run in debug mode
Before adding more code to get this benefits, is there a better solution?
What phpunit features can help in this case?
You can use a data provider instead:
/**
* #dataProvider providerFilenames
*
* #param string $testFilename
* #param string $expectedFilename
*/
public function testContent($testFilename, $expectedFilename)
{
$data = file_get_contents($testFilename);
// code to perform the test, and create $processedData from $data
$processedData = '';
$expectedData = file_get_contents($expectedFilename);
$this->assertEquals($expectedData, $processedData);
}
/**
* #return \Generator
*/
public function providerFilenames()
{
for ($key = 0; $key < 213; ++$key) {
$testFilename = sprintf(
'test%03d.txt',
$key
);
$expectedFilename = sprintf(
'expected%03d.txt',
$key
);
/**
* by yielding with a name here, it's easier to tell which set failed
*/
$name = sprintf(
'this is set %03d',
$key
);
yield $name => [
$testFilename,
$expectedFilename ,
];
}
}
If you can't use generators yet, adjust the data provider to:
/**
* #return \Generator
*/
public function providerFilenames()
{
$keys = range(0, 213);
$names = array_map(function ($key) {
return sprintf(
'this is set %03d',
$key
);
}, $keys);
$data = array_combine(
$names,
$keys
);
return array_map(function ($key) {
$testFilename = sprintf(
'test%03d.txt',
$key
);
$expectedFilename = sprintf(
'expected%03d.txt',
$key
);
return [
$testFilename,
$expectedFilename
];
}, $data);
}
For reference, see:
https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.data-providers
http://php.net/manual/en/language.generators.syntax.php
http://php.net/manual/en/function.array-map.php
http://php.net/manual/en/function.array-combine.php
Based on this documentation , how to pass second parameter to the rule method?
This is my custom rule
public function email_exists($email, $exclude_id=NULL)
{
if ( $exclude_id !== NULL ) $this->db->where_not_in('id', $exclude_id);
$result = $this->db->select('id')->from('users')->where('email', $email)->get();
if ( $result->num_rows() > 0 ) {
$this->form_validation->set_message('email_exists', '{field} has been used by other user.');
return FALSE;
} else {
return TRUE;
}
}
and this is how i call it from controller
$rules = [
[
'field' => 'email',
'label' => 'Email',
'rules' => [
'required',
'trim',
'valid_email',
'xss_clean',
['email_exists', [$this->m_user, 'email_exists']]
]
]
];
$this->form_validation->set_rules($rules);
How can I pass second parameter to email_exists method?
Its seems CI does not provide a mechanism for this. I found several approaches to solve this. First way, you can hack the file system (Form_validation.php) and modify some script at line 728
if ( preg_match('/(.*?)\[(.*)\]/', $rule[1], $rulea) ) {
$method = $rulea[1];
$extra = $rulea[2];
} else {
$method = $rule[1];
$extra = NULL;
}
$result = is_array($rule)
? $rule[0]->{$method}($postdata, $extra)
: $rule($postdata);
Second way you can extends CI_Form_validation core and add your custom rule in it. I found the detail about this on codeigniter documentation.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
public function __construct()
{
parent::__construct();
}
public function check_conflict_email($str, $exclude_id=NULL)
{
if ( $exclude_id !== NULL ) $this->CI->db->where_not_in('id', $exclude_id);
$result = $this->CI->db->select('id')->from('users')->where('email', $str)->get();
if ( $result->num_rows() > 0 ) {
$this->set_message('check_conflict_email', '{field} has been used by other user.');
return FALSE;
} else {
return TRUE;
}
}
}
/* End of file MY_Form_validation.php */
/* Location: ./application/libraries/MY_Form_validation.php */
Third way, and I think this is the best way to do it. Thanks to skunkbad for provide the solution
$rules = [
[
'field' => 'email',
'label' => 'Email',
'rules' => [
'required',
'trim',
'valid_email',
'xss_clean',
[
'email_exists',
function( $str ) use ( $second_param ){
return $this->m_user->email_exists( $str, $second_param );
}
]
]
]
];
Just do it the right way (at least for CI 2.1+) as described in the docs:
$this->form_validation->set_rules('uri', 'URI', 'callback_check_uri['.$this->input->post('id').']');
// Later:
function check_uri($field, $id){
// your callback code here
}
If this is not working than make an hidden field in your form for $exclude_id and check that directly in your callback via
$exclude_id = $this->input->post('exclude_id');//or whatever the field name is
More here
I use CI 3.1.10 and this issue still exists, I extend the library and use the same way as callback
array('username_callable[param]' => array($this->some_model, 'some_method'))
Extended Form_validation library:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation {
/**
* Executes the Validation routines
*
* #param array
* #param array
* #param mixed
* #param int
* #return mixed
*/
protected function _execute($row, $rules, $postdata = NULL, $cycles = 0)
{
// If the $_POST data is an array we will run a recursive call
//
// Note: We MUST check if the array is empty or not!
// Otherwise empty arrays will always pass validation.
if (is_array($postdata) && ! empty($postdata))
{
foreach ($postdata as $key => $val)
{
$this->_execute($row, $rules, $val, $key);
}
return;
}
$rules = $this->_prepare_rules($rules);
foreach ($rules as $rule)
{
$_in_array = FALSE;
// We set the $postdata variable with the current data in our master array so that
// each cycle of the loop is dealing with the processed data from the last cycle
if ($row['is_array'] === TRUE && is_array($this->_field_data[$row['field']]['postdata']))
{
// We shouldn't need this safety, but just in case there isn't an array index
// associated with this cycle we'll bail out
if ( ! isset($this->_field_data[$row['field']]['postdata'][$cycles]))
{
continue;
}
$postdata = $this->_field_data[$row['field']]['postdata'][$cycles];
$_in_array = TRUE;
}
else
{
// If we get an array field, but it's not expected - then it is most likely
// somebody messing with the form on the client side, so we'll just consider
// it an empty field
$postdata = is_array($this->_field_data[$row['field']]['postdata'])
? NULL
: $this->_field_data[$row['field']]['postdata'];
}
// Is the rule a callback?
$callback = $callable = FALSE;
if (is_string($rule))
{
if (strpos($rule, 'callback_') === 0)
{
$rule = substr($rule, 9);
$callback = TRUE;
}
}
elseif (is_callable($rule))
{
$callable = TRUE;
}
elseif (is_array($rule) && isset($rule[0], $rule[1]) && is_callable($rule[1]))
{
// We have a "named" callable, so save the name
$callable = $rule[0];
$rule = $rule[1];
}
// Strip the parameter (if exists) from the rule
// Rules can contain a parameter: max_length[5]
$param = FALSE;
if ( ! $callable && preg_match('/(.*?)\[(.*)\]/', $rule, $match))
{
$rule = $match[1];
$param = $match[2];
}
elseif ( is_string($callable) && preg_match('/(.*?)\[(.*)\]/', $callable, $match))
{
$param = $match[2];
}
// Ignore empty, non-required inputs with a few exceptions ...
if (
($postdata === NULL OR $postdata === '')
&& $callback === FALSE
&& $callable === FALSE
&& ! in_array($rule, array('required', 'isset', 'matches'), TRUE)
)
{
continue;
}
// Call the function that corresponds to the rule
if ($callback OR $callable !== FALSE)
{
if ($callback)
{
if ( ! method_exists($this->CI, $rule))
{
log_message('debug', 'Unable to find callback validation rule: '.$rule);
$result = FALSE;
}
else
{
// Run the function and grab the result
$result = $this->CI->$rule($postdata, $param);
}
}
else
{
$result = is_array($rule)
? $rule[0]->{$rule[1]}($postdata, $param)
: $rule($postdata);
// Is $callable set to a rule name?
if ($callable !== FALSE)
{
$rule = $callable;
}
}
// Re-assign the result to the master data array
if ($_in_array === TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result;
}
}
elseif ( ! method_exists($this, $rule))
{
// If our own wrapper function doesn't exist we see if a native PHP function does.
// Users can use any native PHP function call that has one param.
if (function_exists($rule))
{
// Native PHP functions issue warnings if you pass them more parameters than they use
$result = ($param !== FALSE) ? $rule($postdata, $param) : $rule($postdata);
if ($_in_array === TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result;
}
}
else
{
log_message('debug', 'Unable to find validation rule: '.$rule);
$result = FALSE;
}
}
else
{
$result = $this->$rule($postdata, $param);
if ($_in_array === TRUE)
{
$this->_field_data[$row['field']]['postdata'][$cycles] = is_bool($result) ? $postdata : $result;
}
else
{
$this->_field_data[$row['field']]['postdata'] = is_bool($result) ? $postdata : $result;
}
}
// Did the rule test negatively? If so, grab the error.
if ($result === FALSE)
{
// Callable rules might not have named error messages
if ( ! is_string($rule))
{
$line = $this->CI->lang->line('form_validation_error_message_not_set').'(Anonymous function)';
}
else
{
$line = $this->_get_error_message($rule, $row['field']);
}
// Is the parameter we are inserting into the error message the name
// of another field? If so we need to grab its "field label"
if (isset($this->_field_data[$param], $this->_field_data[$param]['label']))
{
$param = $this->_translate_fieldname($this->_field_data[$param]['label']);
}
// Build the error message
$message = $this->_build_error_msg($line, $this->_translate_fieldname($row['label']), $param);
// Save the error message
$this->_field_data[$row['field']]['error'] = $message;
if ( ! isset($this->_error_array[$row['field']]))
{
$this->_error_array[$row['field']] = $message;
}
return;
}
}
}
}
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 5 years ago.
public function is used inside a class called Client but it still throws error like this for every function in that class. Any solution to this? I am trying to test getstream for php. I am getting this error in client.php
I know this error occurs when class isn't declared while using public function but in this case the class has been declared and according to the documentation this should have worked without an error.
<?php
namespace GuzzleHttp;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Promise;
use GuzzleHttp\Psr7;
use Psr\Http\Message\UriInterface;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* #method ResponseInterface get(string|UriInterface $uri, array $options = [])
* #method ResponseInterface head(string|UriInterface $uri, array $options = [])
* #method ResponseInterface put(string|UriInterface $uri, array $options = [])
* #method ResponseInterface post(string|UriInterface $uri, array $options = [])
* #method ResponseInterface patch(string|UriInterface $uri, array $options = [])
* #method ResponseInterface delete(string|UriInterface $uri, array $options = [])
* #method Promise\PromiseInterface getAsync(string|UriInterface $uri, array $options = [])
* #method Promise\PromiseInterface headAsync(string|UriInterface $uri, array $options = [])
* #method Promise\PromiseInterface putAsync(string|UriInterface $uri, array $options = [])
* #method Promise\PromiseInterface postAsync(string|UriInterface $uri, array $options = [])
* #method Promise\PromiseInterface patchAsync(string|UriInterface $uri, array $options = [])
* #method Promise\PromiseInterface deleteAsync(string|UriInterface $uri, array $options = [])
*/
class Client implements ClientInterface
{
/** #var array Default request options */
private $config;
/**
* Clients accept an array of constructor parameters.
*
* Here's an example of creating a client using a base_uri and an array of
* default request options to apply to each request:
*
* $client = new Client([
* 'base_uri' => 'http://www.foo.com/1.0/',
* 'timeout' => 0,
* 'allow_redirects' => false,
* 'proxy' => '192.168.16.1:10'
* ]);
*
* Client configuration settings include the following options:
*
* - handler: (callable) Function that transfers HTTP requests over the
* wire. The function is called with a Psr7\Http\Message\RequestInterface
* and array of transfer options, and must return a
* GuzzleHttp\Promise\PromiseInterface that is fulfilled with a
* Psr7\Http\Message\ResponseInterface on success. "handler" is a
* constructor only option that cannot be overridden in per/request
* options. If no handler is provided, a default handler will be created
* that enables all of the request options below by attaching all of the
* default middleware to the handler.
* - base_uri: (string|UriInterface) Base URI of the client that is merged
* into relative URIs. Can be a string or instance of UriInterface.
* - **: any request option
*
* #param array $config Client configuration settings.
*
* #see \GuzzleHttp\RequestOptions for a list of available request options.
*/
//public function __construct(array $config = [])
public function __construct(array $config = ['verify' => false]) {
{
if (!isset($config['handler'])) {
$config['handler'] = HandlerStack::create();
}
// Convert the base_uri to a UriInterface
if (isset($config['base_uri'])) {
$config['base_uri'] = Psr7\uri_for($config['base_uri']);
}
$this->configureDefaults($config);
}
public function __call($method, $args)
{
if (count($args) < 1) {
throw new \InvalidArgumentException('Magic request methods require a URI and optional options array');
}
$uri = $args[0];
$opts = isset($args[1]) ? $args[1] : [];
return substr($method, -5) === 'Async'
? $this->requestAsync(substr($method, 0, -5), $uri, $opts)
: $this->request($method, $uri, $opts);
}
public function sendAsync(RequestInterface $request, array $options = [])
{
// Merge the base URI into the request URI if needed.
$options = $this->prepareDefaults($options);
return $this->transfer(
$request->withUri($this->buildUri($request->getUri(), $options), $request->hasHeader('Host')),
$options
);
}
public function send(RequestInterface $request, array $options = [])
{
$options[RequestOptions::SYNCHRONOUS] = true;
return $this->sendAsync($request, $options)->wait();
}
public function requestAsync($method, $uri = '', array $options = [])
{
$options = $this->prepareDefaults($options);
// Remove request modifying parameter because it can be done up-front.
$headers = isset($options['headers']) ? $options['headers'] : [];
$body = isset($options['body']) ? $options['body'] : null;
$version = isset($options['version']) ? $options['version'] : '1.1';
// Merge the URI into the base URI.
$uri = $this->buildUri($uri, $options);
if (is_array($body)) {
$this->invalidBody();
}
$request = new Psr7\Request($method, $uri, $headers, $body, $version);
// Remove the option so that they are not doubly-applied.
unset($options['headers'], $options['body'], $options['version']);
return $this->transfer($request, $options);
}
public function request($method, $uri = '', array $options = [])
{
$options[RequestOptions::SYNCHRONOUS] = true;
return $this->requestAsync($method, $uri, $options)->wait();
}
public function getConfig($option = null)
{
return $option === null
? $this->config
: (isset($this->config[$option]) ? $this->config[$option] : null);
}
private function buildUri($uri, array $config)
{
// for BC we accept null which would otherwise fail in uri_for
$uri = Psr7\uri_for($uri === null ? '' : $uri);
if (isset($config['base_uri'])) {
$uri = Psr7\UriResolver::resolve(Psr7\uri_for($config['base_uri']), $uri);
}
return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
}
/**
* Configures the default options for a client.
*
* #param array $config
*/
private function configureDefaults(array $config)
{
$defaults = [
'allow_redirects' => RedirectMiddleware::$defaultSettings,
'http_errors' => true,
'decode_content' => true,
'verify' => true,
'cookies' => false
];
// Use the standard Linux HTTP_PROXY and HTTPS_PROXY if set.
// We can only trust the HTTP_PROXY environment variable in a CLI
// process due to the fact that PHP has no reliable mechanism to
// get environment variables that start with "HTTP_".
if (php_sapi_name() == 'cli' && getenv('HTTP_PROXY')) {
$defaults['proxy']['http'] = getenv('HTTP_PROXY');
}
if ($proxy = getenv('HTTPS_PROXY')) {
$defaults['proxy']['https'] = $proxy;
}
if ($noProxy = getenv('NO_PROXY')) {
$cleanedNoProxy = str_replace(' ', '', $noProxy);
$defaults['proxy']['no'] = explode(',', $cleanedNoProxy);
}
$this->config = $config + $defaults;
if (!empty($config['cookies']) && $config['cookies'] === true) {
$this->config['cookies'] = new CookieJar();
}
// Add the default user-agent header.
if (!isset($this->config['headers'])) {
$this->config['headers'] = ['User-Agent' => default_user_agent()];
} else {
// Add the User-Agent header if one was not already set.
foreach (array_keys($this->config['headers']) as $name) {
if (strtolower($name) === 'user-agent') {
return;
}
}
$this->config['headers']['User-Agent'] = default_user_agent();
}
}
/**
* Merges default options into the array.
*
* #param array $options Options to modify by reference
*
* #return array
*/
private function prepareDefaults($options)
{
$defaults = $this->config;
if (!empty($defaults['headers'])) {
// Default headers are only added if they are not present.
$defaults['_conditional'] = $defaults['headers'];
unset($defaults['headers']);
}
// Special handling for headers is required as they are added as
// conditional headers and as headers passed to a request ctor.
if (array_key_exists('headers', $options)) {
// Allows default headers to be unset.
if ($options['headers'] === null) {
$defaults['_conditional'] = null;
unset($options['headers']);
} elseif (!is_array($options['headers'])) {
throw new \InvalidArgumentException('headers must be an array');
}
}
// Shallow merge defaults underneath options.
$result = $options + $defaults;
// Remove null values.
foreach ($result as $k => $v) {
if ($v === null) {
unset($result[$k]);
}
}
return $result;
}
/**
* Transfers the given request and applies request options.
*
* The URI of the request is not modified and the request options are used
* as-is without merging in default options.
*
* #param RequestInterface $request
* #param array $options
*
* #return Promise\PromiseInterface
*/
private function transfer(RequestInterface $request, array $options)
{
// save_to -> sink
if (isset($options['save_to'])) {
$options['sink'] = $options['save_to'];
unset($options['save_to']);
}
// exceptions -> http_errors
if (isset($options['exceptions'])) {
$options['http_errors'] = $options['exceptions'];
unset($options['exceptions']);
}
$request = $this->applyOptions($request, $options);
$handler = $options['handler'];
try {
return Promise\promise_for($handler($request, $options));
} catch (\Exception $e) {
return Promise\rejection_for($e);
}
}
/**
* Applies the array of request options to a request.
*
* #param RequestInterface $request
* #param array $options
*
* #return RequestInterface
*/
private function applyOptions(RequestInterface $request, array &$options)
{
$modify = [];
if (isset($options['form_params'])) {
if (isset($options['multipart'])) {
throw new \InvalidArgumentException('You cannot use '
. 'form_params and multipart at the same time. Use the '
. 'form_params option if you want to send application/'
. 'x-www-form-urlencoded requests, and the multipart '
. 'option to send multipart/form-data requests.');
}
$options['body'] = http_build_query($options['form_params'], '', '&');
unset($options['form_params']);
$options['_conditional']['Content-Type'] = 'application/x-www-form-urlencoded';
}
if (isset($options['multipart'])) {
$options['body'] = new Psr7\MultipartStream($options['multipart']);
unset($options['multipart']);
}
if (isset($options['json'])) {
$options['body'] = \GuzzleHttp\json_encode($options['json']);
unset($options['json']);
$options['_conditional']['Content-Type'] = 'application/json';
}
if (!empty($options['decode_content'])
&& $options['decode_content'] !== true
) {
$modify['set_headers']['Accept-Encoding'] = $options['decode_content'];
}
if (isset($options['headers'])) {
if (isset($modify['set_headers'])) {
$modify['set_headers'] = $options['headers'] + $modify['set_headers'];
} else {
$modify['set_headers'] = $options['headers'];
}
unset($options['headers']);
}
if (isset($options['body'])) {
if (is_array($options['body'])) {
$this->invalidBody();
}
$modify['body'] = Psr7\stream_for($options['body']);
unset($options['body']);
}
if (!empty($options['auth']) && is_array($options['auth'])) {
$value = $options['auth'];
$type = isset($value[2]) ? strtolower($value[2]) : 'basic';
switch ($type) {
case 'basic':
$modify['set_headers']['Authorization'] = 'Basic '
. base64_encode("$value[0]:$value[1]");
break;
case 'digest':
// #todo: Do not rely on curl
$options['curl'][CURLOPT_HTTPAUTH] = CURLAUTH_DIGEST;
$options['curl'][CURLOPT_USERPWD] = "$value[0]:$value[1]";
break;
}
}
if (isset($options['query'])) {
$value = $options['query'];
if (is_array($value)) {
$value = http_build_query($value, null, '&', PHP_QUERY_RFC3986);
}
if (!is_string($value)) {
throw new \InvalidArgumentException('query must be a string or array');
}
$modify['query'] = $value;
unset($options['query']);
}
// Ensure that sink is not an invalid value.
if (isset($options['sink'])) {
// TODO: Add more sink validation?
if (is_bool($options['sink'])) {
throw new \InvalidArgumentException('sink must not be a boolean');
}
}
$request = Psr7\modify_request($request, $modify);
if ($request->getBody() instanceof Psr7\MultipartStream) {
// Use a multipart/form-data POST if a Content-Type is not set.
$options['_conditional']['Content-Type'] = 'multipart/form-data; boundary='
. $request->getBody()->getBoundary();
}
// Merge in conditional headers if they are not present.
if (isset($options['_conditional'])) {
// Build up the changes so it's in a single clone of the message.
$modify = [];
foreach ($options['_conditional'] as $k => $v) {
if (!$request->hasHeader($k)) {
$modify['set_headers'][$k] = $v;
}
}
$request = Psr7\modify_request($request, $modify);
// Don't pass this internal value along to middleware/handlers.
unset($options['_conditional']);
}
return $request;
}
private function invalidBody()
{
throw new \InvalidArgumentException('Passing in the "body" request '
. 'option as an array to send a POST request has been deprecated. '
. 'Please use the "form_params" request option to send a '
. 'application/x-www-form-urlencoded request, or a the "multipart" '
. 'request option to send a multipart/form-data request.');
}
}
public function __construct(array $config = ['verify' => false]) {
{ // <-- duplicated brace here
I’m trying to calculate a signature to make Amazon Marketplace API calls, but I keep getting the following error:
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
I’ve wrapped the signature creation process into a class:
<?php
namespace App\Marketplace\Amazon;
class Signature
{
protected $signedString;
public function __construct($url, array $parameters, $secretAccessKey)
{
$stringToSign = $this->calculateStringToSign($url, $parameters);
$this->signedString = $this->sign($stringToSign, $secretAccessKey);
}
protected function calculateStringToSign($url, array $parameters)
{
$url = parse_url($url);
$string = "POST\n";
$string .= $url['host'] . "\n";
$string .= $url['path'] . "\n";
$string .= $this->getParametersAsString($parameters);
return $string;
}
protected function sign($data, $secretAccessKey)
{
return base64_encode(hash_hmac('sha256', $data, $secretAccessKey, true));
}
protected function getParametersAsString(array $parameters)
{
uksort($parameters, 'strcmp');
$queryParameters = [];
foreach ($parameters as $key => $value) {
$queryParameters[$key] = $this->urlEncode($value);
}
return http_build_query($queryParameters);
}
protected function urlEncode($value)
{
return str_replace('%7E', '~', rawurlencode($value));
}
public function __toString()
{
return $this->signedString;
}
}
But I can’t for the life of me see where I’m going wrong. I’ve followed the guide in the API, and looked at the Java example as well as the antiquated Marketplace PHP SDK*.
EDIT: And here is how I’m using the Signature class:
$version = '2011-07-01';
$url = 'https://mws.amazonservices.com/Sellers/'.$version;
$timestamp = gmdate('c', time());
$parameters = [
'AWSAccessKeyId' => $command->accessKeyId,
'Action' => 'GetAuthToken',
'SellerId' => $command->sellerId,
'SignatureMethod' => 'HmacSHA256',
'SignatureVersion' => 2,
'Timestamp' => $timestamp,
'Version' => $version,
];
$signature = new Signature($url, $parameters, $command->secretAccessKey);
$parameters['Signature'] = strval($signature);
try {
$response = $this->client->post($url, [
'headers' => [
'User-Agent' => 'my-app-name',
],
'body' => $parameters,
]);
dd($response->getBody());
} catch (\Exception $e) {
dd(strval($e->getResponse()));
}
As an aside: I know the Marketplace credentials are correct as I’ve logged in to the account and retrieved the access key, secret, and seller IDs.
* I’m not using the SDK as it doesn’t support the API call I need: SubmitFeed.
I’m not sure what I’ve changed, but my signature generation is working now. Below is the contents of the class:
<?php
namespace App\Marketplace\Amazon;
class Signature
{
/**
* The signed string.
*
* #var string
*/
protected $signedString;
/**
* Create a new signature instance.
*
* #param string $url
* #param array $data
* #param string $secretAccessKey
*/
public function __construct($url, array $parameters, $secretAccessKey)
{
$stringToSign = $this->calculateStringToSign($url, $parameters);
$this->signedString = $this->sign($stringToSign, $secretAccessKey);
}
/**
* Calculate the string to sign.
*
* #param string $url
* #param array $parameters
* #return string
*/
protected function calculateStringToSign($url, array $parameters)
{
$url = parse_url($url);
$string = "POST\n";
$string .= $url['host']."\n";
$string .= $url['path']."\n";
$string .= $this->getParametersAsString($parameters);
return $string;
}
/**
* Computes RFC 2104-compliant HMAC signature.
*
* #param string $data
* #param string $secretAccessKey
* #return string
*/
protected function sign($data, $secretAccessKey)
{
return base64_encode(hash_hmac('sha256', $data, $secretAccessKey, true));
}
/**
* Convert paremeters to URL-encoded query string.
*
* #param array $parameters
* #return string
*/
protected function getParametersAsString(array $parameters)
{
uksort($parameters, 'strcmp');
$queryParameters = [];
foreach ($parameters as $key => $value) {
$key = rawurlencode($key);
$value = rawurlencode($value);
$queryParameters[] = sprintf('%s=%s', $key, $value);
}
return implode('&', $queryParameters);
}
/**
* The string representation of this signature.
*
* #return string
*/
public function __toString()
{
return $this->signedString;
}
}
Try this function after calling your sign function:
function amazonEncode($text)
{
$encodedText = "";
$j = strlen($text);
for($i=0;$i<$j;$i++)
{
$c = substr($text,$i,1);
if (!preg_match("/[A-Za-z0-9\-_.~]/",$c))
{
$encodedText .= sprintf("%%%02X",ord($c));
}
else
{
$encodedText .= $c;
}
}
return $encodedText;
}
Reference
After you've created the canonical string as described in Format the
Query Request, you calculate the signature by creating a hash-based
message authentication code (HMAC) using either the HMAC-SHA1 or
HMAC-SHA256 protocols. The HMAC-SHA256 protocol is preferred.
The resulting signature must be base-64 encoded and then URI encoded.