Completed
Push — master ( 20dd6d...7a31d9 )
by Daniel
02:15
created

Compare::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 19
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 14
Bugs 0 Features 1
Metric Value
c 14
b 0
f 1
dl 0
loc 19
rs 9.4286
cc 2
eloc 15
nc 2
nop 0
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' => ['en_US' => 'EN', 'ro_RO' => 'RO'],
52
            'default_language'    => 'ro_RO',
53
            'name'                => 'Info-Compare'
54
        ];
55
        echo $this->setHeaderHtml();
56
        $rqst                   = new \Symfony\Component\HttpFoundation\Request;
57
        $superGlobals           = $rqst->createFromGlobals();
58
        $this->prepareForOutputForm(['SuperGlobals' => $superGlobals]);
59
        if (!is_null($superGlobals->get('Label'))) {
60
            $this->processInfos();
61
            echo $this->setFormCurlInfos(['SuperGlobals' => $superGlobals]);
62
            echo $this->setFormInfos(['SuperGlobals' => $superGlobals]);
63
        }
64
        echo $this->setFooterHtml();
65
    }
66
67
    private function displayTableFromMultiLevelArray($inArray)
68
    {
69
        if ((!is_array($inArray['source'])) || (!is_array($inArray['destination']))) {
70
            return '';
71
        }
72
        $firstRow     = $this->mergeArraysIntoFirstSecond($inArray['source'], $inArray['destination'], [
73
            'first',
74
            'second',
75
        ]);
76
        $secondRow    = $this->mergeArraysIntoFirstSecond($inArray['destination'], $inArray['source'], [
77
            'second',
78
            'first',
79
        ]);
80
        $row          = array_merge($firstRow, $secondRow);
81
        ksort($row);
82
        $urlArguments = '?Label=' . $inArray['SuperGlobals']->get('Label');
83
        $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...
84
                . '<thead><tr>'
85
                . '<th>Identifier</th>'
86
                . '<th><a href="' . $this->config['Servers'][$inArray['SuperGlobals']->get('localConfig')]['url']
87
                . $urlArguments . '" target="_blank">'
88
                . $this->config['Servers'][$inArray['SuperGlobals']->get('localConfig')]['name'] . '</a></th>'
89
                . '<th><a href="' . $this->config['Servers'][$inArray['SuperGlobals']->get('serverConfig')]['url']
90
                . $urlArguments . '" target="_blank">'
91
                . $this->config['Servers'][$inArray['SuperGlobals']->get('serverConfig')]['name'] . '</a></th>'
92
                . '</tr></thead>'
93
                . '<tbody>';
94
        if ($inArray['SuperGlobals']->get('displayOnlyDifferent') == '1') {
95
            $displayOnlyDifferent = true;
96
        } else {
97
            $displayOnlyDifferent = false;
98
        }
99
        foreach ($row as $key => $value) {
100
            $rowString = '<tr><td style="width:20%;">' . $key . '</td><td style="width:40%;">'
101
                    . str_replace(',', ', ', $value['first']) . '</td><td style="width:40%;">'
102
                    . str_replace(',', ', ', $value['second']) . '</td></tr>';
103
            if ($displayOnlyDifferent) {
104
                if ($value['first'] != $value['second']) {
105
                    $sString[] = $rowString;
106
                }
107
            } else {
108
                $sString[] = $rowString;
109
            }
110
        }
111
        $sString[] = '</tbody></table>';
112
        return implode('', $sString);
113
    }
114
115
    private function getConfiguration()
116
    {
117
        $strdConfig = $this->configuredDeployedInformators();
118
        foreach ($strdConfig['informators'] as $key => $value) {
119
            $this->config['Servers'][] = [
120
                'name' => $key,
121
                'url'  => $value,
122
            ];
123
        }
124
        $haystack                                         = array_keys($strdConfig['informators']);
125
        $this->config['Defaults']['Label']                = $strdConfig['default']['label'];
126
        $this->config['Defaults']['localConfig']          = array_search($strdConfig['default']['source'], $haystack);
127
        $this->config['Defaults']['serverConfig']         = array_search($strdConfig['default']['target'], $haystack);
128
        $this->config['Defaults']['displayOnlyDifferent'] = $strdConfig['default']['typeOfResults'];
129
    }
130
131
    private function mergeArraysIntoFirstSecond($firstArray, $secondArray, $pSequence = ['first', 'second'])
132
    {
133
        $row = [];
134
        foreach ($firstArray as $key => $value) {
135
            if (is_array($value)) {
136
                foreach ($value as $key2 => $value2) {
137
                    if (is_array($value2)) {
138
                        foreach ($value2 as $key3 => $value3) {
139
                            if (is_array($value3)) {
140
                                foreach ($value3 as $key4 => $value4) {
141
                                    $keyCrt                      = $key . '_' . $key2 . '__' . $key3 . '__' . $key4;
142
                                    $row[$keyCrt][$pSequence[0]] = $value4;
143
                                    if (isset($secondArray[$key][$key2][$key3][$key4])) {
144
                                        $row[$keyCrt][$pSequence[1]] = $secondArray[$key][$key2][$key3][$key4];
145
                                    } else {
146
                                        $row[$keyCrt][$pSequence[1]] = '';
147
                                    }
148
                                }
149
                            } else {
150
                                $keyCrt                      = $key . '_' . $key2 . '__' . $key3;
151
                                $row[$keyCrt][$pSequence[0]] = $value3;
152 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...
153
                                    $row[$keyCrt][$pSequence[1]] = $secondArray[$key][$key2][$key3];
154
                                } else {
155
                                    $row[$keyCrt][$pSequence[1]] = '';
156
                                }
157
                            }
158
                        }
159
                    } else {
160
                        $keyCrt                      = $key . '_' . $key2;
161
                        $row[$keyCrt][$pSequence[0]] = $value2;
162
                        if (isset($secondArray[$key][$key2])) {
163
                            $row[$keyCrt][$pSequence[1]] = $secondArray[$key][$key2];
164
                        } else {
165
                            $row[$keyCrt][$pSequence[1]] = '';
166
                        }
167
                    }
168
                }
169 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...
170
                $row[$key][$pSequence[0]] = $value;
171
                if (isset($secondArray[$key])) {
172
                    $row[$key][$pSequence[1]] = $secondArray[$key];
173
                } else {
174
                    $row[$key][$pSequence[1]] = '';
175
                }
176
            }
177
        }
178
        return $row;
179
    }
180
181
    private function prepareForOutputForm($inArray)
182
    {
183
        $urlToGetLbl = $this->config['Servers'][$this->config['Defaults']['localConfig']]['url']
184
                . '?Label=---' . urlencode(' List of known labels');
185
        $knownLabels = $this->getContentFromUrlThroughCurlAsArrayIfJson($urlToGetLbl)['response'];
186
        echo $this->setOutputForm([
187
            'Defaults'     => $this->config['Defaults'],
188
            'KnownLabels'  => $knownLabels,
189
            'Servers'      => $this->config['Servers'],
190
            'SuperGlobals' => $inArray['SuperGlobals'],
191
        ]);
192
    }
193
194
    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...
195
    {
196
        if (isset($_GET['localConfig']) && isset($_GET['serverConfig'])) {
197
            $urlArguments              = '?Label=' . urlencode($_GET['Label']);
198
            $source                    = $this->config['Servers'][$_GET['localConfig']]['url'] . $urlArguments;
199
            $this->localConfiguration  = $this->getContentFromUrlThroughCurlAsArrayIfJson($source);
200
            $destination               = $this->config['Servers'][$_GET['serverConfig']]['url'] . $urlArguments;
201
            $this->serverConfiguration = $this->getContentFromUrlThroughCurlAsArrayIfJson($destination);
202
        } else {
203
            $this->localConfiguration  = ['response' => '', 'info' => ''];
204
            $this->serverConfiguration = ['response' => '', 'info' => ''];
205
        }
206
    }
207
208
    private function setFooterHtml()
209
    {
210
        $sReturn   = [];
211
        $sReturn[] = '</div><!-- from main Tabber -->';
212
        $sReturn[] = '<div class="resetOnly author">&copy; 2015 Daniel Popiniuc</div>';
213
        $sReturn[] = '<hr/>';
214
        $sReturn[] = '<div class="disclaimer">'
215
                . 'The developer cannot be liable of any data input or results, '
216
                . 'included but not limited to any implication of these '
217
                . '(anywhere and whomever there might be these)!'
218
                . '</div>';
219
        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...
220
    }
221
222
    private function setFormCurlInfos($inArray)
223
    {
224
        return '<div class="tabbertab" id="tabCurl" title="CURL infos">'
225
                . $this->displayTableFromMultiLevelArray([
226
                    'source'       => $this->localConfiguration['info'],
227
                    'destination'  => $this->serverConfiguration['info'],
228
                    'SuperGlobals' => $inArray['SuperGlobals'],
229
                ])
230
                . '</div><!--from tabCurl-->';
231
    }
232
233
    private function setFormInfos($inArray)
234
    {
235
        return '<div class="tabbertab'
236
                . (is_null($inArray['SuperGlobals']->get('Label')) ? '' : ' tabbertabdefault')
237
                . '" id="tabConfigs" title="Informations">'
238
                . $this->displayTableFromMultiLevelArray([
239
                    'source'       => $this->localConfiguration['response'],
240
                    'destination'  => $this->serverConfiguration['response'],
241
                    'SuperGlobals' => $inArray['SuperGlobals'],
242
                ])
243
                . '</div><!--from tabConfigs-->';
244
    }
245
246
    private function setHeaderHtml()
247
    {
248
        return $this->setHeaderCommon([
249
                    'lang'       => 'en-US',
250
                    'title'      => $this->applicationFlags['name'],
251
                    'css'        => 'css/main.css',
252
                    'javascript' => 'js/tabber.min.js',
253
                ])
254
                . $this->setJavascriptContent('document.write(\'<style type="text/css">.tabber{display:none;}</style>\');')
255
                . '<h1>' . $this->applicationFlags['name'] . '</h1>'
256
                . '<div class="tabber" id="tab">';
257
    }
258
}
259