Completed
Pull Request — master (#4)
by Timothy
03:57
created

WebDiagnosticsCollaborationTest   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 186
Duplicated Lines 26.88 %

Coupling/Cohesion

Components 1
Dependencies 13

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 9
c 1
b 0
f 1
lcom 1
cbo 13
dl 50
loc 186
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
B setUp() 0 27 1
B testDiagnosticsRouteReturnsJsonWithoutAnyFailures() 0 28 1
B testDiagnosticsRouteWithMigrationsUpToDate() 24 24 1
B testDiagnosticsRouteWithOrmSchemaValidation() 26 26 1
A getRequest() 0 7 1
A addHeader() 0 6 1
A dispatchDiagnostics() 0 8 1
A updateSchema() 0 12 1
A mergeConfigFile() 0 18 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
namespace AbacaphiliacTest\DoctrineORMDiagnosticsModuleTest\ModuleCollaboration;
4
5
use Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand;
6
use Symfony\Component\Console\Application;
7
use Symfony\Component\Console\Input\ArrayInput;
8
use Symfony\Component\Console\Output\NullOutput;
9
use Zend\Http\PhpEnvironment\Request;
10
use Zend\Json\Json;
11
use Zend\ServiceManager\ServiceLocatorInterface;
12
use Zend\ServiceManager\ServiceManager;
13
use Zend\Stdlib\ArrayUtils;
14
use Zend\Stdlib\ResponseInterface;
15
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
16
17
class WebDiagnosticsCollaborationTest extends AbstractHttpControllerTestCase
18
{
19
    /** @var Application */
20
    private $cli;
21
22
    public function setUp()
23
    {
24
        parent::setUp();
25
        
26
        \PHPUnit_Framework_Error_Deprecated::$enabled = false;
27
        
28
        $this->setApplicationConfig([
29
            'modules' => [
30
                'DoctrineModule',
31
                'DoctrineORMModule',
32
                'ZFTool',
33
                'Abacaphiliac\DoctrineORMDiagnosticsModule',
34
            ],
35
            'module_listener_options' => [
36
                'config_static_paths' => [
37
                    __DIR__ . '/test.config.php',
38
                ],
39
                'module_paths' => [],
40
            ],
41
        ]);
42
        
43
        $serviceLocator = $this->getApplicationServiceLocator();
44
        \PHPUnit_Framework_Assert::assertInstanceOf(ServiceLocatorInterface::class, $serviceLocator);
45
46
        $this->cli = $serviceLocator->get('doctrine.cli');
0 ignored issues
show
Documentation Bug introduced by
It seems like $serviceLocator->get('doctrine.cli') can also be of type array. However, the property $cli is declared as type object<Symfony\Component\Console\Application>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
47
        \PHPUnit_Framework_Assert::assertInstanceOf(Application::class, $this->cli);
48
    }
49
    
50
    public function testDiagnosticsRouteReturnsJsonWithoutAnyFailures()
51
    {
52
        $this->dispatchDiagnostics(200);
53
        
54
        $response = $this->getResponse();
55
        \PHPUnit_Framework_Assert::assertInstanceOf(ResponseInterface::class, $response);
56
        
57
        $encoded = $response->getContent();
58
        \PHPUnit_Framework_Assert::assertNotEmpty($encoded);
59
        
60
        $decoded = Json::decode($encoded);
61
        $encodedPretty = json_encode($decoded, JSON_PRETTY_PRINT);
62
        \PHPUnit_Framework_Assert::assertAttributeEquals(true, 'passed', $decoded, $encodedPretty);
63
        \PHPUnit_Framework_Assert::assertObjectHasAttribute('details', $decoded, $encodedPretty);
64
        $details = $decoded->details;
65
        
66
        \PHPUnit_Framework_Assert::assertObjectHasAttribute(
67
            'DoctrineORMDiagnosticsModule: Database Connection',
68
            $details,
69
            $encodedPretty
70
        );
71
        
72
        \PHPUnit_Framework_Assert::assertObjectHasAttribute(
73
            'DoctrineORMDiagnosticsModule: ORM Info',
74
            $details,
75
            $encodedPretty
76
        );
77
    }
78
    
79 View Code Duplication
    public function testDiagnosticsRouteWithMigrationsUpToDate()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
80
    {
81
        $this->mergeConfigFile(__DIR__ . '/../../../config/migrations_schema.global.php.dist');
82
83
        $this->dispatchDiagnostics(200);
84
        
85
        $response = $this->getResponse();
86
        \PHPUnit_Framework_Assert::assertInstanceOf(ResponseInterface::class, $response);
87
        
88
        $encoded = $response->getContent();
89
        \PHPUnit_Framework_Assert::assertNotEmpty($encoded);
90
        
91
        $decoded = Json::decode($encoded);
92
        $encodedPretty = json_encode($decoded, JSON_PRETTY_PRINT);
93
        \PHPUnit_Framework_Assert::assertAttributeEquals(true, 'passed', $decoded, $encodedPretty);
94
        \PHPUnit_Framework_Assert::assertObjectHasAttribute('details', $decoded, $encodedPretty);
95
        $details = $decoded->details;
96
        
97
        \PHPUnit_Framework_Assert::assertObjectHasAttribute(
98
            'DoctrineORMDiagnosticsModule: Schema Migrations Up-To-Date',
99
            $details,
100
            $encodedPretty
101
        );
102
    }
103
    
104 View Code Duplication
    public function testDiagnosticsRouteWithOrmSchemaValidation()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
105
    {
106
        $this->updateSchema();
107
108
        $this->mergeConfigFile(__DIR__ . '/../../../config/orm_schema.global.php.dist');
109
        
110
        $this->dispatchDiagnostics(200);
111
        
112
        $response = $this->getResponse();
113
        \PHPUnit_Framework_Assert::assertInstanceOf(ResponseInterface::class, $response);
114
        
115
        $encoded = $response->getContent();
116
        \PHPUnit_Framework_Assert::assertNotEmpty($encoded);
117
        
118
        $decoded = Json::decode($encoded);
119
        $encodedPretty = json_encode($decoded, JSON_PRETTY_PRINT);
120
        \PHPUnit_Framework_Assert::assertAttributeEquals(true, 'passed', $decoded, $encodedPretty);
121
        \PHPUnit_Framework_Assert::assertObjectHasAttribute('details', $decoded, $encodedPretty);
122
        $details = $decoded->details;
123
        
124
        \PHPUnit_Framework_Assert::assertObjectHasAttribute(
125
            'DoctrineORMDiagnosticsModule: ORM Schema Valid',
126
            $details,
127
            $encodedPretty
128
        );
129
    }
130
131
    /**
132
     * @return Request
133
     */
134
    public function getRequest()
135
    {
136
        $request = parent::getRequest();
137
        \PHPUnit_Framework_Assert::assertInstanceOf(Request::class, $request);
138
139
        return $request;
140
    }
141
142
    /**
143
     * @param $name
144
     * @param $value
145
     * @return void
146
     */
147
    private function addHeader($name, $value)
148
    {
149
        $request = $this->getRequest();
150
        $headers = $request->getHeaders();
151
        $headers->addHeaderLine($name, $value);
152
    }
153
154
    /**
155
     * @param int $statusCode
156
     * @return void
157
     */
158
    private function dispatchDiagnostics($statusCode = 200)
159
    {
160
        $this->addHeader('Accept', 'application/json');
161
        
162
        $this->dispatch('/diagnostics', 'GET', [], true);
163
        
164
        $this->assertResponseStatusCode($statusCode);
165
    }
166
167
    private function updateSchema()
168
    {
169
        $command = $this->cli->get('orm:schema-tool:update');
170
        \PHPUnit_Framework_Assert::assertInstanceOf(UpdateCommand::class, $command);
171
        
172
        $definition = $command->getDefinition();
173
        $input = new ArrayInput(['--force' => true], $definition);
174
        $output = new NullOutput();
175
        
176
        $exitCode = $command->run($input, $output);
177
        \PHPUnit_Framework_Assert::assertSame(0, $exitCode);
178
    }
179
180
    /**
181
     * @param $file
182
     * @return void
183
     */
184
    private function mergeConfigFile($file)
185
    {
186
        $override = require $file;
187
        \PHPUnit_Framework_Assert::assertInternalType('array', $override);
188
        
189
        $serviceManager = $this->getApplicationServiceLocator();
190
        \PHPUnit_Framework_Assert::assertInstanceOf(ServiceManager::class, $serviceManager);
191
        
192
        $allowOverride = $serviceManager->getAllowOverride();
193
        $serviceManager->setAllowOverride(true);
194
        
195
        $config = $serviceManager->get('config');
196
        \PHPUnit_Framework_Assert::assertInternalType('array', $config);
197
        
198
        $serviceManager->setService('config', ArrayUtils::merge($config, $override));
0 ignored issues
show
Bug introduced by
It seems like $config defined by $serviceManager->get('config') on line 195 can also be of type object; however, Zend\Stdlib\ArrayUtils::merge() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
199
        
200
        $serviceManager->setAllowOverride($allowOverride);
201
    }
202
}
203