Explorar el Código

Merge pull request #503 from mpociot/seed-faker

Add option to seed faker for deterministic output (closes #461)
Shalvah hace 6 años
padre
commit
f3b50ddf4a
Se han modificado 4 ficheros con 27 adiciones y 5 borrados
  1. 3 1
      TODO.md
  2. 6 0
      config/apidoc.php
  3. 1 1
      src/Commands/GenerateDocumentation.php
  4. 17 3
      src/Tools/Generator.php

+ 3 - 1
TODO.md

@@ -1,2 +1,4 @@
-- Add tests for bindings
+- Add tests for bindings and bindings prefixes
 - Add tests for config overrdes
+- Add tests for faker seed
+- Add tests on output

+ 6 - 0
config/apidoc.php

@@ -200,4 +200,10 @@ return [
     'fractal' => [
         'serializer' => null,
     ],
+
+    /*
+     * If you would like the package to generate the same example values for parameters on each run,
+     * set this to any number (eg. 1234)
+     */
+    'faker_seed' => null,
 ];

+ 1 - 1
src/Commands/GenerateDocumentation.php

@@ -55,7 +55,7 @@ class GenerateDocumentation extends Command
             $routes = $this->routeMatcher->getLaravelRoutesToBeDocumented(config('apidoc.routes'));
         }
 
-        $generator = new Generator();
+        $generator = new Generator(config('apidoc.faker_seed'));
         $parsedRoutes = $this->processRoutes($generator, $routes);
         $parsedRoutes = collect($parsedRoutes)->groupBy('group')
             ->sortBy(static function ($group) {

+ 17 - 3
src/Tools/Generator.php

@@ -14,6 +14,17 @@ class Generator
 {
     use ParamHelpers;
 
+    /**
+     * @var string The seed to be used with Faker.
+     * Useful when you want to always have the same fake output.
+     */
+    private $fakerSeed = null;
+
+    public function __construct(string $fakerSeed = null)
+    {
+        $this->fakerSeed = $fakerSeed;
+    }
+
     /**
      * @param Route $route
      *
@@ -265,9 +276,12 @@ class Generator
     private function generateDummyValue(string $type)
     {
         $faker = Factory::create();
+        if ($this->fakerSeed) {
+            $faker->seed($this->fakerSeed);
+        }
         $fakes = [
-            'integer' => function () {
-                return rand(1, 20);
+            'integer' => function () use ($faker) {
+                return $faker->numberBetween(1, 20);
             },
             'number' => function () use ($faker) {
                 return $faker->randomFloat();
@@ -279,7 +293,7 @@ class Generator
                 return $faker->boolean();
             },
             'string' => function () use ($faker) {
-                return str_random();
+                return $faker->word;
             },
             'array' => function () {
                 return [];