Bläddra i källkod

RuleDescriptionParser: Refactored main Class and Test

Marcel Pociot 9 år sedan
förälder
incheckning
a2d1cc7132

+ 2 - 3
README.md

@@ -50,14 +50,13 @@ Option | Description
 
 ## Publish rule descriptions for customisation or translation.
 
- By default, this package returns the descriptions in the main language of the application. 
- You can publish the packages language files, to customise and translate the documentation output.
+ By default, this package returns the descriptions in english. You can publish the packages language files, to customise and translate the documentation output.
 
  ```sh
  $ php artisan vendor:publish
  ```
 
- After the files are published you can customise or translate the descriptions in the language you want by editing the files in `public/vendor/apidoc/resources/lang`.
+ After the files are published you can customise or translate the descriptions in the language you want by renaming the `en` folder and editing the files in `public/vendor/apidoc/resources/lang`.
 
 
 ### How does it work?

+ 2 - 1
composer.json

@@ -24,7 +24,8 @@
     "require-dev": {
         "orchestra/testbench": "~3.0",
         "phpunit/phpunit": "~4.0 || ~5.0",
-        "dingo/api": "1.0.*@dev"
+        "dingo/api": "1.0.*@dev",
+        "mockery/mockery": "^0.9.5"
     },
     "autoload": {
         "psr-0": {

+ 31 - 13
src/Mpociot/ApiDoc/Parsers/RuleDescriptionParser.php

@@ -8,12 +8,14 @@ class RuleDescriptionParser
 
     private $parameters = [];
 
+    const DEFAULT_LOCALE = 'en';
+
     /**
      * @param null $rule
      */
     public function __construct($rule = null)
     {
-        $this->rule = $rule;
+        $this->rule = "apidoc::rules.{$rule}";
     }
 
     /**
@@ -21,11 +23,7 @@ class RuleDescriptionParser
      */
     public function getDescription()
     {
-        $key = "apidoc::rules.{$this->rule}";
-
-        $description = $this->parameters ? $this->translateWithAttributes($key) : trans($key);
-
-        return $description != $key ? $description : [];
+        return $this->ruleDescriptionExist() ? $this->makeDescription() : [];
     }
 
     /**
@@ -35,25 +33,45 @@ class RuleDescriptionParser
      */
     public function with($parameters)
     {
-        is_array($parameters) ? $this->parameters += $parameters : $this->parameters[] = $parameters;
+        is_array($parameters) ?
+            $this->parameters += $parameters :
+            $this->parameters[] = $parameters;
 
         return $this;
     }
 
     /**
-     * @param $key
-     *
+     * @return bool
+     */
+    protected function ruleDescriptionExist()
+    {
+        return trans()->hasForLocale($this->rule) || trans()->hasForLocale($this->rule, self::DEFAULT_LOCALE);
+    }
+
+    /**
      * @return string
      */
-    protected function translateWithAttributes($key)
+    protected function makeDescription()
     {
-        $translate = trans($key);
+        $description = trans()->hasForLocale($this->rule) ?
+                            trans()->get($this->rule) :
+                            trans()->get($this->rule, [], self::DEFAULT_LOCALE);
+
+        return $this->replaceAttributes($description);
+    }
 
+    /**
+     * @param string $description$
+     *
+     * @return string
+     */
+    protected function replaceAttributes($description)
+    {
         foreach ($this->parameters as $parameter) {
-            $translate = preg_replace('/:attribute/', $parameter, $translate, 1);
+            $description = preg_replace('/:attribute/', $parameter, $description, 1);
         }
 
-        return $translate;
+        return $description;
     }
 
     /**

+ 4 - 4
tests/Fixtures/TestController.php

@@ -36,10 +36,10 @@ class TestController extends Controller
         $fixture->delicious = 1;
 
         return [
-            'id'        => (int) $fixture->id,
-            'name'      => ucfirst($fixture->name),
-            'color'     => ucfirst($fixture->color),
-            'weight'    => $fixture->weight . ' grams',
+            'id' => (int) $fixture->id,
+            'name' => ucfirst($fixture->name),
+            'color' => ucfirst($fixture->color),
+            'weight' => $fixture->weight.' grams',
             'delicious' => (bool) $fixture->delicious,
         ];
     }

+ 53 - 26
tests/RuleDescriptionParserTest.php

@@ -2,17 +2,37 @@
 
 namespace Mpociot\ApiDoc\Tests;
 
+use Illuminate\Translation\LoaderInterface;
+use Illuminate\Translation\Translator;
 use Mpociot\ApiDoc\ApiDocGeneratorServiceProvider;
 use Mpociot\ApiDoc\Parsers\RuleDescriptionParser;
 use Orchestra\Testbench\TestCase;
+use Mockery as m;
 
 class RuleDescriptionParserTest extends TestCase
 {
+    protected $translatorMock;
+
+    public function setUp()
+    {
+        parent::setUp();
+        $fileLoaderMock = m::mock(LoaderInterface::class);
+        $this->translatorMock = m::mock(Translator::class, [$fileLoaderMock, 'es']);
+        $this->app->instance('translator', $this->translatorMock);
+    }
+
+    public function tearDown()
+    {
+        m::close();
+    }
+
     public function testReturnsAnEmptyDescriptionIfARuleIsNotParsed()
     {
-        $rule = new RuleDescriptionParser();
+        $this->translatorMock->shouldReceive('hasForLocale')->twice()->andReturn(false);
+
+        $description = new RuleDescriptionParser();
 
-        $this->assertEmpty($rule->getDescription());
+        $this->assertEmpty($description->getDescription());
     }
 
     public function testProvidesANamedContructor()
@@ -20,51 +40,57 @@ class RuleDescriptionParserTest extends TestCase
         $this->assertInstanceOf(RuleDescriptionParser::class, RuleDescriptionParser::parse());
     }
 
-    public function testReturnsADescriptionInTheMainLanguageOfTheApplication()
+    public function testReturnsADescriptionInMainLanguageIfAvailable()
     {
-        $expected = 'Only alphabetic characters allowed';
-        $rule = new RuleDescriptionParser('alpha');
+        $this->translatorMock->shouldReceive('hasForLocale')->twice()->with('apidoc::rules.alpha')->andReturn(true);
+        $this->translatorMock->shouldReceive('get')->once()->with('apidoc::rules.alpha')->andReturn('Solo caracteres alfabeticos permitidos');
 
-        $this->assertEquals($expected, $rule->getDescription());
+        $description = RuleDescriptionParser::parse('alpha')->getDescription();
+
+        $this->assertEquals('Solo caracteres alfabeticos permitidos', $description);
     }
 
-    public function testReturnsAnEmptyDescriptionIfNotAvailable()
+    public function testReturnsDescriptionInDefaultLanguageIfNotAvailableInMainLanguage()
     {
-        $rule = new RuleDescriptionParser('dummy_rule');
+        $this->translatorMock->shouldReceive('hasForLocale')->twice()->with('apidoc::rules.alpha')->andReturn(false);
+        $this->translatorMock->shouldReceive('hasForLocale')->once()->with('apidoc::rules.alpha', 'en')->andReturn(true);
+        $this->translatorMock->shouldReceive('get')->once()->with('apidoc::rules.alpha', [], 'en')->andReturn('Only alphabetic characters allowed');
 
-        $description = $rule->getDescription();
+        $description = RuleDescriptionParser::parse('alpha')->getDescription();
 
-        $this->assertEmpty($description);
+        $this->assertEquals('Only alphabetic characters allowed', $description);
     }
 
-    public function testAllowsToPassParametersToTheDescription()
+    public function testReturnsAnEmptyDescriptionIfNotAvailable()
     {
-        $expected = 'Must have an exact length of `2`';
-        $rule = new RuleDescriptionParser('digits');
+        $this->translatorMock->shouldReceive('hasForLocale')->once()->with('apidoc::rules.dummy_rule')->andReturn(false);
+        $this->translatorMock->shouldReceive('hasForLocale')->once()->with('apidoc::rules.dummy_rule', 'en')->andReturn(false);
 
-        $actual = $rule->with(2)->getDescription();
+        $description = RuleDescriptionParser::parse('dummy_rule')->getDescription();
 
-        $this->assertEquals($expected, $actual);
+        $this->assertEmpty($description);
     }
 
-    public function testOnlyPassesParametersIfTheDescriptionAllows()
+    public function testAllowsToPassParametersToTheDescription()
     {
-        $expected = 'Only alphabetic characters allowed';
-        $rule = new RuleDescriptionParser('alpha');
+        $this->translatorMock->shouldReceive('hasForLocale')->twice()->with('apidoc::rules.digits')->andReturn(false);
+        $this->translatorMock->shouldReceive('hasForLocale')->once()->with('apidoc::rules.digits', 'en')->andReturn(true);
+        $this->translatorMock->shouldReceive('get')->once()->with('apidoc::rules.digits', [], 'en')->andReturn('Must have an exact length of `:attribute`');
 
-        $actual = $rule->with('dummy parameter')->getDescription();
+        $description = RuleDescriptionParser::parse('digits')->with(2)->getDescription();
 
-        $this->assertEquals($expected, $actual);
+        $this->assertEquals('Must have an exact length of `2`', $description);
     }
 
     public function testAllowsToPassMultipleParametersToTheDescription()
     {
-        $expected = 'Required if `2 + 2` is `4`';
-        $rule = new RuleDescriptionParser('required_if');
+        $this->translatorMock->shouldReceive('hasForLocale')->twice()->with('apidoc::rules.required_if')->andReturn(false);
+        $this->translatorMock->shouldReceive('hasForLocale')->once()->with('apidoc::rules.required_if', 'en')->andReturn(true);
+        $this->translatorMock->shouldReceive('get')->once()->with('apidoc::rules.required_if', [], 'en')->andReturn('Required if `:attribute` is `:attribute`');
 
-        $actual = $rule->with(['2 + 2', 4])->getDescription();
+        $description = RuleDescriptionParser::parse('required_if')->with(['2 + 2', 4])->getDescription();
 
-        $this->assertEquals($expected, $actual);
+        $this->assertEquals('Required if `2 + 2` is `4`', $description);
     }
 
     /**
@@ -80,12 +106,13 @@ class RuleDescriptionParserTest extends TestCase
     /**
      * Define environment setup.
      *
-     * @param  \Illuminate\Foundation\Application  $app
+     * @param  \Illuminate\Foundation\Application   $app
      *
      * @return void
      */
     protected function getEnvironmentSetUp($app)
     {
-        $app['config']->set('app.locale', 'en');
+        $app['config']->set('app.locale', 'es'); // Just to be different to default language.
+        $app['config']->set('app.fallback_locale', 'ch'); // Just to be different to default language.
     }
 }