Passed
Push — master ( 39e7ce...573e3b )
by Tõnis
03:33
created

Respondent::findByToken()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 9
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
namespace andmemasin\surveybasemodels;
4
5
use andmemasin\myabstract\MyActiveRecord;
6
use PascalDeVink\ShortUuid\ShortUuid;
7
use Ramsey\Uuid\Uuid;
8
use yii;
9
use andmemasin\helpers\DateHelper;
10
11
/**
12
 * This is the model class for a generic Respondent.
13
 *
14
 * @property int $respondent_id
15
 * @property int $survey_id
16
 * @property string $token
17
 * @property string $email_address
18
 * @property string $alternative_email_addresses Inserted as CSV, stored as JSON
19
 * @property string $phone_number
20
 * @property string $alternative_phone_numbers Inserted as CSV, stored as JSON
21
 * @property string $time_collector_registered
22
 *
23
 * @property boolean $isRejected
24
 * @property string $shortToken If the token is uuid, then short-uuid will be returned
25
 * @property Survey $survey
26
 */
27
class Respondent extends MyActiveRecord
28
{
29
    const MAX_ALTERNATIVE_CONTACTS = 20;
30
31
    /** @var bool $checkDSNForEmails whether email validation also used DSN records to check if domain exists */
32
    public static $checkDSNForEmails = false;
33
34
    /**
35
     * @var array $surveyIdentifyingColumns names of the columns that identify a respondent as unique inside a survey
36
     */
37
    public static $surveyIdentifyingColumns = ['phone_number', 'email_address'];
38
39
    public function init()
40
    {
41
        parent::init();
42
    }
43
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function rules()
49
    {
50
        return array_merge([
51
            [['survey_id', 'token'], 'required'],
52
            [['survey_id'], 'integer'],
53
            [['email_address'], 'validateEmail'],
54
            [['email_address', 'phone_number'], 'filter', 'filter' => 'trim'],
55
            [['email_address', 'phone_number'], 'filter', 'filter' => 'strtolower'],
56
            [['alternative_email_addresses'], 'string'],
57
            [['alternative_email_addresses'], 'validateMultipleEmails'],
58
            [['phone_number'], 'string', 'length' => [4, 32]],
59
            [['phone_number'], 'validatePhoneNumber'],
60
            [['time_collector_registered'], 'string', 'max' => 32],
61
            [['alternative_phone_numbers'], 'string'],
62
            [['alternative_phone_numbers'], 'validateMultiplePhoneNumbers'],
63
            [['token'], 'unique'],
64
        ], parent::rules());
65
    }
66
67
68
    /**
69
     * @param string $attribute
70
     * @param string $address
71
     * @return bool
72
     */
73
    public function validateEmail($attribute, $address)
74
    {
75
        if (empty($address)) {
76
            $address = $this->email_address;
77
        }
78
        if (!empty($address)) {
79
            if ($this->validateEmailFormat($attribute, $address)
80
                && !$this->isSameAsMainAddress($attribute, $address)
81
                && !$this->isEmailSurveyDuplicate($attribute, $address)) {
82
                return true;
83
            }
84
        }
85
86
        return false;
87
    }
88
89
    /**
90
     * @param string $attribute
91
     * @param string $address
92
     * @return bool
93
     */
94
    private function validateEmailFormat($attribute, $address)
95
    {
96
        $validator = new yii\validators\EmailValidator();
97
        $validator->checkDNS = static::$checkDSNForEmails;
98
        if (!$validator->validate($address)) {
99
            $this->addError($attribute,
100
                Yii::t('app',
101
                    'Invalid email address "{0}"', [$address]
102
                ) . ' ' . Yii::t('app', 'Reason: {0}', [Yii::t('app', 'Invalid email format')])
103
            );
104
            return false;
105
        }
106
        return true;
107
    }
108
109
    /**
110
     * @param string $address
111
     * @return bool
112
     */
113
    private function isSameAsMainAddress($attribute, $address)
114
    {
115
        if (empty($address) | $attribute === "email_address") {
0 ignored issues
show
Bug introduced by
Are you sure you want to use the bitwise | or did you mean ||?
Loading history...
116
            return false;
117
        }
118
        if ($address === $this->email_address) {
119
            $this->addError($attribute,
120
                Yii::t('app',
121
                    'Email address same as main address "{0}"', [$address]
122
                ) . ' ' . Yii::t('app', 'Reason: {0}', [Yii::t('app', $attribute . ' duplicates main address')])
123
            );
124
            return true;
125
        }
126
        return false;
127
    }
128
129
130
    public function validateMultipleEmails($attribute)
131
    {
132
        $cleanAddresses = [];
133
        $addresses = yii\helpers\Json::decode($this->alternative_email_addresses);
134
        if (!empty($addresses)) {
135
            $i = 0;
136
            foreach ($addresses as $key => $address) {
137
                if (!empty($address)) {
138
                    $i++;
139
                    // check the alternative numbers of that model for duplicates
140
                    $checkItems = $addresses;
141
                    unset($checkItems[$key]);
142
                    if (in_array($address, $checkItems)) {
143
                        $this->addError($attribute, Yii::t('app', 'Duplicate email in alternative email addresses'));
144
                    }
145
146
                    if ($i > static::MAX_ALTERNATIVE_CONTACTS) {
147
                        $this->addError($attribute, Yii::t('app', 'Maximum alternative addresses limit ({0}) reached for {1}', [static::MAX_ALTERNATIVE_CONTACTS, $this->email_address]));
148
                    }
149
                    $address = strtolower(trim($address));
150
                    if ($this->validateEmail($attribute, $address)) {
151
                        $cleanAddresses[] = $address;
152
                    }
153
                }
154
            }
155
        }
156
        $this->alternative_email_addresses = yii\helpers\Json::encode($cleanAddresses);
157
    }
158
159
160
    public function validatePhoneNumber($attribute, $phone_number)
161
    {
162
        if (empty($phone_number)) {
163
            $phone_number = $this->phone_number;
164
        }
165
        if (!empty($phone_number)) {
166
            $this->validateSameAsMainNumber($attribute, $phone_number);
167
            // FIXME
168
            $isValidFormat = true;
0 ignored issues
show
Unused Code introduced by
The assignment to $isValidFormat is dead and can be removed.
Loading history...
169
            $this->validatePhoneSurveyDuplicate($attribute, $phone_number);
170
171
        }
172
173
    }
174
175
176
    public function validateMultiplePhoneNumbers($attribute)
177
    {
178
        $cleanItems = [];
179
        $items = yii\helpers\Json::decode($this->alternative_phone_numbers);
180
        if (!empty($items)) {
181
            $i = 0;
182
            foreach ($items as $key => $item) {
183
                $i++;
184
                $item = strtolower(trim($item));
185
                $this->validateAlternativePhoneNumberInternalDuplicates($attribute, $item, $key);
186
187
                if ($i > static::MAX_ALTERNATIVE_CONTACTS) {
188
                    $this->addError($attribute, Yii::t('app', 'Maximum alternative phone numbers limit ({0}) reached for {1}', [static::MAX_ALTERNATIVE_CONTACTS, $this->phone_number]));
189
                }
190
               $this->validatePhoneNumber($attribute, $item);
191
            }
192
        }
193
        $this->alternative_phone_numbers = yii\helpers\Json::encode($cleanItems);
194
    }
195
196
    private function validateAlternativePhoneNumberInternalDuplicates($attribute, $number, $key)
197
    {
198
        $items = yii\helpers\Json::decode($this->alternative_phone_numbers);
199
        $checkItems = $items;
200
        unset($checkItems[$key]);
201
        if (in_array($number, $checkItems)) {
0 ignored issues
show
Bug introduced by
It seems like $checkItems can also be of type null; however, parameter $haystack of in_array() 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

201
        if (in_array($number, /** @scrutinizer ignore-type */ $checkItems)) {
Loading history...
202
            $this->addError($attribute, Yii::t('app', 'Duplicate number in alternative phone numbers'));
203
        }
204
    }
205
206
207
    /**
208
     * @param string $attribute
209
     * @param string $number
210
     * @return null
211
     */
212
    private function validateSameAsMainNumber($attribute, $number)
213
    {
214
        if (empty($number) | $attribute === 'phone_number') {
0 ignored issues
show
Bug introduced by
Are you sure you want to use the bitwise | or did you mean ||?
Loading history...
215
            return null;
216
        }
217
218
        if ($number === $this->phone_number) {
219
            $this->addError($attribute,
220
                Yii::t('app',
221
                    'Invalid phone number "{0}"', [$number]
222
                ) . ' ' . Yii::t('app', 'Reason: {0}', [Yii::t('app', $attribute . ' duplicates main phone number')])
223
            );
224
        }
225
        return null;
226
    }
227
228
229
    /**
230
     * @param string $attribute
231
     * @param string $phone_number Phone number to check duplicates for
232
     */
233
    protected function validatePhoneSurveyDuplicate($attribute, $phone_number)
234
    {
235
236
        $query = static::find();
237
        // check only this survey
238
        $query->andWhere(['survey_id' => $this->survey_id]);
239
240
        if ($this->respondent_id) {
241
            // not itself
242
            $query->andWhere(['!=', 'respondent_id', $this->respondent_id]);
243
        }
244
245
        $condition = ['or',
246
            '`phone_number`=:phone_number',
247
            '`alternative_phone_numbers` LIKE :phone_number2',
248
        ];
249
250
        $query->andWhere($condition, [':phone_number' => $phone_number, ':phone_number2' => '%\"' . $phone_number . '\"%']);
251
252
        if ($query->count() > 0) {
253
            $this->addError($attribute,
254
                Yii::t('app',
255
                    'Invalid phone number "{0}"', [$phone_number]
256
                ) . ' ' . Yii::t('app', 'Reason: {0}', [Yii::t('app', 'Duplicate phone number')])
257
            );
258
        }
259
    }
260
261
262
    /**
263
     * @param string $email_address Email address to check duplicates for
264
     * @return bool
265
     */
266
    public function isEmailSurveyDuplicate($attribute, $email_address)
267
    {
268
        $query = static::find();
269
        // check only this survey
270
        $query->andWhere(['survey_id' => $this->survey_id]);
271
272
        // not itself
273
        if (!empty($this->respondent_id)) {
274
            // not itself
275
            $query->andWhere(['!=', 'respondent_id', $this->respondent_id]);
276
        }
277
278
        $email_condition = ['or',
279
            '`email_address`=:email_address',
280
            '`alternative_email_addresses` LIKE :email_address2',
281
        ];
282
283
        $query->andWhere($email_condition, [':email_address' => $email_address, ':email_address2' => '%\"' . $email_address . '\"%']);
284
285
        if ($query->count() > 0) {
286
            $this->addError($attribute,
287
                Yii::t('app',
288
                    'Invalid email address "{0}"', [$email_address]
289
                ) . ' ' . Yii::t('app', 'Reason: {0}', [Yii::t('app', 'Duplicates some other address')])
290
            );
291
            return true;
292
        }
293
294
295
        return false;
296
    }
297
298
    /**
299
     * {@inheritdoc}
300
     */
301
    public function attributeLabels()
302
    {
303
        return [
304
            'token' => Yii::t('app', 'Unique Token'),
305
        ];
306
    }
307
308
    /**
309
     * @param string $token Respondents token
310
     * @return static
311
     */
312
    public static function findByToken($token = null)
313
    {
314
        if ($token) {
315
            $models = self::findByTokens([$token]);
316
            if (!empty($models)) {
317
                return $models[0];
318
            }
319
        }
320
        return null;
321
    }
322
323
    /**
324
     * @param string[] $tokens Respondents tokens
325
     * @return static[]
326
     */
327
    public static function findByTokens($tokens)
328
    {
329
        /** @var static[] $model */
330
        $models = static::find()
331
            ->andWhere(['in', 'token', $tokens])
332
            ->all();
333
        return $models;
334
    }
335
336
    /**
337
     * Check whether respondent has rejected this specific survey or has a hard bounce on e_mail address
338
     * @return bool
339
     */
340
    public function getIsRejected()
341
    {
342
        if (Rejection::rejectedByCode($this->token)) {
343
            return true;
344
        }
345
346
        if (Rejection::bouncedByEmailAddress($this->email_address)) {
347
            return true;
348
        }
349
350
        return false;
351
    }
352
353
    /**
354
     * Get the last respondent based on Email-address
355
     * @param string $email_address
356
     * @return static
357
     */
358
    public static function getLatestByEmail($email_address)
359
    {
360
        /** @var static $model */
361
        $model = static::find()
362
            ->andWhere(['email_address' => $email_address])
363
            ->orderBy([(new static)->primaryKeySingle() => SORT_DESC])
364
            ->one();
365
        return $model;
366
    }
367
368
    /**
369
     * @return string
370
     */
371
    public function getShortToken()
372
    {
373
        if (Uuid::isValid($this->token)) {
374
            $uuid = Uuid::fromString($this->token);
375
            $shotUuid = new ShortUuid();
376
            return $shotUuid->encode($uuid);
377
        }
378
        return $this->token;
379
    }
380
381
    /**
382
     * TODO move to some factory
383
     * @return integer
384
     */
385
    public function setBulkRegistered($tokens, $field = 'time_collector_registered')
386
    {
387
        $query = new yii\db\Query();
388
        $dateHelper = new DateHelper();
389
        return $query->createCommand()
390
            ->update(self::tableName(),
391
                [$field=> $dateHelper->getDatetime6()],
392
                ['in','token',$tokens]
393
            )->execute();
394
    }
395
396
    /**
397
     * @return array
398
     */
399
    public function getParticipantData(){
400
        return [];
401
    }
402
403
404
}