Passed
Pull Request — master (#14)
by Tim
02:07
created

ConsentController   A

Complexity

Total Complexity 42

Size/Duplication

Total Lines 276
Duplicated Lines 0 %

Importance

Changes 8
Bugs 0 Features 0
Metric Value
eloc 147
c 8
b 0
f 0
dl 0
loc 276
rs 9.0399
wmc 42

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
F getconsent() 0 164 31
B noconsent() 0 44 8
A logoutcompleted() 0 3 1
A logout() 0 8 1

How to fix   Complexity   

Complex Class

Complex classes like ConsentController often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ConsentController, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
declare(strict_types=1);
4
5
namespace SimpleSAML\Module\consent\Controller;
6
7
use Exception;
8
use SimpleSAML\Auth;
9
use SimpleSAML\Configuration;
10
use SimpleSAML\Error;
11
use SimpleSAML\HTTP\RunnableResponse;
12
use SimpleSAML\IdP;
13
use SimpleSAML\Locale\Translate;
14
use SimpleSAML\Logger;
15
use SimpleSAML\Module;
16
use SimpleSAML\Session;
17
use SimpleSAML\Stats;
18
use SimpleSAML\Utils;
19
use SimpleSAML\XHTML\Template;
20
use Symfony\Component\HttpFoundation\Request;
21
22
/**
23
 * Controller class for the consent module.
24
 *
25
 * This class serves the consent views available in the module.
26
 *
27
 * @package SimpleSAML\Module\consent
28
 */
29
class ConsentController
30
{
31
    /** @var \SimpleSAML\Configuration */
32
    protected $config;
33
34
    /** @var \SimpleSAML\Session */
35
    protected $session;
36
37
38
    /**
39
     * ConsentController constructor.
40
     *
41
     * @param \SimpleSAML\Configuration $config The configuration to use.
42
     * @param \SimpleSAML\Session $session The current user session.
43
     */
44
    public function __construct(Configuration $config, Session $session)
45
    {
46
        $this->config = $config;
47
        $this->session = $session;
48
    }
49
50
51
52
    /**
53
     * Display consent form.
54
     *
55
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
56
     * @param string $id The StateId
57
     *
58
     * @return \SimpleSAML\XHTML\Template
59
     */
60
    public function getconsent(Request $request, string $id): Template
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

60
    public function getconsent(/** @scrutinizer ignore-unused */ Request $request, string $id): Template

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
61
    {
62
        session_cache_limiter('nocache');
63
64
        Logger::info('Consent - getconsent: Accessing consent interface');
65
66
        $state = Auth\State::loadState($id, 'consent:request');
67
68
        if (is_null($state)) {
69
            throw new Error\NoState();
70
        } elseif (array_key_exists('core:SP', $state)) {
71
            $spentityid = $state['core:SP'];
72
        } elseif (array_key_exists('saml:sp:State', $state)) {
73
            $spentityid = $state['saml:sp:State']['core:SP'];
74
        } else {
75
            $spentityid = 'UNKNOWN';
76
        }
77
78
        // The user has pressed the yes-button
79
        if (array_key_exists('yes', $_REQUEST)) {
80
            if (array_key_exists('saveconsent', $_REQUEST)) {
81
                Logger::stats('consentResponse remember');
82
            } else {
83
                Logger::stats('consentResponse rememberNot');
84
            }
85
86
            $statsInfo = [
87
                'remember' => array_key_exists('saveconsent', $_REQUEST),
88
            ];
89
            if (isset($state['Destination']['entityid'])) {
90
                $statsInfo['spEntityID'] = $state['Destination']['entityid'];
91
            }
92
            Stats::log('consent:accept', $statsInfo);
93
94
            if (
95
                array_key_exists('consent:store', $state)
96
                && array_key_exists('saveconsent', $_REQUEST)
97
                && $_REQUEST['saveconsent'] === '1'
98
            ) {
99
                // Save consent
100
                $store = $state['consent:store'];
101
                $userId = $state['consent:store.userId'];
102
                $targetedId = $state['consent:store.destination'];
103
                $attributeSet = $state['consent:store.attributeSet'];
104
105
                Logger::debug(
106
                    'Consent - saveConsent() : [' . $userId . '|' . $targetedId . '|' . $attributeSet . ']'
107
                );
108
                try {
109
                    $store->saveConsent($userId, $targetedId, $attributeSet);
110
                } catch (Exception $e) {
111
                    Logger::error('Consent: Error writing to storage: ' . $e->getMessage());
112
                }
113
            }
114
115
            Auth\ProcessingChain::resumeProcessing($state);
116
        }
117
118
        // Prepare attributes for presentation
119
        $attributes = $state['Attributes'];
120
        $noconsentattributes = $state['consent:noconsentattributes'];
121
122
        // Remove attributes that do not require consent
123
        foreach ($attributes as $attrkey => $attrval) {
124
            if (in_array($attrkey, $noconsentattributes, true)) {
125
                unset($attributes[$attrkey]);
126
            }
127
        }
128
        $para = [
129
            'attributes' => &$attributes
130
        ];
131
132
        // Reorder attributes according to attributepresentation hooks
133
        Module::callHooks('attributepresentation', $para);
134
135
        // Parse parameters
136
        if (array_key_exists('name', $state['Source'])) {
137
            $srcName = $state['Source']['name'];
138
        } elseif (array_key_exists('OrganizationDisplayName', $state['Source'])) {
139
            $srcName = $state['Source']['OrganizationDisplayName'];
140
        } else {
141
            $srcName = $state['Source']['entityid'];
142
        }
143
144
        if (array_key_exists('name', $state['Destination'])) {
145
            $dstName = $state['Destination']['name'];
146
        } elseif (array_key_exists('OrganizationDisplayName', $state['Destination'])) {
147
            $dstName = $state['Destination']['OrganizationDisplayName'];
148
        } else {
149
            $dstName = $state['Destination']['entityid'];
150
        }
151
152
        // Make, populate and layout consent form
153
        $t = new Template($this->config, 'consent:consentform.twig');
154
        $translator = $t->getTranslator();
155
        $t->data['srcMetadata'] = $state['Source'];
156
        $t->data['dstMetadata'] = $state['Destination'];
157
        $t->data['yesTarget'] = Module::getModuleURL('consent/getconsent');
158
        $t->data['yesData'] = ['StateId' => $id];
159
        $t->data['noTarget'] = Module::getModuleURL('consent/noconsent');
160
        $t->data['noData'] = ['StateId' => $id];
161
        $t->data['attributes'] = $attributes;
162
        $t->data['checked'] = $state['consent:checked'];
163
        $t->data['stateId'] = $id;
164
165
        $t->data['srcName'] = htmlspecialchars(is_array($srcName) ? $translator->getPreferredTranslation($srcName) : $srcName);
166
        $t->data['dstName'] = htmlspecialchars(is_array($dstName) ? $translator->getPreferredTranslation($dstName) : $dstName);
167
168
        if (array_key_exists('descr_purpose', $state['Destination'])) {
169
            $t->data['dstDesc'] = $translator->getPreferredTranslation(
170
                Utils\Arrays::arrayize(
171
                    $state['Destination']['descr_purpose'],
172
                    'en'
173
                )
174
            );
175
        }
176
177
        // Fetch privacypolicy
178
        if (
179
            array_key_exists('UIInfo', $state['Destination']) &&
180
            array_key_exists('PrivacyStatementURL', $state['Destination']['UIInfo']) &&
181
            (!empty($state['Destination']['UIInfo']['PrivacyStatementURL']))
182
        ) {
183
            $privacypolicy = reset($state['Destination']['UIInfo']['PrivacyStatementURL']);
184
        } elseif (
185
            array_key_exists('UIInfo', $state['Source']) &&
186
            array_key_exists('PrivacyStatementURL', $state['Source']['UIInfo']) &&
187
            (!empty($state['Source']['UIInfo']['PrivacyStatementURL']))
188
        ) {
189
            $privacypolicy = reset($state['Source']['UIInfo']['PrivacyStatementURL']);
190
        } else {
191
            $privacypolicy = false;
192
        }
193
        if ($privacypolicy !== false) {
194
            $privacypolicy = str_replace(
195
                '%SPENTITYID%',
196
                urlencode($spentityid),
197
                $privacypolicy
198
            );
199
        }
200
        $t->data['sppp'] = $privacypolicy;
201
202
        // Set focus element
203
        switch ($state['consent:focus']) {
204
            case 'yes':
205
                $t->data['autofocus'] = 'yesbutton';
206
                break;
207
            case 'no':
208
                $t->data['autofocus'] = 'nobutton';
209
                break;
210
            case null:
211
            default:
212
                break;
213
        }
214
215
        $t->data['usestorage'] = array_key_exists('consent:store', $state);
216
217
        if (array_key_exists('consent:hiddenAttributes', $state)) {
218
            $t->data['hiddenAttributes'] = $state['consent:hiddenAttributes'];
219
        } else {
220
            $t->data['hiddenAttributes'] = [];
221
        }
222
223
        return $t;
224
    }
225
226
227
    /**
228
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
229
     * @param string $id The StateId
230
     *
231
     * @return \SimpleSAML\XHTML\Template
232
     */
233
    public function noconsent(Request $request, string $id): Template
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

233
    public function noconsent(/** @scrutinizer ignore-unused */ Request $request, string $id): Template

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
234
    {
235
        /** @psalm-var array $state */
236
        $state = Auth\State::loadState($id, 'consent:request');
237
238
        $resumeFrom = Module::getModuleURL(
239
            'consent/getconsent',
240
            ['StateId' => $id]
241
        );
242
243
        $logoutLink = Module::getModuleURL(
244
            'consent/logout',
245
            ['StateId' => $id]
246
        );
247
248
        $aboutService = null;
249
        if (!isset($state['consent:showNoConsentAboutService']) || $state['consent:showNoConsentAboutService']) {
250
            if (isset($state['Destination']['url.about'])) {
251
                $aboutService = $state['Destination']['url.about'];
252
            }
253
        }
254
255
        $statsInfo = [];
256
        if (isset($state['Destination']['entityid'])) {
257
            $statsInfo['spEntityID'] = $state['Destination']['entityid'];
258
        }
259
        Stats::log('consent:reject', $statsInfo);
260
261
        if (array_key_exists('name', $state['Destination'])) {
262
            $dstName = $state['Destination']['name'];
263
        } elseif (array_key_exists('OrganizationDisplayName', $state['Destination'])) {
264
            $dstName = $state['Destination']['OrganizationDisplayName'];
265
        } else {
266
            $dstName = $state['Destination']['entityid'];
267
        }
268
269
        $t = new Template($this->config, 'consent:noconsent.twig');
270
        $translator = $t->getTranslator();
271
        $t->data['dstMetadata'] = $state['Destination'];
272
        $t->data['resumeFrom'] = $resumeFrom;
273
        $t->data['aboutService'] = $aboutService;
274
        $t->data['logoutLink'] = $logoutLink;
275
        $t->data['dstName'] = htmlspecialchars(is_array($dstName) ? $translator->getPreferredTranslation($dstName) : $dstName);
276
        return $t;
277
    }
278
279
280
    /**
281
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
282
     * @param string $id The StateId
283
     *
284
     * @return \SimpleSAML\HTTP\RunnableResponse
285
     */
286
    public function logout(Request $request, string $id): RunnableResponse
287
    {
288
        $state = Auth\State::loadState($id, 'consent:request');
289
290
        $state['Responder'] = ['\SimpleSAML\Module\consent\Logout', 'postLogout'];
291
292
        $idp = IdP::getByState($state);
0 ignored issues
show
Bug introduced by
It seems like $state can also be of type null; however, parameter $state of SimpleSAML\IdP::getByState() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

292
        $idp = IdP::getByState(/** @scrutinizer ignore-type */ $state);
Loading history...
293
        return new RunnableResponse([$idp, 'handleLogoutRequest'], [$state, null]);
294
    }
295
296
297
    /**
298
     * @param \Symfony\Component\HttpFoundation\Request $request The current request.
299
     *
300
     * @return \SimpleSAML\XHTML\Template
301
     */
302
    public function logoutcompleted(Request $request): Template
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

302
    public function logoutcompleted(/** @scrutinizer ignore-unused */ Request $request): Template

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
303
    {
304
        return new Template($this->config, 'consent:logout_completed.twig');
305
    }
306
}
307