Passed
Pull Request — master (#1953)
by Struan
04:40
created

Policies::getPoliciesWithFreeVote()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 8
nc 2
nop 0
dl 0
loc 13
ccs 0
cts 0
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Policies Class
5
 *
6
 * @package TheyWorkForYou
7
 */
8
9
namespace MySociety\TheyWorkForYou;
10
11
/**
12
 * Policies
13
 *
14
 * Class to provide management (selection, sorting etc) of PublicWhip policies.
15
 */
16
17
class Policies {
18
    private $commons_only = [
19
        811,
20
        826,
21
        1053,
22
    ];
23
24
    # policies where votes affected by covid voting restrictions
25
    protected $covid_affected = [1136, 6860];
26
27
    private $db;
28
29
    private $policy_id;
30
    /**
31
     * @var array $policies key-value of policy id to the context description.
32
     * e.g. "363": "introducing <b>foundation hospitals</b>"
33
     */
34
    private array $policies;
35
36
    /**
37
     * @var array $sets - key-value pair of a set slug to an array of policy IDs
38
     * in that set.
39
     * e.g. "foreignpolicy": ["975", "984"]
40
     */
41
    private array $sets;
42
43
    /**
44
     * @var array $set_descs - key-value pairs of a set slug to a description
45
     * of that set.
46
     * e.g. "foreignpolicy": "Foreign Policy"
47
     */
48
    private array $set_descs;
49
50
    /**
51
     * @var array $all_policy_agreements - key-value pair of a policy ID to
52
     * an array of
53
     * agreements links.
54
     * e.g. "1030": [{
55
     *   "division_name": "Approval of SI setting 2050 Net Zero target date",
56
     *   "alignment": "agree",
57
     *   "gid": "2019-06-24b.530.1",
58
     *   "url": "/debates/?id=2019-06-24b.530.1",
59
     *   "house": "commons",
60
     *   "strength": "strong",
61
     *   "date": "2019-06-24"
62
     * }]
63
     */
64
    public array $all_policy_agreements;
65
66
    public function __construct($policy_id = null) {
67
        $this->db = new \ParlDB();
68
69
        if (defined('TESTING') && TESTING == true) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
70
            $policy_data = json_decode(file_get_contents(dirname(__FILE__) . '/../tests/policies.json'), true);
71
        } else {
72
            $policy_data = json_decode(file_get_contents(RAWDATA . '/scrapedjson/policies.json'), true);
0 ignored issues
show
Bug introduced by
The constant MySociety\TheyWorkForYou\RAWDATA was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
73
        }
74
        $this->policies = $policy_data['policies'] ?? [];
75
        $this->set_descs = $policy_data['set_descs'] ?? [];
76
        $this->sets = $policy_data['sets'] ?? [];
77
78
        $this->all_policy_agreements = $policy_data['agreements'] ?? [];
79
80
        if ($policy_id) {
81
            $this->policy_id = $policy_id;
82
            $this->policies = [
83
                $policy_id => $this->policies[$policy_id] ?? '',
84
            ];
85
        }
86
    }
87
88
    public function getCovidAffected() {
89
        return $this->covid_affected;
90
    }
91
92
    public function getPolicies() {
93
        return $this->policies;
94
    }
95
96
    public function getPolicyIDs() {
97
        return array_keys($this->policies);
98
    }
99
100
    public function getSets() {
101
        return $this->sets;
102
    }
103
104
    public function getSetDescriptions() {
105
        return $this->set_descs;
106
    }
107
108
    /**
109
     * Get Array
110
     *
111
     * Return an array of policies.
112
     *
113
     * @return array Array of policies in the form `[ {id} , {text} ]`
114
     */
115
    public function getPoliciesData() {
116
        $out = [];
117
        foreach ($this->policies as $policy_id => $policy_text) {
118
            $out[] = [
119
                'id' => $policy_id,
120
                'text' => $policy_text,
121
                'commons_only' => in_array($policy_id, $this->commons_only),
122
            ];
123
        }
124
        return $out;
125
    }
126
127
    /**
128
     * Shuffle
129
     *
130
     * Shuffles the list of policy positions.
131
     *
132
     * @return self
133
     */
134
135
    public function shuffle() {
136
        $random = Utility\Shuffle::keyValue($this->policies);
137
138
        $new_policies = new self();
139
        $new_policies->policies = $random;
140
141
        return $new_policies;
142
    }
143
144
    /**
145
     * Limit To Set
146
     *
147
     * Limit the policies to those in a set and order accordingly
148
     *
149
     * @param string $set The name of the set to use.
150
     *
151
     * @return self
152
     */
153
    public function limitToSet($set) {
154
155
        // Sanity check the set exists
156
        if (isset($this->sets[$set])) {
157
            $out = [];
158
            // Reassemble the new policies list based on the set.
159
            foreach ($this->sets[$set] as $set_policy) {
160
                if (isset($this->policies[$set_policy])) {
161
                    $out[$set_policy] = $this->policies[$set_policy];
162
                } else {
163
                    // if we've limited the policies to a single one then we only
164
                    // want to complain here if we're looking for that policy and
165
                    // it does not exist. Otherwise, if the single policy isn't in
166
                    // the set we want to return an empty set
167
                    if (!isset($this->policy_id) || $set_policy == $this->policy_id) {
168
                        throw new \Exception('Policy ' . $set_policy . ' in set "' . $set . '" does not exist.');
169
                    }
170
                }
171
            }
172
173
            $new_policies = new self($this->policy_id);
174
            $new_policies->policies = $out;
175
176
            return $new_policies->shuffle();
177
178
        } else {
179
            throw new \Exception('Policy set "' . $set . '" does not exist.');
180
        }
181
    }
182
183
    public function limitToArray($policies) {
184
        $out = [];
185
        // Reassemble the new policies list based on the set.
186
        foreach ($policies as $policy) {
187
            if (isset($this->policies[$policy])) {
188
                $out[$policy] = $this->policies[$policy];
189
            }
190
        }
191
192
        $new_policies = new self();
193
        $new_policies->policies = $out;
194
195
        return $new_policies;
196
    }
197
198
    public function getPoliciesWithFreeVote() {
199
        $q = $this->db->query(
200
            "SELECT policy_id
201
            FROM policies WHERE contains_free_vote = 1",
202
        );
203
204
        error_log(print_r($q, 1));
0 ignored issues
show
Bug introduced by
It seems like print_r($q, 1) can also be of type true; however, parameter $message of error_log() does only seem to accept string, 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

204
        error_log(/** @scrutinizer ignore-type */ print_r($q, 1));
Loading history...
205
        $ids = [];
206
        foreach ($q as $row) {
207
            $ids[] = $row['policy_id'];
208
        }
209
210
        return $ids;
211
    }
212
213
    public function getPolicyDetails($policyID) {
214
        $q = $this->db->query(
215
            "SELECT policy_id, title, description, contains_free_vote, image, image_attrib, image_license, image_license_url, image_source
216
            FROM policies WHERE policy_id = :policy_id",
217
            [':policy_id' => $policyID]
218
        )->first();
219
220
        $props = [
221
            'policy_id' => $q['policy_id'],
222
            'title' => $q['title'],
223
            // remove full stops from the end of descriptions. Some of them have them and
224
            // some of them don't so we enforce consistency here
225
            'description' => preg_replace('/\. *$/', '', $q['description']),
226
            'contains_free_vote' => $q['contains_free_vote'],
227
            'image' => '/images/header-debates-uk.jpg', // TODO: get a better default image
228
            'image_license' => '',
229
            'image_attribution' => '',
230
            'image_source' => '',
231
            'image_license_url' => '',
232
        ];
233
234
        $image = $q['image'];
235
236
        if ($image && file_exists(BASEDIR . '/' . $image)) {
237
            $props['image'] = $image;
238
            $props['image_license'] = $q['image_license'];
239
            $props['image_attribution'] = $q['image_attrib'];
240
            $props['image_source'] = $q['image_source'];
241
            $props['image_license_url'] = $q['image_license_url'];
242
        }
243
244
        return $props;
245
    }
246
247
}
248