|
@@ -101,7 +101,8 @@ class Generator
|
|
|
}
|
|
|
|
|
|
$type = $this->normalizeParameterType($type);
|
|
|
- $value = $this->generateDummyValue($type);
|
|
|
+ list($description, $example) = $this->parseDescription($description, $type);
|
|
|
+ $value = is_null($example) ? $this->generateDummyValue($type) : $example;
|
|
|
|
|
|
return [$name => compact('type', 'description', 'required', 'value')];
|
|
|
})->toArray();
|
|
@@ -137,10 +138,11 @@ class Generator
|
|
|
$required = trim($required) == 'required' ? true : false;
|
|
|
}
|
|
|
|
|
|
- if (str_contains($description, ['number', 'count', 'page'])) {
|
|
|
- $value = $this->generateDummyValue('integer');
|
|
|
- } else {
|
|
|
- $value = $this->generateDummyValue('string');
|
|
|
+ list($description, $value) = $this->parseDescription($description, 'string');
|
|
|
+ if (is_null($value)) {
|
|
|
+ $value = str_contains($description, ['number', 'count', 'page'])
|
|
|
+ ? $this->generateDummyValue('integer')
|
|
|
+ : $this->generateDummyValue('string');
|
|
|
}
|
|
|
|
|
|
return [$name => compact('description', 'required', 'value')];
|
|
@@ -255,4 +257,56 @@ class Generator
|
|
|
|
|
|
return $fake();
|
|
|
}
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Allows users to specify an example for the parameter by writing 'Example: the-example',
|
|
|
+ * to be used in example requests and response calls.
|
|
|
+ *
|
|
|
+ * @param string $description
|
|
|
+ * @param string $type The type of the parameter. Used to cast the example provided, if any.
|
|
|
+ *
|
|
|
+ * @return array The description and included example.
|
|
|
+ */
|
|
|
+ private function parseDescription(string $description, string $type)
|
|
|
+ {
|
|
|
+ $example = null;
|
|
|
+ if (preg_match('/(.*)\s+Example:\s*(.*)\s*/', $description, $content)) {
|
|
|
+ $description = $content[1];
|
|
|
+
|
|
|
+ // examples are parsed as strings by default, we need to cast them properly
|
|
|
+ $example = $this->castToType($content[2], $type);
|
|
|
+ }
|
|
|
+
|
|
|
+ return [$description, $example];
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * Cast a value from a string to a specified type.
|
|
|
+ *
|
|
|
+ * @param string $value
|
|
|
+ * @param string $type
|
|
|
+ *
|
|
|
+ * @return mixed
|
|
|
+ */
|
|
|
+ private function castToType(string $value, string $type)
|
|
|
+ {
|
|
|
+ $casts = [
|
|
|
+ 'integer' => 'intval',
|
|
|
+ 'number' => 'floatval',
|
|
|
+ 'float' => 'floatval',
|
|
|
+ 'boolean' => 'boolval',
|
|
|
+ ];
|
|
|
+
|
|
|
+ // First, we handle booleans. We can't use a regular cast,
|
|
|
+ //because PHP considers string 'false' as true.
|
|
|
+ if ($value == 'false' && $type == 'boolean') {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ if (isset($casts[$type])) {
|
|
|
+ return $casts[$type]($value);
|
|
|
+ }
|
|
|
+
|
|
|
+ return $value;
|
|
|
+ }
|
|
|
}
|