Passed
Push — 1.0 ( 929063...d6f2a0 )
by Morven
03:15
created

Contact::getDefaultAddress()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace SilverCommerce\ContactAdmin\Model;
4
5
use SilverStripe\ORM\DataObject;
6
use SilverStripe\Security\Member;
7
use SilverStripe\Security\Security;
8
use SilverStripe\TagField\TagField;
9
use SilverStripe\Forms\DropdownField;
10
use SilverStripe\Security\Permission;
11
use SilverStripe\Forms\RequiredFields;
12
use SilverStripe\Forms\GridField\GridField;
13
use SilverStripe\Security\PermissionProvider;
14
use SilverCommerce\ContactAdmin\Model\ContactTag;
15
use SilverStripe\ORM\FieldType\DBHTMLText as HTMLText;
16
use SilverStripe\Forms\GridField\GridFieldConfig_RelationEditor;
17
use NathanCox\HasOneAutocompleteField\Forms\HasOneAutocompleteField;
18
19
/**
20
 * Details on a particular contact
21
 * 
22
 * @author ilateral
23
 * @package Contacts
24
 */
25
class Contact extends DataObject implements PermissionProvider
26
{
27
    private static $table_name = 'Contact';
28
29
    /**
30
     * String used to seperate tags, lists, etc
31
     * when rendering a summary.
32
     *
33
     * @var string
34
     */
35
    private static $list_seperator = ", ";
36
37
    private static $db = [
38
        "FirstName" => "Varchar(255)",
39
        "Surname" => "Varchar(255)",
40
        "Company" => "Varchar(255)",
41
        "Phone" => "Varchar(15)",
42
        "Mobile" => "Varchar(15)",
43
        "Email" => "Varchar(255)",
44
        "Source" => "Text"
45
    ];
46
47
    private static $has_one = [
48
        "Member" => Member::class
49
    ];
50
51
    private static $has_many = [
52
        "Locations" => ContactLocation::class,
53
        "Notes" => ContactNote::class
54
    ];
55
    
56
    private static $many_many = [
57
        'Tags' => ContactTag::class
58
    ];
59
60
    private static $belongs_many_many = [
61
        'Lists' => ContactList::class
62
    ];
63
    
64
    private static $casting = [
65
        'TagsList' => 'Varchar',
66
        'ListsList' => 'Varchar',
67
        'FlaggedNice' => 'Boolean',
68
        'FullName' => 'Varchar',
69
        'Name' => 'Varchar',
70
        "DefaultAddress" => "Text"
71
    ];
72
    
73
    private static $summary_fields = [
74
        "FlaggedNice" =>"Flagged",
75
        "FirstName" => "FirstName",
76
        "Surname" => "Surname",
77
        "Email" => "Email",
78
        "DefaultAddress" => "Default Address",
79
        "TagsList" => "Tags",
80
        "ListsList" => "Lists"
81
    ];
82
83
    private static $default_sort = [
84
        "FirstName" => "ASC",
85
        "Surname" => "ASC"
86
    ];
87
    
88
    private static $searchable_fields = [
89
        "FirstName",
90
        "Surname",
91
        "Email",
92
        "Locations.Address1",
93
        "Locations.Address2",
94
        "Locations.City",
95
        "Locations.Country",
96
        "Locations.PostCode",
97
        "Tags.Title",
98
        "Lists.Title"
99
    ];
100
101
    /**
102
     * Fields that can be synced with associated member
103
     * 
104
     * @var array
105
     */
106
    private static $sync_fields = [
107
        "FirstName",
108
        "Surname",
109
        "Company",
110
        "Phone",
111
        "Mobile",
112
        "Email"
113
    ];
114
    
115
    public function getTitle()
116
    {
117
        $parts = [];
118
119
        if (!empty($this->FirstName)) {
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __get, consider adding a @property annotation.
Loading history...
120
            $parts[] = $this->FirstName;
121
        }
122
123
        if (!empty($this->Surname)) {
0 ignored issues
show
Bug Best Practice introduced by
The property Surname does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __get, consider adding a @property annotation.
Loading history...
124
            $parts[] = $this->Surname;
125
        }
126
127
        if (!empty($this->Email)) {
0 ignored issues
show
Bug Best Practice introduced by
The property Email does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __get, consider adding a @property annotation.
Loading history...
128
            $parts[] = "($this->Email)";
129
        }
130
131
        $title = implode(" ", $parts);
132
133
        $this->extend("updateTitle", $title);
134
        
135
		return $title;
136
	}
137
138
    public function getFullName() 
139
    {
140
        $parts = [];
141
142
        if (!empty($this->FirstName)) {
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __get, consider adding a @property annotation.
Loading history...
143
            $parts[] = $this->FirstName;
144
        }
145
146
		if (!empty($this->Surname)) {
0 ignored issues
show
Bug Best Practice introduced by
The property Surname does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __get, consider adding a @property annotation.
Loading history...
147
            $parts[] = $this->Surname;
148
        }
149
150
        $name = implode(" ", $parts);
151
        
152
        $this->extend("updateFullName", $name);
153
154
        return $name;
155
	}
156
    
157
    public function getFlaggedNice()
158
    {
159
        $obj = HTMLText::create();
160
        $obj->setValue(($this->Flagged)? '<span class="red">&#10033;</span>' : '');
0 ignored issues
show
Bug Best Practice introduced by
The property Flagged does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __get, consider adding a @property annotation.
Loading history...
161
162
        $this->extend("updateFlaggedNice", $obj);
163
       
164
        return $obj;
165
    }
166
167
    /**
168
     * Find from our locations one marked as default (of if not the
169
     * first in the list).
170
     *
171
     * @return ContactLocation
172
     */
173
    public function DefaultLocation()
174
    {
175
        $location = $this
176
            ->Locations()
0 ignored issues
show
Bug introduced by
The method Locations() does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

176
            ->/** @scrutinizer ignore-call */ Locations()
Loading history...
177
            ->sort("Default", "DESC")
178
            ->first();
179
        
180
        $this->extend("updateDefaultLocation", $location);
181
182
        return $location;
183
    }
184
185
    /**
186
     * Find from our locations one marked as default (of if not the
187
     * first in the list).
188
     *
189
     * @return string
190
     */
191
    public function getDefaultAddress()
192
    {
193
        $location = $this->DefaultLocation();
194
195
        if ($location) {
0 ignored issues
show
introduced by
$location is of type SilverCommerce\ContactAdmin\Model\ContactLocation, thus it always evaluated to true.
Loading history...
196
            return $location->Address;
0 ignored issues
show
Bug Best Practice introduced by
The property Address does not exist on SilverCommerce\ContactAdmin\Model\ContactLocation. Since you implemented __get, consider adding a @property annotation.
Loading history...
197
        } else {
198
            return "";
199
        }
200
    }
201
202
	/**
203
	 * Get the complete name of the member
204
	 *
205
	 * @return string Returns the first- and surname of the member.
206
	 */
207
	public function getName() 
208
    {
209
        $name = ($this->Surname) ? trim($this->FirstName . ' ' . $this->Surname) : $this->FirstName;
0 ignored issues
show
Bug Best Practice introduced by
The property FirstName does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __get, consider adding a @property annotation.
Loading history...
Bug Best Practice introduced by
The property Surname does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __get, consider adding a @property annotation.
Loading history...
210
        
211
        $this->extend("updateName", $name);
212
213
        return $name;
214
	}
215
    
216
    /**
217
     * Generate as string of tag titles seperated by a comma
218
     *
219
     * @return string
220
     */
221
    public function getTagsList()
222
    {
223
        $return = "";
0 ignored issues
show
Unused Code introduced by
The assignment to $return is dead and can be removed.
Loading history...
224
        $tags = $this->Tags()->column("Title");
0 ignored issues
show
Bug introduced by
The method Tags() does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

224
        $tags = $this->/** @scrutinizer ignore-call */ Tags()->column("Title");
Loading history...
225
        
226
        $this->extend("updateTagsList", $tags);
227
        
228
        return implode(
229
            $this->config()->list_seperator,
230
            $tags
231
        );
232
    }
233
    
234
    /**
235
     * Generate as string of list titles seperated by a comma
236
     *
237
     * @return string
238
     */
239
    public function getListsList()
240
    {
241
        $return = "";
0 ignored issues
show
Unused Code introduced by
The assignment to $return is dead and can be removed.
Loading history...
242
        $list = $this->Lists()->column("Title");
0 ignored issues
show
Bug introduced by
The method Lists() does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

242
        $list = $this->/** @scrutinizer ignore-call */ Lists()->column("Title");
Loading history...
243
244
        $this->extend("updateListsList", $tags);
245
246
        return implode(
247
            $this->config()->list_seperator,
248
            $list
249
        );
250
    }
251
    
252
    public function getFlagged()
253
    {
254
        $flagged = false;
255
        
256
        foreach ($this->Notes() as $note) {
0 ignored issues
show
Bug introduced by
The method Notes() does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

256
        foreach ($this->/** @scrutinizer ignore-call */ Notes() as $note) {
Loading history...
257
            if ($note->Flag) {
258
                $flagged = true;
259
            }
260
        }
261
262
        $this->extend("updateFlagged", $flagged);
263
264
        return $flagged;
265
    }
266
    
267
    /**
268
     * Update an associated member with the data from this contact
269
     * 
270
     * @return void
271
     */
272
    public function syncToMember()
273
    {
274
        $member = $this->Member();
0 ignored issues
show
Bug introduced by
The method Member() does not exist on SilverCommerce\ContactAdmin\Model\Contact. Since you implemented __call, consider adding a @method annotation. ( Ignorable by Annotation )

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

274
        /** @scrutinizer ignore-call */ 
275
        $member = $this->Member();
Loading history...
275
        $sync = $this->config()->sync_fields;
276
        $write = false;
277
278
        if (!$member->exists()) {
279
            return;
280
        }
281
282
        foreach ($this->getChangedFields() as $field => $change) {
283
            // If this field is a field to sync, and it is different
284
            // then update member
285
            if (in_array($field, $sync) && $member->$field != $this->$field) {
286
                $member->$field = $this->$field;
287
                $write = true;
288
            }
289
        }
290
291
        if ($write) {
292
            $member->write();
293
        }
294
    }
295
296
    public function getCMSFields()
297
    {
298
        $fields = parent::getCMSFields();
299
        
300
        $fields->removeByName("Tags");
301
        $fields->removeByName("Notes");
302
        
303
        $tag_field = TagField::create(
304
            'Tags',
305
            null,
306
            ContactTag::get(),
307
            $this->Tags()
308
        )->setRightTitle(_t(
309
            "Contacts.TagDescription",
310
            "List of tags related to this contact, seperated by a comma."
311
        ))->setShouldLazyLoad(true);
312
        
313
        if ($this->ID) {
314
            $gridField = GridField::create(
315
                'Notes',
316
                'Notes',
317
                $this->Notes()
318
            );
319
            
320
            $config = GridFieldConfig_RelationEditor::create();
321
322
            $gridField->setConfig($config);
323
324
            $fields->addFieldToTab(
325
                "Root.Notes",
326
                $gridField
327
            );
328
        }
329
        
330
        $fields->addFieldsToTab(
331
            "Root.Main",
332
            [
333
                $member_field = HasOneAutocompleteField::create(
0 ignored issues
show
Unused Code introduced by
The assignment to $member_field is dead and can be removed.
Loading history...
334
                    'MemberID',
335
                    _t(
336
                        'SilverCommerce\ContactAdmin.LinkContactToAccount',
337
                        'Link this contact to a user account?'
338
                    ),
339
                    Member::class,
340
                    'Title'
341
                ),
342
                $tag_field
343
            ]
344
        );
345
346
        return $fields;
347
    }
348
    
349
    public function getCMSValidator()
350
    {
351
        return new RequiredFields(array(
352
            "FirstName",
353
            "Surname"
354
        ));
355
    }
356
    
357
    public function providePermissions()
358
    {
359
        return array(
360
            "CONTACTS_MANAGE" => array(
361
                'name' => _t(
362
                    'Contacts.PERMISSION_MANAGE_CONTACTS_DESCRIPTION',
363
                    'Manage contacts'
364
                ),
365
                'help' => _t(
366
                    'Contacts.PERMISSION_MANAGE_CONTACTS_HELP',
367
                    'Allow creation and editing of contacts'
368
                ),
369
                'category' => _t('Contacts.Contacts', 'Contacts')
370
            ),
371
            "CONTACTS_DELETE" => array(
372
                'name' => _t(
373
                    'Contacts.PERMISSION_DELETE_CONTACTS_DESCRIPTION',
374
                    'Delete contacts'
375
                ),
376
                'help' => _t(
377
                    'Contacts.PERMISSION_DELETE_CONTACTS_HELP',
378
                    'Allow deleting of contacts'
379
                ),
380
                'category' => _t('Contacts.Contacts', 'Contacts')
381
            )
382
        );
383
    }
384
    
385
    public function canView($member = null)
386
    {
387
        $extended = $this->extendedCan(__FUNCTION__, $member);
388
389
        if ($extended !== null) {
390
            return $extended;
391
        }
392
393
        if (!$member) {
394
            $member = Member::currentUser();
0 ignored issues
show
Deprecated Code introduced by
The function SilverStripe\Security\Member::currentUser() has been deprecated: 5.0.0 use Security::getCurrentUser() ( Ignorable by Annotation )

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

394
            $member = /** @scrutinizer ignore-deprecated */ Member::currentUser();

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
395
        }
396
397
        if ($member && Permission::checkMember($member->ID, "CONTACTS_MANAGE")) {
398
            return true;
399
        }
400
401
        return false;
402
    }
403
404
    public function canCreate($member = null, $context = [])
405
    {
406
        $extended = $this->extendedCan(__FUNCTION__, $member, $context);
407
408
        if ($extended !== null) {
409
            return $extended;
410
        }
411
412
        if (!$member) {
413
            $member = Security::getCurrentUser();
414
        }
415
416
        if ($member && Permission::checkMember($member->ID, "CONTACTS_MANAGE")) {
417
            return true;
418
        }
419
420
        return false;
421
    }
422
423
    public function canEdit($member = null)
424
    {
425
        $extended = $this->extendedCan(__FUNCTION__, $member);
426
427
        if ($extended !== null) {
428
            return $extended;
429
        }
430
431
        if (!$member) {
432
            $member = Security::getCurrentUser();
433
        }
434
435
        if ($member && Permission::checkMember($member->ID, "CONTACTS_MANAGE")) {
436
            return true;
437
        }
438
439
        return false;
440
    }
441
442
    public function canDelete($member = null, $context = [])
0 ignored issues
show
Unused Code introduced by
The parameter $context 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

442
    public function canDelete($member = null, /** @scrutinizer ignore-unused */ $context = [])

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...
443
    {
444
        $extended = $this->extendedCan(__FUNCTION__, $member);
445
446
        if ($extended !== null) {
447
            return $extended;
448
        }
449
450
        if (!$member) {
451
            $member = Security::getCurrentUser();
452
        }
453
454
        if ($member && Permission::checkMember($member->ID, "CONTACTS_DELETE")) {
455
            return true;
456
        }
457
458
        return false;
459
    }
460
461
    /**
462
     * Sync to associated member (if needed)
463
     * 
464
     * @return void
465
     */
466
    public function onAfterWrite()
467
    {
468
        parent::onAfterWrite();
469
470
        $this->syncToMember();
471
    }
472
473
    /**
474
     * Cleanup DB on removal
475
     *
476
     */
477
    public function onBeforeDelete()
478
    {
479
        parent::onBeforeDelete();
480
        
481
        // Delete all locations attached to this order
482
        foreach ($this->Locations() as $item) {
483
            $item->delete();
484
        }
485
486
        // Delete all notes attached to this order
487
        foreach ($this->Notes() as $item) {
488
            $item->delete();
489
        }
490
    }
491
}
492