PageRenderTime 43ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-content/plugins/iwp-client/lib/amazon/guzzle/guzzle/src/Guzzle/Service/Description/SchemaValidator.php

https://gitlab.com/treighton/wpgit
PHP | 291 lines | 194 code | 35 blank | 62 comment | 86 complexity | f0670f22d9dd464e1096e63a5cd9bb48 MD5 | raw file
  1. <?php
  2. namespace Guzzle\Service\Description;
  3. use Guzzle\Common\ToArrayInterface;
  4. /**
  5. * Default parameter validator
  6. */
  7. class SchemaValidator implements ValidatorInterface
  8. {
  9. /** @var self Cache instance of the object */
  10. protected static $instance;
  11. /** @var bool Whether or not integers are converted to strings when an integer is received for a string input */
  12. protected $castIntegerToStringType;
  13. /** @var array Errors encountered while validating */
  14. protected $errors;
  15. /**
  16. * @return self
  17. * @codeCoverageIgnore
  18. */
  19. public static function getInstance()
  20. {
  21. if (!self::$instance) {
  22. self::$instance = new self();
  23. }
  24. return self::$instance;
  25. }
  26. /**
  27. * @param bool $castIntegerToStringType Set to true to convert integers into strings when a required type is a
  28. * string and the input value is an integer. Defaults to true.
  29. */
  30. public function __construct($castIntegerToStringType = true)
  31. {
  32. $this->castIntegerToStringType = $castIntegerToStringType;
  33. }
  34. public function validate(Parameter $param, &$value)
  35. {
  36. $this->errors = array();
  37. $this->recursiveProcess($param, $value);
  38. if (empty($this->errors)) {
  39. return true;
  40. } else {
  41. sort($this->errors);
  42. return false;
  43. }
  44. }
  45. /**
  46. * Get the errors encountered while validating
  47. *
  48. * @return array
  49. */
  50. public function getErrors()
  51. {
  52. return $this->errors ?: array();
  53. }
  54. /**
  55. * Recursively validate a parameter
  56. *
  57. * @param Parameter $param API parameter being validated
  58. * @param mixed $value Value to validate and validate. The value may change during this validate.
  59. * @param string $path Current validation path (used for error reporting)
  60. * @param int $depth Current depth in the validation validate
  61. *
  62. * @return bool Returns true if valid, or false if invalid
  63. */
  64. protected function recursiveProcess(Parameter $param, &$value, $path = '', $depth = 0)
  65. {
  66. // Update the value by adding default or static values
  67. $value = $param->getValue($value);
  68. $required = $param->getRequired();
  69. // if the value is null and the parameter is not required or is static, then skip any further recursion
  70. if ((null === $value && !$required) || $param->getStatic()) {
  71. return true;
  72. }
  73. $type = $param->getType();
  74. // Attempt to limit the number of times is_array is called by tracking if the value is an array
  75. $valueIsArray = is_array($value);
  76. // If a name is set then update the path so that validation messages are more helpful
  77. if ($name = $param->getName()) {
  78. $path .= "[{$name}]";
  79. }
  80. if ($type == 'object') {
  81. // Objects are either associative arrays, ToArrayInterface, or some other object
  82. if ($param->getInstanceOf()) {
  83. $instance = $param->getInstanceOf();
  84. if (!($value instanceof $instance)) {
  85. $this->errors[] = "{$path} must be an instance of {$instance}";
  86. return false;
  87. }
  88. }
  89. // Determine whether or not this "value" has properties and should be traversed
  90. $traverse = $temporaryValue = false;
  91. // Convert the value to an array
  92. if (!$valueIsArray && $value instanceof ToArrayInterface) {
  93. $value = $value->toArray();
  94. }
  95. if ($valueIsArray) {
  96. // Ensure that the array is associative and not numerically indexed
  97. if (isset($value[0])) {
  98. $this->errors[] = "{$path} must be an array of properties. Got a numerically indexed array.";
  99. return false;
  100. }
  101. $traverse = true;
  102. } elseif ($value === null) {
  103. // Attempt to let the contents be built up by default values if possible
  104. $value = array();
  105. $temporaryValue = $valueIsArray = $traverse = true;
  106. }
  107. if ($traverse) {
  108. if ($properties = $param->getProperties()) {
  109. // if properties were found, the validate each property of the value
  110. foreach ($properties as $property) {
  111. $name = $property->getName();
  112. if (isset($value[$name])) {
  113. $this->recursiveProcess($property, $value[$name], $path, $depth + 1);
  114. } else {
  115. $current = null;
  116. $this->recursiveProcess($property, $current, $path, $depth + 1);
  117. // Only set the value if it was populated with something
  118. if (null !== $current) {
  119. $value[$name] = $current;
  120. }
  121. }
  122. }
  123. }
  124. $additional = $param->getAdditionalProperties();
  125. if ($additional !== true) {
  126. // If additional properties were found, then validate each against the additionalProperties attr.
  127. $keys = array_keys($value);
  128. // Determine the keys that were specified that were not listed in the properties of the schema
  129. $diff = array_diff($keys, array_keys($properties));
  130. if (!empty($diff)) {
  131. // Determine which keys are not in the properties
  132. if ($additional instanceOf Parameter) {
  133. foreach ($diff as $key) {
  134. $this->recursiveProcess($additional, $value[$key], "{$path}[{$key}]", $depth);
  135. }
  136. } else {
  137. // if additionalProperties is set to false and there are additionalProperties in the values, then fail
  138. foreach ($diff as $prop) {
  139. $this->errors[] = sprintf('%s[%s] is not an allowed property', $path, $prop);
  140. }
  141. }
  142. }
  143. }
  144. // A temporary value will be used to traverse elements that have no corresponding input value.
  145. // This allows nested required parameters with default values to bubble up into the input.
  146. // Here we check if we used a temp value and nothing bubbled up, then we need to remote the value.
  147. if ($temporaryValue && empty($value)) {
  148. $value = null;
  149. $valueIsArray = false;
  150. }
  151. }
  152. } elseif ($type == 'array' && $valueIsArray && $param->getItems()) {
  153. foreach ($value as $i => &$item) {
  154. // Validate each item in an array against the items attribute of the schema
  155. $this->recursiveProcess($param->getItems(), $item, $path . "[{$i}]", $depth + 1);
  156. }
  157. }
  158. // If the value is required and the type is not null, then there is an error if the value is not set
  159. if ($required && $value === null && $type != 'null') {
  160. $message = "{$path} is " . ($param->getType() ? ('a required ' . implode(' or ', (array) $param->getType())) : 'required');
  161. if ($param->getDescription()) {
  162. $message .= ': ' . $param->getDescription();
  163. }
  164. $this->errors[] = $message;
  165. return false;
  166. }
  167. // Validate that the type is correct. If the type is string but an integer was passed, the class can be
  168. // instructed to cast the integer to a string to pass validation. This is the default behavior.
  169. if ($type && (!$type = $this->determineType($type, $value))) {
  170. if ($this->castIntegerToStringType && $param->getType() == 'string' && is_integer($value)) {
  171. $value = (string) $value;
  172. } else {
  173. $this->errors[] = "{$path} must be of type " . implode(' or ', (array) $param->getType());
  174. }
  175. }
  176. // Perform type specific validation for strings, arrays, and integers
  177. if ($type == 'string') {
  178. // Strings can have enums which are a list of predefined values
  179. if (($enum = $param->getEnum()) && !in_array($value, $enum)) {
  180. $this->errors[] = "{$path} must be one of " . implode(' or ', array_map(function ($s) {
  181. return '"' . addslashes($s) . '"';
  182. }, $enum));
  183. }
  184. // Strings can have a regex pattern that the value must match
  185. if (($pattern = $param->getPattern()) && !preg_match($pattern, $value)) {
  186. $this->errors[] = "{$path} must match the following regular expression: {$pattern}";
  187. }
  188. $strLen = null;
  189. if ($min = $param->getMinLength()) {
  190. $strLen = strlen($value);
  191. if ($strLen < $min) {
  192. $this->errors[] = "{$path} length must be greater than or equal to {$min}";
  193. }
  194. }
  195. if ($max = $param->getMaxLength()) {
  196. if (($strLen ?: strlen($value)) > $max) {
  197. $this->errors[] = "{$path} length must be less than or equal to {$max}";
  198. }
  199. }
  200. } elseif ($type == 'array') {
  201. $size = null;
  202. if ($min = $param->getMinItems()) {
  203. $size = count($value);
  204. if ($size < $min) {
  205. $this->errors[] = "{$path} must contain {$min} or more elements";
  206. }
  207. }
  208. if ($max = $param->getMaxItems()) {
  209. if (($size ?: count($value)) > $max) {
  210. $this->errors[] = "{$path} must contain {$max} or fewer elements";
  211. }
  212. }
  213. } elseif ($type == 'integer' || $type == 'number' || $type == 'numeric') {
  214. if (($min = $param->getMinimum()) && $value < $min) {
  215. $this->errors[] = "{$path} must be greater than or equal to {$min}";
  216. }
  217. if (($max = $param->getMaximum()) && $value > $max) {
  218. $this->errors[] = "{$path} must be less than or equal to {$max}";
  219. }
  220. }
  221. return empty($this->errors);
  222. }
  223. /**
  224. * From the allowable types, determine the type that the variable matches
  225. *
  226. * @param string $type Parameter type
  227. * @param mixed $value Value to determine the type
  228. *
  229. * @return string|bool Returns the matching type on
  230. */
  231. protected function determineType($type, $value)
  232. {
  233. foreach ((array) $type as $t) {
  234. if ($t == 'string' && (is_string($value) || (is_object($value) && method_exists($value, '__toString')))) {
  235. return 'string';
  236. } elseif ($t == 'object' && (is_array($value) || is_object($value))) {
  237. return 'object';
  238. } elseif ($t == 'array' && is_array($value)) {
  239. return 'array';
  240. } elseif ($t == 'integer' && is_integer($value)) {
  241. return 'integer';
  242. } elseif ($t == 'boolean' && is_bool($value)) {
  243. return 'boolean';
  244. } elseif ($t == 'number' && is_numeric($value)) {
  245. return 'number';
  246. } elseif ($t == 'numeric' && is_numeric($value)) {
  247. return 'numeric';
  248. } elseif ($t == 'null' && !$value) {
  249. return 'null';
  250. } elseif ($t == 'any') {
  251. return 'any';
  252. }
  253. }
  254. return false;
  255. }
  256. }