Passed
Push — master ( 05853c...117d80 )
by Tõnis
04:48
created

Respondent::init()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

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

202
        if (in_array($number, /** @scrutinizer ignore-type */ $checkItems)) {
Loading history...
203
            $this->addError($attribute, Yii::t('app', 'Duplicate number in alternative phone numbers'));
204
        }
205
    }
206
207
208
    /**
209
     * @param string $attribute
210
     * @param string $number
211
     * @return null
212
     */
213
    private function validateSameAsMainNumber($attribute, $number)
214
    {
215
        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...
216
            return null;
217
        }
218
219
        if ($number === $this->phone_number) {
220
            $this->addError($attribute,
221
                Yii::t('app',
222
                    'Invalid phone number "{0}"', [$number]
223
                ) . ' ' . Yii::t('app', 'Reason: {0}', [Yii::t('app', $attribute . ' duplicates main phone number')])
224
            );
225
        }
226
        return null;
227
    }
228
229
230
    /**
231
     * @param string $attribute
232
     * @param string $phone_number Phone number to check duplicates for
233
     */
234
    private function validatePhoneSurveyDuplicate($attribute, $phone_number)
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([static::primaryKey()[0] => 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
     */
384
    public function setBulkRegistered($tokens, $field = 'time_collector_registered')
385
    {
386
        $query = new yii\db\Query();
387
        $dateHelper = new DateHelper();
388
        $query->createCommand()
389
            ->update(self::tableName(),
390
                [$field=> $dateHelper->getDatetime6()],
391
                ['in','token',$tokens]
392
            )->execute();
393
    }
394
395
    /**
396
     * @return array
397
     */
398
    public function getParticipantData(){
399
        return [];
400
    }
401
402
403
}