Completed
Push — master ( e7cb84...96842c )
by Daniel
02:22
created

Compare::setFormInfos()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 1
Metric Value
c 6
b 0
f 1
dl 0
loc 10
rs 9.4286
cc 2
eloc 8
nc 2
nop 1
1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\info_compare;
30
31
/**
32
 * Description of compare
33
 *
34
 * @author Transformer-
35
 */
36
class Compare
37
{
38
39
    use \danielgp\common_lib\CommonCode,
40
        \danielgp\info_compare\ConfigurationCompare,
41
        \danielgp\info_compare\OutputFormBuilder;
42
43
    private $config;
44
    private $localConfiguration;
45
    private $serverConfiguration;
46
47
    public function __construct()
48
    {
49
        $this->getConfiguration();
50
        $this->applicationFlags = [
0 ignored issues
show
Bug introduced by
The property applicationFlags does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
51
            'available_languages' => [
52
                'en_US' => 'EN',
53
                'ro_RO' => 'RO',
54
            ],
55
            'default_language'    => 'ro_RO',
56
            'name'                => 'Info-Compare'
57
        ];
58
        echo $this->setHeaderHtml();
59
        $rqst                   = new \Symfony\Component\HttpFoundation\Request;
60
        $superGlobals           = $rqst->createFromGlobals();
61
        $this->prepareForOutputForm([
62
            'SuperGlobals' => $superGlobals,
63
        ]);
64
        if (!is_null($superGlobals->get('Label'))) {
65
            $this->processInfos();
66
            echo $this->setFormCurlInfos($superGlobals);
67
            echo $this->setFormInfos($superGlobals);
68
        }
69
        echo $this->setFooterHtml();
70
    }
71
72
    private function displayTableFromMultiLevelArray($firstArray, $secondArray, $superGlobals)
0 ignored issues
show
Coding Style introduced by
displayTableFromMultiLevelArray uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
73
    {
74
        if ((!is_array($firstArray)) || (!is_array($secondArray))) {
75
            return '';
76
        }
77
        $firstRow     = $this->mergeArraysIntoFirstSecond($firstArray, $secondArray, ['first', 'second']);
78
        $secondRow    = $this->mergeArraysIntoFirstSecond($secondArray, $firstArray, ['second', 'first']);
79
        $row          = array_merge($firstRow, $secondRow);
80
        ksort($row);
81
        $urlArguments = '?Label=' . $_GET['Label'];
82
        $sString[]    = '<table style="width:100%">'
0 ignored issues
show
Coding Style Comprehensibility introduced by
$sString was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sString = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
83
                . '<thead><tr>'
84
                . '<th>Identifier</th>'
85
                . '<th><a href="' . $this->config['Servers'][$_GET['localConfig']]['url']
86
                . $urlArguments . '" target="_blank">'
87
                . $this->config['Servers'][$_GET['localConfig']]['name'] . '</a></th>'
88
                . '<th><a href="' . $this->config['Servers'][$_GET['serverConfig']]['url']
89
                . $urlArguments . '" target="_blank">'
90
                . $this->config['Servers'][$_GET['serverConfig']]['name'] . '</a></th>'
91
                . '</tr></thead>'
92
                . '<tbody>';
93
        if ($superGlobals->get('displayOnlyDifferent') == '1') {
94
            $displayOnlyDifferent = true;
95
        } else {
96
            $displayOnlyDifferent = false;
97
        }
98
        foreach ($row as $key => $value) {
99
            $rowString = '<tr><td style="width:20%;">' . $key . '</td><td style="width:40%;">'
100
                    . str_replace(',', ', ', $value['first']) . '</td><td style="width:40%;">'
101
                    . str_replace(',', ', ', $value['second']) . '</td></tr>';
102
            if ($displayOnlyDifferent) {
103
                if ($value['first'] != $value['second']) {
104
                    $sString[] = $rowString;
105
                }
106
            } else {
107
                $sString[] = $rowString;
108
            }
109
        }
110
        $sString[] = '</tbody></table>';
111
        return implode('', $sString);
112
    }
113
114
    private function getConfiguration()
115
    {
116
        $strdConfig = $this->configuredDeployedInformators();
117
        foreach ($strdConfig['informators'] as $key => $value) {
118
            $this->config['Servers'][] = [
119
                'name' => $key,
120
                'url'  => $value,
121
            ];
122
        }
123
        $haystack                                         = array_keys($strdConfig['informators']);
124
        $this->config['Defaults']['Label']                = $strdConfig['default']['label'];
125
        $this->config['Defaults']['localConfig']          = array_search($strdConfig['default']['source'], $haystack);
126
        $this->config['Defaults']['serverConfig']         = array_search($strdConfig['default']['target'], $haystack);
127
        $this->config['Defaults']['displayOnlyDifferent'] = $strdConfig['default']['typeOfResults'];
128
    }
129
130
    private function mergeArraysIntoFirstSecond($firstArray, $secondArray, $pSequence = ['first', 'second'])
131
    {
132
        $row = [];
133
        foreach ($firstArray as $key => $value) {
134
            if (is_array($value)) {
135
                foreach ($value as $key2 => $value2) {
136
                    if (is_array($value2)) {
137
                        foreach ($value2 as $key3 => $value3) {
138
                            if (is_array($value3)) {
139
                                foreach ($value3 as $key4 => $value4) {
140
                                    $keyCrt                      = $key . '_' . $key2 . '__' . $key3 . '__' . $key4;
141
                                    $row[$keyCrt][$pSequence[0]] = $value4;
142
                                    if (isset($secondArray[$key][$key2][$key3][$key4])) {
143
                                        $row[$keyCrt][$pSequence[1]] = $secondArray[$key][$key2][$key3][$key4];
144
                                    } else {
145
                                        $row[$keyCrt][$pSequence[1]] = '';
146
                                    }
147
                                }
148
                            } else {
149
                                $keyCrt                      = $key . '_' . $key2 . '__' . $key3;
150
                                $row[$keyCrt][$pSequence[0]] = $value3;
151 View Code Duplication
                                if (isset($secondArray[$key][$key2][$key3])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
152
                                    $row[$keyCrt][$pSequence[1]] = $secondArray[$key][$key2][$key3];
153
                                } else {
154
                                    $row[$keyCrt][$pSequence[1]] = '';
155
                                }
156
                            }
157
                        }
158
                    } else {
159
                        $keyCrt                      = $key . '_' . $key2;
160
                        $row[$keyCrt][$pSequence[0]] = $value2;
161
                        if (isset($secondArray[$key][$key2])) {
162
                            $row[$keyCrt][$pSequence[1]] = $secondArray[$key][$key2];
163
                        } else {
164
                            $row[$keyCrt][$pSequence[1]] = '';
165
                        }
166
                    }
167
                }
168 View Code Duplication
            } else {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
169
                $row[$key][$pSequence[0]] = $value;
170
                if (isset($secondArray[$key])) {
171
                    $row[$key][$pSequence[1]] = $secondArray[$key];
172
                } else {
173
                    $row[$key][$pSequence[1]] = '';
174
                }
175
            }
176
        }
177
        return $row;
178
    }
179
180
    private function prepareForOutputForm($inArray)
181
    {
182
        $urlToGetLbl = $this->config['Servers'][$this->config['Defaults']['localConfig']]['url']
183
                . '?Label=---' . urlencode(' List of known labels');
184
        $knownLabels = $this->getContentFromUrlThroughCurlAsArrayIfJson($urlToGetLbl)['response'];
185
        echo $this->setFormOptions([
186
            'Defaults'     => $this->config['Defaults'],
187
            'KnownLabels'  => $knownLabels,
188
            'Servers'      => $this->config['Servers'],
189
            'SuperGlobals' => $inArray['SuperGlobals'],
190
        ]);
191
    }
192
193
    private function processInfos()
0 ignored issues
show
Coding Style introduced by
processInfos uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
194
    {
195
        if (isset($_GET['localConfig']) && isset($_GET['serverConfig'])) {
196
            $urlArguments              = '?Label=' . urlencode($_GET['Label']);
197
            $source                    = $this->config['Servers'][$_GET['localConfig']]['url'] . $urlArguments;
198
            $this->localConfiguration  = $this->getContentFromUrlThroughCurlAsArrayIfJson($source);
199
            $destination               = $this->config['Servers'][$_GET['serverConfig']]['url'] . $urlArguments;
200
            $this->serverConfiguration = $this->getContentFromUrlThroughCurlAsArrayIfJson($destination);
201
        } else {
202
            $this->localConfiguration  = ['response' => '', 'info' => ''];
203
            $this->serverConfiguration = ['response' => '', 'info' => ''];
204
        }
205
    }
206
207
    private function setFooterHtml()
208
    {
209
        $sReturn   = [];
210
        $sReturn[] = '</div><!-- from main Tabber -->';
211
        $sReturn[] = '<div class="resetOnly author">&copy; 2015 Daniel Popiniuc</div>';
212
        $sReturn[] = '<hr/>';
213
        $sReturn[] = '<div class="disclaimer">'
214
                . 'The developer cannot be liable of any data input or results, '
215
                . 'included but not limited to any implication of these '
216
                . '(anywhere and whomever there might be these)!'
217
                . '</div>';
218
        return $this->setFooterCommon(implode('', $sReturn));
0 ignored issues
show
Documentation introduced by
implode('', $sReturn) is of type string, but the function expects a array|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
219
    }
220
221
    private function setFormCurlInfos($superGlobals)
222
    {
223
        $source      = $this->localConfiguration['info'];
224
        $destination = $this->serverConfiguration['info'];
225
        return '<div class="tabbertab" id="tabCurl" title="CURL infos">'
226
                . $this->displayTableFromMultiLevelArray($source, $destination, $superGlobals)
227
                . '</div><!--from tabCurl-->';
228
    }
229
230
    private function setFormInfos($superGlobals)
0 ignored issues
show
Coding Style introduced by
setFormInfos uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
231
    {
232
        $source      = $this->localConfiguration['response'];
233
        $destination = $this->serverConfiguration['response'];
234
        return '<div class="tabbertab'
235
                . (isset($_GET['Label']) ? ' tabbertabdefault' : '')
236
                . '" id="tabConfigs" title="Informations">'
237
                . $this->displayTableFromMultiLevelArray($source, $destination, $superGlobals)
238
                . '</div><!--from tabConfigs-->';
239
    }
240
241
    private function setHeaderHtml()
242
    {
243
        return $this->setHeaderCommon([
244
                    'lang'       => 'en-US',
245
                    'title'      => $this->applicationFlags['name'],
246
                    'css'        => 'css/main.css',
247
                    'javascript' => 'js/tabber.min.js',
248
                ])
249
                . $this->setJavascriptContent('document.write(\'<style type="text/css">.tabber{display:none;}</style>\');')
250
                . '<h1>' . $this->applicationFlags['name'] . '</h1>'
251
                . '<div class="tabber" id="tab">';
252
    }
253
}
254