[TASK] Use stricter types in JsonView and its test 00/56500/6
authorOliver Klee <typo3-coding@oliverklee.de>
Sat, 31 Mar 2018 18:56:06 +0000 (20:56 +0200)
committerGeorg Ringer <georg.ringer@gmail.com>
Thu, 19 Apr 2018 06:59:28 +0000 (08:59 +0200)
Also clean up the code a bit, use more imports, and use
assertSame to do type-safe checks.

Resolves: #84571

Releases: master
Change-Id: I933a8354b0cd866ffcb2178664899c94821219a4
Reviewed-on: https://review.typo3.org/56500
Tested-by: TYPO3com <no-reply@typo3.com>
Reviewed-by: Mathias Schreiber <mathias.schreiber@typo3.com>
Tested-by: Mathias Schreiber <mathias.schreiber@typo3.com>
Reviewed-by: Wouter Wolters <typo3@wouterwolters.nl>
Reviewed-by: Thomas Maroschik <tmaroschik@dfau.de>
Tested-by: Thomas Maroschik <tmaroschik@dfau.de>
Reviewed-by: Kay Strobach <typo3@kay-strobach.de>
Tested-by: Kay Strobach <typo3@kay-strobach.de>
Reviewed-by: Georg Ringer <georg.ringer@gmail.com>
Tested-by: Georg Ringer <georg.ringer@gmail.com>
typo3/sysext/extbase/Classes/Mvc/View/JsonView.php
typo3/sysext/extbase/Tests/Unit/Mvc/View/JsonViewTest.php

index 1ffd40d..62c80a1 100644 (file)
@@ -1,4 +1,6 @@
 <?php
+declare(strict_types = 1);
+
 namespace TYPO3\CMS\Extbase\Mvc\View;
 
 /*
@@ -15,6 +17,9 @@ namespace TYPO3\CMS\Extbase\Mvc\View;
  */
 
 use TYPO3\CMS\Extbase\Mvc\Web\Response as WebResponse;
+use TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface;
+use TYPO3\CMS\Extbase\Reflection\ObjectAccess;
+use TYPO3\CMS\Extbase\Reflection\ReflectionService;
 use TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController;
 
 /**
@@ -41,7 +46,7 @@ class JsonView extends AbstractView
     const EXPOSE_CLASSNAME_UNQUALIFIED = 2;
 
     /**
-     * @var \TYPO3\CMS\Extbase\Reflection\ReflectionService
+     * @var ReflectionService
      */
     protected $reflectionService;
 
@@ -53,7 +58,7 @@ class JsonView extends AbstractView
     /**
      * Only variables whose name is contained in this array will be rendered
      *
-     * @var array
+     * @var string[]
      */
     protected $variablesToRender = ['value'];
 
@@ -158,22 +163,22 @@ class JsonView extends AbstractView
     protected $configuration = [];
 
     /**
-     * @var \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface
+     * @var PersistenceManagerInterface
      */
     protected $persistenceManager;
 
     /**
-     * @param \TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface $persistenceManager
+     * @param PersistenceManagerInterface $persistenceManager
      */
-    public function injectPersistenceManager(\TYPO3\CMS\Extbase\Persistence\PersistenceManagerInterface $persistenceManager)
+    public function injectPersistenceManager(PersistenceManagerInterface $persistenceManager): void
     {
         $this->persistenceManager = $persistenceManager;
     }
 
     /**
-     * @param \TYPO3\CMS\Extbase\Reflection\ReflectionService $reflectionService
+     * @param ReflectionService $reflectionService
      */
-    public function injectReflectionService(\TYPO3\CMS\Extbase\Reflection\ReflectionService $reflectionService)
+    public function injectReflectionService(ReflectionService $reflectionService): void
     {
         $this->reflectionService = $reflectionService;
     }
@@ -185,7 +190,7 @@ class JsonView extends AbstractView
      * @param array $variablesToRender
      * @api
      */
-    public function setVariablesToRender(array $variablesToRender)
+    public function setVariablesToRender(array $variablesToRender): void
     {
         $this->variablesToRender = $variablesToRender;
     }
@@ -193,7 +198,7 @@ class JsonView extends AbstractView
     /**
      * @param array $configuration The rendering configuration for this JSON view
      */
-    public function setConfiguration(array $configuration)
+    public function setConfiguration(array $configuration): void
     {
         $this->configuration = $configuration;
     }
@@ -206,7 +211,7 @@ class JsonView extends AbstractView
      * @return string The JSON encoded variables
      * @api
      */
-    public function render()
+    public function render(): string
     {
         $response = $this->controllerContext->getResponse();
         if ($response instanceof WebResponse) {
@@ -296,12 +301,12 @@ class JsonView extends AbstractView
      * @param array $configuration Configuration for transforming the given object or NULL
      * @return array|string Object structure as an array or as a rendered string (for a DateTime instance)
      */
-    protected function transformObject($object, array $configuration)
+    protected function transformObject(object $object, array $configuration)
     {
         if ($object instanceof \DateTime) {
             return $object->format(\DateTime::ATOM);
         }
-        $propertyNames = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getGettablePropertyNames($object);
+        $propertyNames = ObjectAccess::getGettablePropertyNames($object);
 
         $propertiesToRender = [];
         foreach ($propertyNames as $propertyName) {
@@ -312,7 +317,7 @@ class JsonView extends AbstractView
                 continue;
             }
 
-            $propertyValue = \TYPO3\CMS\Extbase\Reflection\ObjectAccess::getProperty($object, $propertyName);
+            $propertyValue = ObjectAccess::getProperty($object, $propertyName);
 
             if (!is_array($propertyValue) && !is_object($propertyValue)) {
                 $propertiesToRender[$propertyName] = $propertyValue;
index 9d578d6..90b30f3 100644 (file)
@@ -1,4 +1,6 @@
 <?php
+declare(strict_types = 1);
+
 namespace TYPO3\CMS\Extbase\Tests\Unit\Mvc\View;
 
 /*
@@ -14,12 +16,16 @@ namespace TYPO3\CMS\Extbase\Tests\Unit\Mvc\View;
  * The TYPO3 project - inspiring people to share!
  */
 
+use TYPO3\CMS\Extbase\Mvc\Controller\ControllerContext;
 use TYPO3\CMS\Extbase\Mvc\View\JsonView;
+use TYPO3\CMS\Extbase\Mvc\Web\Response;
+use TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager;
+use TYPO3\TestingFramework\Core\Unit\UnitTestCase;
 
 /**
  * Testcase for the JSON view
  */
-class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
+class JsonViewTest extends UnitTestCase
 {
     /**
      * @var \TYPO3\CMS\Extbase\Mvc\View\JsonView
@@ -27,25 +33,25 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
     protected $view;
 
     /**
-     * @var \TYPO3\CMS\Extbase\Mvc\Controller\ControllerContext
+     * @var ControllerContext
      */
     protected $controllerContext;
 
     /**
-     * @var \TYPO3\CMS\Extbase\Mvc\Web\Response
+     * @var Response
      */
     protected $response;
 
     /**
      * Sets up this test case
      */
-    protected function setUp()
+    protected function setUp(): void
     {
-        $this->view = $this->getMockBuilder(\TYPO3\CMS\Extbase\Mvc\View\JsonView::class)
+        $this->view = $this->getMockBuilder(JsonView::class)
             ->setMethods(['loadConfigurationFromYamlFile'])
             ->getMock();
-        $this->controllerContext = $this->createMock(\TYPO3\CMS\Extbase\Mvc\Controller\ControllerContext::class);
-        $this->response = $this->createMock(\TYPO3\CMS\Extbase\Mvc\Web\Response::class);
+        $this->controllerContext = $this->createMock(ControllerContext::class);
+        $this->response = $this->createMock(Response::class);
         $this->controllerContext->expects($this->any())->method('getResponse')->will($this->returnValue($this->response));
         $this->view->setControllerContext($this->controllerContext);
     }
@@ -54,7 +60,7 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
      * data provider for testTransformValue()
      * @return array
      */
-    public function jsonViewTestData()
+    public function jsonViewTestData(): array
     {
         $output = [];
 
@@ -118,14 +124,14 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
             '_only' => ['name', 'path', 'properties'],
             '_descend' => [
                  'properties' => [
-                      '_exclude' => ['prohibited']
-                 ]
-            ]
+                      '_exclude' => ['prohibited'],
+                 ],
+            ],
         ];
         $expected = [
             'name' => 'name',
             'path' => 'path',
-            'properties' => ['foo' => 'bar']
+            'properties' => ['foo' => 'bar'],
         ];
         $output[] = [$object, $configuration, $expected, 'descending into arrays should be possible'];
 
@@ -146,27 +152,32 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
         $configuration = [];
         $expected = '2013-08-15T15:25:30-07:00';
         $output[] = [$dateTimeObject, $configuration, $expected, 'DateTime object in America/Los_Angeles time zone could not be serialized.'];
+
         return $output;
     }
 
     /**
      * @test
+     * @param object|array $object
+     * @param array $configuration
+     * @param array|string $expected
+     * @param string $description
      * @dataProvider jsonViewTestData
      */
-    public function testTransformValue($object, $configuration, $expected, $description)
+    public function testTransformValue($object, array $configuration, $expected, string $description): void
     {
-        $jsonView = $this->getAccessibleMock(\TYPO3\CMS\Extbase\Mvc\View\JsonView::class, ['dummy'], [], '', false);
+        $jsonView = $this->getAccessibleMock(JsonView::class, ['dummy'], [], '', false);
 
         $actual = $jsonView->_call('transformValue', $object, $configuration);
 
-        $this->assertEquals($expected, $actual, $description);
+        $this->assertSame($expected, $actual, $description);
     }
 
     /**
      * data provider for testTransformValueWithObjectIdentifierExposure()
      * @return array
      */
-    public function objectIdentifierExposureTestData()
+    public function objectIdentifierExposureTestData(): array
     {
         $output = [];
 
@@ -177,9 +188,9 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
         $configuration = [
             '_descend' => [
                  'value1' => [
-                      '_exposeObjectIdentifier' => true
-                 ]
-            ]
+                      '_exposeObjectIdentifier' => true,
+                 ],
+            ],
         ];
 
         $expected = ['value1' => ['__identity' => $dummyIdentifier]];
@@ -194,27 +205,37 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
 
     /**
      * @test
+     * @param object $object
+     * @param array $configuration
+     * @param array $expected
+     * @param string $dummyIdentifier
+     * @param string $description
      * @dataProvider objectIdentifierExposureTestData
      */
-    public function testTransformValueWithObjectIdentifierExposure($object, $configuration, $expected, $dummyIdentifier, $description)
-    {
-        $persistenceManagerMock = $this->getMockBuilder(\TYPO3\CMS\Extbase\Persistence\Generic\PersistenceManager::class)
+    public function testTransformValueWithObjectIdentifierExposure(
+        object $object,
+        array $configuration,
+        array $expected,
+        string $dummyIdentifier,
+        string $description
+    ): void {
+        $persistenceManagerMock = $this->getMockBuilder(PersistenceManager::class)
             ->setMethods(['getIdentifierByObject'])
             ->getMock();
-        $jsonView = $this->getAccessibleMock(\TYPO3\CMS\Extbase\Mvc\View\JsonView::class, ['dummy'], [], '', false);
+        $jsonView = $this->getAccessibleMock(JsonView::class, ['dummy'], [], '', false);
         $jsonView->_set('persistenceManager', $persistenceManagerMock);
 
         $persistenceManagerMock->expects($this->once())->method('getIdentifierByObject')->with($object->value1)->will($this->returnValue($dummyIdentifier));
 
         $actual = $jsonView->_call('transformValue', $object, $configuration);
 
-        $this->assertEquals($expected, $actual, $description);
+        $this->assertSame($expected, $actual, $description);
     }
 
     /**
      * A data provider
      */
-    public function exposeClassNameSettingsAndResults()
+    public function exposeClassNameSettingsAndResults(): array
     {
         $className = $this->getUniqueId('DummyClass');
         $namespace = 'TYPO3\CMS\Extbase\Tests\Unit\Mvc\View\\' . $className;
@@ -223,29 +244,37 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
                 JsonView::EXPOSE_CLASSNAME_FULLY_QUALIFIED,
                 $className,
                 $namespace,
-                ['value1' => ['__class' => $namespace . '\\' . $className]]
+                ['value1' => ['__class' => $namespace . '\\' . $className]],
             ],
             [
                 JsonView::EXPOSE_CLASSNAME_UNQUALIFIED,
                 $className,
                 $namespace,
-                ['value1' => ['__class' => $className]]
+                ['value1' => ['__class' => $className]],
             ],
             [
                 null,
                 $className,
                 $namespace,
-                ['value1' => []]
+                ['value1' => []],
             ]
         ];
     }
 
     /**
      * @test
+     * @param int|null $exposeClassNameSetting
+     * @param string $className
+     * @param string $namespace
+     * @param array $expected
      * @dataProvider exposeClassNameSettingsAndResults
      */
-    public function viewExposesClassNameFullyIfConfiguredSo($exposeClassNameSetting, $className, $namespace, $expected)
-    {
+    public function viewExposesClassNameFullyIfConfiguredSo(
+        ?int $exposeClassNameSetting,
+        string $className,
+        string $namespace,
+        array $expected
+    ): void {
         $fullyQualifiedClassName = $namespace . '\\' . $className;
         if (class_exists($fullyQualifiedClassName) === false) {
             eval('namespace ' . $namespace . '; class ' . $className . ' {}');
@@ -256,9 +285,9 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
         $configuration = [
             '_descend' => [
                 'value1' => [
-                    '_exposeClassName' => $exposeClassNameSetting
-                ]
-            ]
+                    '_exposeClassName' => $exposeClassNameSetting,
+                ],
+            ],
         ];
         $reflectionService = $this->getMockBuilder(\TYPO3\CMS\Extbase\Reflection\ReflectionService::class)
             ->setMethods([ 'getClassNameByObject' ])
@@ -270,13 +299,13 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
         $jsonView = $this->getAccessibleMock(\TYPO3\CMS\Extbase\Mvc\View\JsonView::class, ['dummy'], [], '', false);
         $this->inject($jsonView, 'reflectionService', $reflectionService);
         $actual = $jsonView->_call('transformValue', $object, $configuration);
-        $this->assertEquals($expected, $actual);
+        $this->assertSame($expected, $actual);
     }
 
     /**
      * @test
      */
-    public function renderSetsContentTypeHeader()
+    public function renderSetsContentTypeHeader(): void
     {
         $this->response->expects($this->once())->method('setHeader')->with('Content-Type', 'application/json');
 
@@ -286,7 +315,7 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
     /**
      * @test
      */
-    public function renderReturnsJsonRepresentationOfAssignedObject()
+    public function renderReturnsJsonRepresentationOfAssignedObject(): void
     {
         $object = new \stdClass();
         $object->foo = 'Foo';
@@ -294,33 +323,33 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
 
         $expectedResult = '{"foo":"Foo"}';
         $actualResult = $this->view->render();
-        $this->assertEquals($expectedResult, $actualResult);
+        $this->assertSame($expectedResult, $actualResult);
     }
 
     /**
      * @test
      */
-    public function renderReturnsJsonRepresentationOfAssignedArray()
+    public function renderReturnsJsonRepresentationOfAssignedArray(): void
     {
         $array = ['foo' => 'Foo', 'bar' => 'Bar'];
         $this->view->assign('value', $array);
 
         $expectedResult = '{"foo":"Foo","bar":"Bar"}';
         $actualResult = $this->view->render();
-        $this->assertEquals($expectedResult, $actualResult);
+        $this->assertSame($expectedResult, $actualResult);
     }
 
     /**
      * @test
      */
-    public function renderReturnsJsonRepresentationOfAssignedSimpleValue()
+    public function renderReturnsJsonRepresentationOfAssignedSimpleValue(): void
     {
         $value = 'Foo';
         $this->view->assign('value', $value);
 
         $expectedResult = '"Foo"';
         $actualResult = $this->view->render();
-        $this->assertEquals($expectedResult, $actualResult);
+        $this->assertSame($expectedResult, $actualResult);
     }
 
     /**
@@ -366,20 +395,20 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
     /**
      * @test
      */
-    public function renderReturnsNullIfNameOfAssignedVariableIsNotEqualToValue()
+    public function renderReturnsNullIfNameOfAssignedVariableIsNotEqualToValue(): void
     {
         $value = 'Foo';
         $this->view->assign('foo', $value);
 
         $expectedResult = 'null';
         $actualResult = $this->view->render();
-        $this->assertEquals($expectedResult, $actualResult);
+        $this->assertSame($expectedResult, $actualResult);
     }
 
     /**
      * @test
      */
-    public function renderOnlyRendersVariableWithTheNameValue()
+    public function renderOnlyRendersVariableWithTheNameValue(): void
     {
         $this->view
             ->assign('value', 'Value')
@@ -387,13 +416,13 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
 
         $expectedResult = '"Value"';
         $actualResult = $this->view->render();
-        $this->assertEquals($expectedResult, $actualResult);
+        $this->assertSame($expectedResult, $actualResult);
     }
 
     /**
      * @test
      */
-    public function setVariablesToRenderOverridesValueToRender()
+    public function setVariablesToRenderOverridesValueToRender(): void
     {
         $value = 'Foo';
         $this->view->assign('foo', $value);
@@ -401,13 +430,13 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
 
         $expectedResult = '"Foo"';
         $actualResult = $this->view->render();
-        $this->assertEquals($expectedResult, $actualResult);
+        $this->assertSame($expectedResult, $actualResult);
     }
 
     /**
      * @test
      */
-    public function renderRendersMultipleValuesIfTheyAreSpecifiedAsVariablesToRender()
+    public function renderRendersMultipleValuesIfTheyAreSpecifiedAsVariablesToRender(): void
     {
         $this->view
             ->assign('value', 'Value1')
@@ -417,13 +446,13 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
 
         $expectedResult = '{"value":"Value1","secondValue":"Value2"}';
         $actualResult = $this->view->render();
-        $this->assertEquals($expectedResult, $actualResult);
+        $this->assertSame($expectedResult, $actualResult);
     }
 
     /**
      * @test
      */
-    public function renderCanRenderMultipleComplexObjects()
+    public function renderCanRenderMultipleComplexObjects(): void
     {
         $array = ['foo' => ['bar' => 'Baz']];
         $object = new \stdClass();
@@ -437,13 +466,13 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
 
         $expectedResult = '{"array":{"foo":{"bar":"Baz"}},"object":{"foo":"Foo"}}';
         $actualResult = $this->view->render();
-        $this->assertEquals($expectedResult, $actualResult);
+        $this->assertSame($expectedResult, $actualResult);
     }
 
     /**
      * @test
      */
-    public function renderCanRenderPlainArray()
+    public function renderCanRenderPlainArray(): void
     {
         $array = [['name' => 'Foo', 'secret' => true], ['name' => 'Bar', 'secret' => true]];
 
@@ -451,20 +480,20 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
         $this->view->setConfiguration([
             'value' => [
                 '_descendAll' => [
-                    '_only' => ['name']
-                ]
-            ]
+                    '_only' => ['name'],
+                ],
+            ],
         ]);
 
         $expectedResult = '[{"name":"Foo"},{"name":"Bar"}]';
         $actualResult = $this->view->render();
-        $this->assertEquals($expectedResult, $actualResult);
+        $this->assertSame($expectedResult, $actualResult);
     }
 
     /**
      * @test
      */
-    public function descendAllKeepsArrayIndexes()
+    public function descendAllKeepsArrayIndexes(): void
     {
         $array = [['name' => 'Foo', 'secret' => true], ['name' => 'Bar', 'secret' => true]];
 
@@ -472,13 +501,13 @@ class JsonViewTest extends \TYPO3\TestingFramework\Core\Unit\UnitTestCase
         $this->view->setConfiguration([
             'value' => [
                 '_descendAll' => [
-                    '_descendAll' => []
-                ]
-            ]
+                    '_descendAll' => [],
+                ],
+            ],
         ]);
 
         $expectedResult = '[{"name":"Foo","secret":true},{"name":"Bar","secret":true}]';
         $actualResult = $this->view->render();
-        $this->assertEquals($expectedResult, $actualResult);
+        $this->assertSame($expectedResult, $actualResult);
     }
 }