MySalesforceContactApi::assert_email()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
nc 2
nop 1
dl 0
loc 4
rs 10
c 1
b 0
f 0
1
<?php
2
3
use SForce\SObject;
4
5
/**
6
 * This class adds / updates subscribers to Salesforce
7
 */
8
9
class MySalesforceContactApi extends Object
10
{
11
    /**
12
     * @var boolean
13
     */
14
    protected static $debug = false;
15
16
    protected static $my_singleton_connection = null;
17
18
    /**
19
     * @param string $email
20
     * @param string $phoneNumber - OPTIONAL
21
     * @param string $firstName - OPTIONAL
22
     * @param string $lastName - OPTIONAL
23
     * @param array $extraFields - OPTIONAL
24
     * @param array $extraFilterArray - OPTIONAL
25
     *
26
     * @return bool
27
     */
28
    public static function add_email_subscriber(
29
        $email,
30
        $phoneNumber = null,
31
        $firstName = null,
32
        $lastName = null,
33
        $extraFields = [],
34
        $extraFilterArray = []
35
    ) {
36
        self::assert_email($email);
37
38
        $fields = $extraFields;
39
        $fields['Email'] = $email;
40
        $fields['FirstName'] = '-';
41
        $fields['LastName'] = '-';
42
43
        if ($firstName) {
44
            $fields['FirstName'] = $firstName;
45
        }
46
        if ($lastName) {
47
            $fields['LastName'] = $lastName;
48
        }
49
        if ($phoneNumber) {
50
            $fields['Phone'] = $phoneNumber;
51
        }
52
53
        //doing it!
54
        return self::create_contact($fields, $extraFilterArray);
55
    }
56
57
    /**
58
     * @param string $email
59
     * @param array $extraFields - OPTIONAL
60
     * @param array $extraFilterArray - OPTIONAL
61
     *
62
     * @return bool
63
     */
64
    public static function update_email_subscriber(
65
        $email,
66
        $extraFields = [],
67
        $extraFilterArray = []
68
    ) {
69
        self::assert_email($email);
70
        $fields = $extraFields;
71
        $fields['Email'] = $email;
72
73
        //doing it
74
        return self::update_contact($fields, $extraFilterArray);
75
    }
76
77
    /**
78
     * @param string $email
79
     * @param array $extraFilterArray
80
     *
81
     * @return bool
82
     */
83
    public static function is_email_registered($email, $extraFilterArray = [])
84
    {
85
        $fieldsArray = ['Email' => $email];
86
        $subscriber = self::retrieve_contact($fieldsArray, $extraFilterArray);
87
88
        return $subscriber ? true : false;
89
    }
90
91
    /**
92
     * todo: all nullify thingy
93
     * assumes that all fields are correct (e.g. correct email format)
94
     * can use email or phone as identifier
95
     * @param  array $fieldsArray
96
     * @param  array $extraFilterArray -independent additional filters for retrieving contact
97
     *
98
     * @return bool
99
     */
100
    public static function create_contact($fieldsArray, $extraFilterArray = [])
101
    {
102
        $connection = self::get_my_singleton_connection();
103
        //get defaults
104
        $extraFilterArray = array_merge(
105
            MySalesforceContactConfigApi::get_fields_for_filter(),
106
            $extraFilterArray
107
        );
108
        $fieldsArray = array_merge(
109
            MySalesforceContactConfigApi::get_fields_to_send_on_creation(),
110
            $fieldsArray,
111
            $extraFilterArray
112
        );
113
        $log = SalesforceContactLog::create_contact_log(
114
            'Created',
115
            $fieldsArray,
116
            $extraFilterArray
117
        );
118
119
        $existingContact = self::retrieve_contact($fieldsArray, $extraFilterArray);
120
        // Contact not found. Create a new Contact and set the details
121
        if ($existingContact) {
122
            //we are out of here!
123
            return true;
124
        }
125
        $contact = new SObject();
126
        $contact->setType('Contact');
127
        foreach ($fieldsArray as $fieldName => $fieldValue) {
128
            $contact->{$fieldName} = $fieldValue;
129
        }
130
131
        //doing it!
132
        $error = '';
133
        $response = null;
134
        try {
135
            $response = $connection->create([$contact]);
136
        }
137
        //catch exception
138
        catch (\Exception $e) {
139
            $error = $e->getMessage();
140
        }
141
142
        if (self::$debug) {
143
            $connection->debug($response);
144
        }
145
        return $log->confirmContactLog($response, $error);
146
    }
147
148
    /**
149
     * todo: all nullify thingy
150
     * assumes that all fields are correct (e.g. correct email format)
151
     * can use email or phone as identifier
152
     * @param  array $fieldsArray
153
     * @param  array $extraFilterArray -independent additional filters for retrieving contact
154
     *
155
     * @return bool
156
     */
157
    public static function update_contact($fieldsArray, $extraFilterArray = [])
158
    {
159
        $connection = self::get_my_singleton_connection();
160
161
        //add defaults
162
        $extraFilterArray = array_merge(
163
            MySalesforceContactConfigApi::get_fields_for_filter(),
164
            $extraFilterArray
165
        );
166
        $fieldsArray = array_merge(
167
            MySalesforceContactConfigApi::get_fields_to_send_on_update(),
168
            $fieldsArray,
169
            $extraFilterArray
170
        );
171
        $log = SalesforceContactLog::create_contact_log(
172
            'Updated',
173
            $fieldsArray,
174
            $extraFilterArray
175
        );
176
177
        //find existing contact
178
        $existingContact = self::retrieve_contact($fieldsArray, $extraFilterArray);
179
        // Contact found. Update Contact with details
180
        if ($existingContact) {
181
            $contact = new SObject();
182
            $contact->setType('Contact');
183
            $contact->setId($existingContact->getId());
184
            foreach ($fieldsArray as $fieldName => $fieldValue) {
185
                if ($fieldValue !== $existingContact->{$fieldName}) {
186
                    $contact->{$fieldName} = $fieldValue;
187
                }
188
            }
189
            //doing it!
190
            $error = '';
191
            $response = null;
192
            try {
193
                $response = $connection->update([$contact]);
194
            }
195
            //catch exception
196
            catch (\Exception $e) {
197
                $error = $e->getMessage();
198
            }
199
        } else {
200
            //we are out of here!
201
            return true;
202
        }
203
        if (self::$debug) {
204
            echo $error;
205
            $connection->debug($response);
206
        }
207
        return $log->confirmContactLog($response, $error);
208
    }
209
210
    /**
211
     * Retrive a contact by email address or by phone number
212
     * either the email (preferred) of phone needs to be set in the $fieldsArray
213
     *
214
     * @param array $fieldsArray
215
     * @param array $extraFilterArray additional filter key-value sets
216
     *
217
     * @return SForce\SObject|null
218
     */
219
    public static function retrieve_contact($fieldsArray, $extraFilterArray = [])
220
    {
221
        $connection = self::get_my_singleton_connection();
222
        // Check for existing Contact
223
        $existingContact = null;
224
        $filterArray = [];
225
        $finalFilterArray = [];
226
        $result = null;
227
228
        $extraFilterArray = array_merge(
229
            MySalesforceContactConfigApi::get_fields_for_filter(),
230
            $extraFilterArray
231
        );
232
233
        $email = isset($fieldsArray['Email']) ? trim($fieldsArray['Email']) : null;
234
        if ($email) {
235
            $filterArray['Email'] = $email;
236
        } else {
237
            $phone = isset($fieldsArray['Phone']) ? trim($fieldsArray['Phone']) : null;
238
            if ($phone) {
239
                $filterArray['Phone'] = $phone;
240
            }
241
        }
242
        if (count($filterArray)) {
243
            $finalFilterArray[] = MySalesforcePartnerApi::array2sql($filterArray);
244
            if (count($extraFilterArray)) {
245
                $finalFilterArray[] = MySalesforcePartnerApi::array2sql($extraFilterArray);
246
            }
247
            $where = ' ( ' . implode(' ) AND ( ', $finalFilterArray) . ' ) ';
248
            $query = 'SELECT Id, FirstName, LastName, Phone, Email FROM Contact WHERE ' . $where . ' LIMIT 1';
249
250
            $result = $connection->query($query);
251
            if ($result) {
252
                $contacts = $result->getRecords();
253
                if ($contacts) {
254
                    $existingContact = $contacts[0];
255
                }
256
            }
257
        }
258
        if (self::$debug) {
259
            $connection->debug($result);
260
        }
261
262
        return $existingContact;
263
    }
264
265
    /**
266
     * @return array
267
     */
268
    public static function retrieve_contact_record_types()
269
    {
270
        $connection = self::get_my_singleton_connection();
271
        $returnArray = [];
272
273
        $query = '
274
            SELECT Id, Name, Description, DeveloperName, IsActive, sObjectType
275
            FROM RecordType
276
            WHERE IsActive = true AND sObjectType = \'Contact\'';
277
278
        $result = $connection->query($query);
279
        if ($result) {
280
            $records = $result->getRecords();
281
            if ($records) {
282
                foreach ($records as $record) {
283
                    $object = $record->getFields();
284
                    $object->Id = $record->getId();
285
                    $returnArray[] = $object;
286
                }
287
            }
288
        }
289
        if (self::$debug) {
290
            $connection->debug($result);
291
        }
292
        return $returnArray;
293
    }
294
295
    /**
296
     * @param string $email
297
     */
298
    public static function assert_email($email)
299
    {
300
        if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
301
            throw new InvalidArgumentException('Wrong email address format');
302
        }
303
    }
304
305
    /**
306
     * @param $b
307
     */
308
    public static function set_debug($b = true)
309
    {
310
        self::$debug = $b;
311
    }
312
313
    protected static function get_my_singleton_connection()
314
    {
315
        if (self::$my_singleton_connection === null) {
316
            self::$my_singleton_connection = MySalesforcePartnerApiConnectionOnly::singleton();
317
        }
318
319
        return self::$my_singleton_connection;
320
    }
321
}
322