Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: Support Filters Being Bound to Different Stages of Processing #171

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 24 additions & 10 deletions src/Handler/ValidatedDescriptionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use GuzzleHttp\Command\CommandInterface;
use GuzzleHttp\Command\Exception\CommandException;
use GuzzleHttp\Command\Guzzle\DescriptionInterface;
use GuzzleHttp\Command\Guzzle\Parameter;
use GuzzleHttp\Command\Guzzle\SchemaValidator;

/**
Expand Down Expand Up @@ -43,17 +44,30 @@ public function __invoke(callable $handler)
foreach ($operation->getParams() as $name => $schema) {
$value = $command[$name];

if ($value) {
$value = $schema->filter($value);
}
$preValidationValue = $schema->filter(
$value,
Parameter::FILTER_STAGE_BEFORE_VALIDATION
);

if (!$this->validator->validate($schema, $preValidationValue)) {
$errors =
array_merge($errors, $this->validator->getErrors());
} else {
$postValidationValue = $schema->filter(
$preValidationValue,
Parameter::FILTER_STAGE_AFTER_VALIDATION
);

if (! $this->validator->validate($schema, $value)) {
$errors = array_merge($errors, $this->validator->getErrors());
} elseif ($value !== $command[$name]) {
// Update the config value if it changed and no validation errors were encountered.
// This happen when the user extending an operation
// See https://github.com/guzzle/guzzle-services/issues/145
$command[$name] = $value;
if ($postValidationValue !== $command[$name]) {
// Update the parameter value if it has changed and no
// validation errors were encountered. This ensures the
// parameter has a value even when the user is extending
// an operation.
//
// See:
// https://github.com/guzzle/guzzle-services/issues/145
$command[$name] = $postValidationValue;
}
}
}

Expand Down
6 changes: 5 additions & 1 deletion src/Operation.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public function __construct(array $config = [], DescriptionInterface $descriptio
{
static $defaults = [
'name' => '',
'httpMethod' => '',
'httpMethod' => 'GET',
'uri' => '',
'responseModel' => null,
'notes' => '',
Expand All @@ -72,6 +72,10 @@ public function __construct(array $config = [], DescriptionInterface $descriptio
$config = $this->resolveExtends($config['extends'], $config);
}

if (array_key_exists('httpMethod', $config) && empty($config['httpMethod'])) {
throw new \InvalidArgumentException('httpMethod must be a non-empty string');
}

$this->config = $config + $defaults;

// Account for the old style of using responseClass
Expand Down
254 changes: 216 additions & 38 deletions src/Parameter.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,43 @@
*/
class Parameter implements ToArrayInterface
{
/**
* The name of the filter stage that happens before a parameter is
* validated, for filtering raw data (e.g. clean-up before validation).
*/
const FILTER_STAGE_BEFORE_VALIDATION = 'before_validation';

/**
* The name of the filter stage that happens immediately after a parameter
* has been validated but before it is evaluated by location handlers to be
* written out on the wire.
*/
const FILTER_STAGE_AFTER_VALIDATION = 'after_validation';

/**
* The name of the filter stage that happens right before a validated value
* is being written out "on the wire" (e.g. for adjusting the structure or
* format of the data before sending it to the server).
*/
const FILTER_STAGE_REQUEST_WIRE = 'request_wire';

/**
* The name of the filter stage that happens right after a value has been
* read out of a response "on the wire" (e.g. for adjusting the structure or
* format of the data after receiving it back from the server).
*/
const FILTER_STAGE_RESPONSE_WIRE = 'response_wire';

/**
* A list of all allowed filter stages.
*/
const FILTER_STAGES = [
self::FILTER_STAGE_BEFORE_VALIDATION,
self::FILTER_STAGE_AFTER_VALIDATION,
self::FILTER_STAGE_REQUEST_WIRE,
self::FILTER_STAGE_RESPONSE_WIRE
];

private $originalData;

/** @var string $name */
Expand Down Expand Up @@ -117,14 +154,23 @@ class Parameter implements ToArrayInterface
* full class path to a static method or an array of complex filter
* information. You can specify static methods of classes using the full
* namespace class name followed by '::' (e.g. Foo\Bar::baz). Some
* filters require arguments in order to properly filter a value. For
* complex filters, use a hash containing a 'method' key pointing to a
* static method, and an 'args' key containing an array of positional
* arguments to pass to the method. Arguments can contain keywords that
* are replaced when filtering a value: '@value' is replaced with the
* value being validated, '@api' is replaced with the Parameter object.
* filters require arguments in order to properly filter a value.
*
* - properties: When the type is an object, you can specify nested parameters
* For complex filters, use a hash containing a 'method' key pointing to a
* static method, an 'args' key containing an array of positional
* arguments to pass to the method, and an optional 'stage' key. Arguments
* can contain keywords that are replaced when filtering a value: '@value'
* is replaced with the value being validated, '@api' is replaced with the
* Parameter object, and '@stage' is replaced with the current filter
* stage (if any was provided).
*
* The optional 'stage' key can be provided to control when the filter is
* invoked. The key can indicate that a filter should only be invoked
* 'before_validation', 'after_validation', when being written out to the
* 'request_wire' or being read from the 'response_wire'.
*
* - properties: When the type is an object, you can specify nested
* parameters
*
* - additionalProperties: (array) This attribute defines a schema for all
* properties that are not explicitly defined in an object type
Expand Down Expand Up @@ -210,7 +256,9 @@ public function __construct(array $data = [], array $options = [])
$this->required = (bool) $this->required;
$this->data = (array) $this->data;

if ($this->filters) {
if (empty($this->filters)) {
$this->filters = [];
} else {
$this->setFilters((array) $this->filters);
}

Expand Down Expand Up @@ -250,15 +298,31 @@ public function getValue($value)
* parameter.
*
* @param mixed $value Value to filter
* @param string $stage An optional specifier of what filter stage to
* invoke. If null, then all filters are invoked no matter what stage
* they apply to. Otherwise, only filters for the specified stage are
* invoked.
*
* @return mixed Returns the filtered value
* @throws \RuntimeException when trying to format when no service
* description is available.
*/
public function filter($value)
{
// Formats are applied exclusively and supersed filters
if ($this->format) {
* @throws \InvalidArgumentException if an invalid validation stage is
* provided.
*/
public function filter($value, $stage = null)
{
if (($stage !== null) && !in_array($stage, self::FILTER_STAGES)) {
throw new \InvalidArgumentException(
sprintf(
'$stage must be one of [%s], but was given "%s"',
implode(', ', self::FILTER_STAGES),
$stage
)
);
}

// Formats are applied exclusively and supercede filters
if (!empty($this->format)) {
if (!$this->serviceDescription) {
throw new \RuntimeException('No service description was set so '
. 'the value cannot be formatted.');
Expand All @@ -272,25 +336,8 @@ public function filter($value)
}

// Apply filters to the value
if ($this->filters) {
foreach ($this->filters as $filter) {
if (is_array($filter)) {
// Convert complex filters that hold value place holders
foreach ($filter['args'] as &$data) {
if ($data == '@value') {
$data = $value;
} elseif ($data == '@api') {
$data = $this;
}
}
$value = call_user_func_array(
$filter['method'],
$filter['args']
);
} else {
$value = call_user_func($filter, $value);
}
}
if (!empty($this->filters)) {
$value = $this->invokeCustomFilters($value, $stage);
}

return $value;
Expand Down Expand Up @@ -487,7 +534,7 @@ public function isStatic()
*/
public function getFilters()
{
return $this->filters ?: [];
return $this->filters;
}

/**
Expand Down Expand Up @@ -605,6 +652,7 @@ public function getFormat()
private function setFilters(array $filters)
{
$this->filters = [];

foreach ($filters as $filter) {
$this->addFilter($filter);
}
Expand All @@ -628,14 +676,21 @@ private function addFilter($filter)
'A [method] value must be specified for each complex filter'
);
}
}

if (!$this->filters) {
$this->filters = [$filter];
} else {
$this->filters[] = $filter;
if (isset($filter['stage'])
&& !in_array($filter['stage'], self::FILTER_STAGES)) {
throw new \InvalidArgumentException(
sprintf(
'[stage] value must be one of [%s], but was given "%s"',
implode(', ', self::FILTER_STAGES),
$filter['stage']
)
);
}
}

$this->filters[] = $filter;

return $this;
}

Expand All @@ -652,4 +707,127 @@ public function has($var)
}
return isset($this->{$var}) && !empty($this->{$var});
}

/**
* Filters the given data using filter methods specified in the config.
*
* If $stage is provided, only filters that apply to the provided filter
* stage will be invoked. To preserve legacy behavior, filters that do not
* specify a stage are implicitly invoked only in the pre-validation stage.
*
* @param mixed $value The value to filter.
* @param string $stage An optional specifier of what filter stage to
* invoke. If null, then all filters are invoked no matter what stage
* they apply to. Otherwise, only filters for the specified stage are
* invoked.
*
* @return mixed The filtered value.
*/
private function invokeCustomFilters($value, $stage) {
$filteredValue = $value;

foreach ($this->filters as $filter) {
if (is_array($filter)) {
$filteredValue =
$this->invokeComplexFilter($filter, $value, $stage);
} else {
$filteredValue =
$this->invokeSimpleFilter($filter, $value, $stage);
}
}

return $filteredValue;
}

/**
* Invokes a filter that uses value substitution and/or should only be
* invoked for a particular filter stage.
*
* If $stage is provided, and the filter specifies a stage, it is not
* invoked unless $stage matches the stage the filter indicates it applies
* to. If the filter is not invoked, $value is returned exactly as it was
* provided to this method.
*
* To preserve legacy behavior, if the filter does not specify a stage, it
* is implicitly invoked only in the pre-validation stage.
*
* @param array $filter Information about the filter to invoke.
* @param mixed $value The value to filter.
* @param string $stage An optional specifier of what filter stage to
* invoke. If null, then the filter is invoked no matter what stage it
* indicates it applies to. Otherwise, the filter is only invoked if it
* matches the specified stage.
*
* @return mixed The filtered value.
*/
private function invokeComplexFilter(array $filter, $value, $stage) {
if (isset($filter['stage'])) {
$filterStage = $filter['stage'];
} else {
$filterStage = self::FILTER_STAGE_AFTER_VALIDATION;
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This default is fine for filters on request payloads/parameters, but wrong for filters on response values. For responses, the default filter stage should be FILTER_STAGE_RESPONSE_WIRE if not specified.

When a simple filter is used, the logic is correct because the filter is invoked for all stages of processing except FILTER_STAGE_AFTER_VALIDATION. But if that simple filter is rewritten as a complex filter (by specifying the filter as an array with a method key), the filter will not work properly without stage key.

}

if (($stage === null) || ($filterStage == $stage)) {
// Convert complex filters that hold value place holders
$filterArgs =
$this->expandFilterArgs($filter['args'], $value, $stage);

$filteredValue =
call_user_func_array($filter['method'], $filterArgs);
} else {
$filteredValue = $value;
}

return $filteredValue;
}

/**
* Replaces any placeholders in filter arguments with values from the
* current context.
*
* @param array $filterArgs The array of arguments to pass to the filter
* function. Some of the elements of this array are expected to be
* placeholders that will be replaced by this function.
*
* @return array The array of arguments, with all placeholders replaced.
*/
private function expandFilterArgs(array $filterArgs, $value, $stage) {
$replacements = [
'@value' => $value,
'@api' => $this,
'@stage' => $stage,
];

foreach ($filterArgs as &$argValue) {
if (isset($replacements[$argValue])) {
$argValue = $replacements[$argValue];
}
}

return $filterArgs;
}

/**
* Invokes a filter only provides a function or method name to invoke,
* without additional parameters.
*
* If $stage is provided, the filter is not invoked unless we are in the
* pre-validation stage, to preserve legacy behavior.
*
* @param array $filter Information about the filter to invoke.
* @param mixed $value The value to filter.
* @param string $stage An optional specifier of what filter stage to
* invoke. If null, then the filter is invoked no matter what.
* Otherwise, the filter is only invoked if the value is
* FILTER_STAGE_AFTER_VALIDATION.
*
* @return mixed The filtered value.
*/
private function invokeSimpleFilter($filter, $value, $stage) {
if ($stage === self::FILTER_STAGE_AFTER_VALIDATION) {
return $value;
} else {
return call_user_func($filter, $value);
}
}
}
Loading