Failed Conditions
Branch master (3ce7e2)
by Nick
14:43
created

pick_multiple()   F

Complexity

Conditions 16
Paths 1446

Size

Total Lines 84
Code Lines 60

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
eloc 60
c 0
b 0
f 0
nc 1446
nop 4
dl 0
loc 84
rs 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
1 ignored issue
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 49 and the first side effect is on line 5.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
# For looking up a postcode and redirecting or displaying appropriately
4
5
include_once '../../includes/easyparliament/init.php';
6
include_once INCLUDESPATH . 'easyparliament/member.php';
1 ignored issue
show
Bug introduced by
The constant INCLUDESPATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
7
8
$errors = array();
9
10
$pc = get_http_var('pc');
11
if (!$pc) {
12
    postcode_error('Please supply a postcode!');
13
}
14
15
$pc = preg_replace('#[^a-z0-9]#i', '', $pc);
16
if (!validate_postcode($pc)) {
17
    twfy_debug ('MP', "Can't display an MP because the submitted postcode wasn't of a valid form.");
18
    postcode_error("Sorry, " . _htmlentities($pc) . " isn't a valid postcode");
19
}
20
21
$constituencies = MySociety\TheyWorkForYou\Utility\Postcode::postcodeToConstituencies($pc);
22
if ($constituencies == 'CONNECTION_TIMED_OUT') {
23
    postcode_error("Sorry, we couldn't check your postcode right now, as our postcode lookup server is under quite a lot of load.");
24
} elseif (!$constituencies) {
25
    postcode_error("Sorry, " . _htmlentities($pc) . " isn't a known postcode");
26
}
27
28
$out = ''; $sidebars = array();
29
if (isset($constituencies['SPE']) || isset($constituencies['SPC'])) {
30
    $MEMBER = fetch_mp($pc, $constituencies);
31
    list($out, $sidebars) = pick_multiple($pc, $constituencies, 'SPE', 'MSP');
32
} elseif (isset($constituencies['NIE'])) {
33
    $MEMBER = fetch_mp($pc, $constituencies);
34
    list($out, $sidebars) = pick_multiple($pc, $constituencies, 'NIE', 'MLA');
35
} else {
36
    # Just have an MP, redirect instantly to the canonical page
37
    $MEMBER = fetch_mp($pc, $constituencies, 1);
38
    member_redirect($MEMBER);
39
}
40
41
$PAGE->page_start();
42
$PAGE->stripe_start();
43
echo $out;
44
$PAGE->stripe_end($sidebars);
45
$PAGE->page_end();
46
47
# ---
48
49
function postcode_error($error) {
50
    global $PAGE;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
51
    $PAGE->page_start();
52
    $PAGE->stripe_start();
53
    $PAGE->error_message($error);
54
    $PAGE->postcode_form();
55
    $PAGE->stripe_end();
56
    $PAGE->page_end();
57
    exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
58
}
59
60
function fetch_mp($pc, $constituencies, $house=null) {
61
    global $THEUSER;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
62
    $args = array('constituency' => $constituencies['WMC']);
63
    if ($house) {
64
        $args['house'] = $house;
65
    }
66
    try {
67
        $MEMBER = new MEMBER($args);
68
    } catch (MySociety\TheyWorkForYou\MemberException $e){
69
        postcode_error($e->getMessage());
70
    }
71
    if ($MEMBER->person_id()) {
72
        $THEUSER->set_postcode_cookie($pc);
73
    }
74
    return $MEMBER;
75
}
76
77
function pick_multiple($pc, $areas, $area_type, $rep_type) {
0 ignored issues
show
Unused Code introduced by
The parameter $pc 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

77
function pick_multiple(/** @scrutinizer ignore-unused */ $pc, $areas, $area_type, $rep_type) {

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...
78
    global $PAGE;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
79
    $db = new ParlDB;
80
81
    $q = $db->query("SELECT member.person_id, given_name, family_name, constituency, left_house
82
        FROM member, person_names pn
83
        WHERE constituency = :constituency
84
            AND member.person_id = pn.person_id AND pn.type = 'name'
85
            AND pn.end_date = (SELECT MAX(end_date) from person_names where person_names.person_id = member.person_id)
86
        AND house = 1 ORDER BY left_house DESC LIMIT 1", array(
87
            ':constituency' => MySociety\TheyWorkForYou\Utility\Constituencies::normaliseConstituencyName($areas['WMC'])
88
            ));
89
    $mp = array();
90
    if ($q->rows()) {
91
        $mp = $q->row(0);
92
        if ($mp['left_house'] != '9999-12-31') $mp['former'] = true;
93
    }
94
95
    $a = array_values($areas);
96
97
    $query_base = "SELECT member.person_id, given_name, family_name, constituency, house
98
        FROM member, person_names pn
99
        WHERE constituency IN ('" . join("','", $a) . "')
100
            AND member.person_id = pn.person_id AND pn.type = 'name'
101
            AND pn.end_date = (SELECT MAX(end_date) from person_names where person_names.person_id = member.person_id)";
102
    $q = $db->query($query_base . " AND left_reason = 'still_in_office' AND house in (3,4)");
103
    $current = true;
104
    if (!$q->rows() && ($dissolution = MySociety\TheyWorkForYou\Dissolution::db())) {
105
        $current = false;
106
        $q = $db->query($query_base . " AND $dissolution[query]",
107
            $dissolution['params']);
108
    }
109
110
    $mcon = array(); $mreg = array();
111
    for ($i=0; $i<$q->rows(); $i++) {
112
        $house = $q->field($i, 'house');
113
        $cons = $q->field($i, 'constituency');
114
        if ($house==3) {
115
            $mreg[] = $q->row($i);
116
        } elseif ($house==4) {
117
            if ($cons == $areas['SPC']) {
118
                $mcon = $q->row($i);
119
            } elseif ($cons == $areas['SPE']) {
120
                $mreg[] = $q->row($i);
121
            }
122
        } else {
123
            $PAGE->error_message('Odd result returned, please let us know!');
124
            return;
125
        }
126
    }
127
128
    $out = '';
129
    $out .= '<p>That postcode has multiple results, please pick who you are interested in:</p>';
130
    $out .= '<ul><li>Your ';
131
    if (isset($mp['former'])) $out .= 'former ';
132
    $out .= '<strong>MP</strong> (Member of Parliament) is <a href="/mp/?p=' . $mp['person_id'] . '">';
133
    $out .= $mp['given_name'] . ' ' . $mp['family_name'] . '</a>, ' . $mp['constituency'] . '</li>';
134
    if ($mcon) {
0 ignored issues
show
introduced by
$mcon is an empty array, thus is always false.
Loading history...
Bug Best Practice introduced by
The expression $mcon of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
135
        $out .= '<li>Your <strong>constituency MSP</strong> (Member of the Scottish Parliament) ';
136
        $out .= $current ? 'is' : 'was';
137
        $out .= ' <a href="/msp/?p=' . $mcon['person_id'] . '">';
138
        $out .= $mcon['given_name'] . ' ' . $mcon['family_name'] . '</a>, ' . $mcon['constituency'] . '</li>';
139
    }
140
    $out .= '<li>Your <strong>' . $areas[$area_type] . ' ' . $rep_type . 's</strong> ';
141
    if ($rep_type=='MLA') $out .= '(Members of the Legislative Assembly)';
142
    $out .= ' ' . ($current ? 'are' : 'were') . ':';
143
    $out .= '<ul>';
144
    foreach ($mreg as $reg) {
145
        $out .= '<li><a href="/' . strtolower($rep_type) . '/?p=' . $reg['person_id'] . '">';
146
        $out .= $reg['given_name'] . ' ' . $reg['family_name'];
147
        $out .= '</a>';
148
    }
149
    $out .= '</ul></ul>';
150
151
    $MPSURL = new \MySociety\TheyWorkForYou\Url('mps');
152
    $REGURL = new \MySociety\TheyWorkForYou\Url(strtolower($rep_type) . 's');
153
    $sidebar = array(array(
154
        'type' => 'html',
155
        'content' => '<div class="block"><h4>Browse people</h4>
156
            <ul><li><a href="' . $MPSURL->generate() . '">Browse all MPs</a></li>
157
            <li><a href="' . $REGURL->generate() . '">Browse all ' . $rep_type . 's</a></li>
158
            </ul></div>'
159
    ));
160
    return array($out, $sidebar);
161
}
162
163
function member_redirect(&$MEMBER) {
164
    if ($MEMBER->valid) {
165
        $url = $MEMBER->url();
166
        header("Location: $url");
167
        exit;
168
    }
169
}
170