ValidatedDescriptionHandler.php 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php namespace GuzzleHttp\Command\Guzzle\Handler;
  2. use GuzzleHttp\Command\CommandInterface;
  3. use GuzzleHttp\Command\Exception\CommandException;
  4. use GuzzleHttp\Command\Guzzle\DescriptionInterface;
  5. use GuzzleHttp\Command\Guzzle\SchemaValidator;
  6. /**
  7. * Handler used to validate command input against a service description.
  8. *
  9. * @author Stefano Kowalke <info@arroba-it.de>
  10. */
  11. class ValidatedDescriptionHandler
  12. {
  13. /** @var SchemaValidator $validator */
  14. private $validator;
  15. /** @var DescriptionInterface $description */
  16. private $description;
  17. /**
  18. * ValidatedDescriptionHandler constructor.
  19. *
  20. * @param DescriptionInterface $description
  21. * @param SchemaValidator|null $schemaValidator
  22. */
  23. public function __construct(DescriptionInterface $description, SchemaValidator $schemaValidator = null)
  24. {
  25. $this->description = $description;
  26. $this->validator = $schemaValidator ?: new SchemaValidator();
  27. }
  28. /**
  29. * @param callable $handler
  30. * @return \Closure
  31. */
  32. public function __invoke(callable $handler)
  33. {
  34. return function (CommandInterface $command) use ($handler) {
  35. $errors = [];
  36. $operation = $this->description->getOperation($command->getName());
  37. foreach ($operation->getParams() as $name => $schema) {
  38. $value = $command[$name];
  39. if ($value) {
  40. $value = $schema->filter($value);
  41. }
  42. if (! $this->validator->validate($schema, $value)) {
  43. $errors = array_merge($errors, $this->validator->getErrors());
  44. } elseif ($value !== $command[$name]) {
  45. // Update the config value if it changed and no validation errors were encountered.
  46. // This happen when the user extending an operation
  47. // See https://github.com/guzzle/guzzle-services/issues/145
  48. $command[$name] = $value;
  49. }
  50. }
  51. if ($params = $operation->getAdditionalParameters()) {
  52. foreach ($command->toArray() as $name => $value) {
  53. // It's only additional if it isn't defined in the schema
  54. if (! $operation->hasParam($name)) {
  55. // Always set the name so that error messages are useful
  56. $params->setName($name);
  57. if (! $this->validator->validate($params, $value)) {
  58. $errors = array_merge($errors, $this->validator->getErrors());
  59. } elseif ($value !== $command[$name]) {
  60. $command[$name] = $value;
  61. }
  62. }
  63. }
  64. }
  65. if ($errors) {
  66. throw new CommandException('Validation errors: ' . implode("\n", $errors), $command);
  67. }
  68. return $handler($command);
  69. };
  70. }
  71. }