MixpanelEvent::handle()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 5
eloc 10
c 3
b 0
f 0
nc 5
nop 1
dl 0
loc 17
rs 9.6111
1
<?php namespace GeneaLabs\LaravelMixpanel\Listeners;
2
3
use GeneaLabs\LaravelMixpanel\Events\MixpanelEvent as Event;
4
use Illuminate\Support\Carbon;
5
6
class MixpanelEvent
7
{
8
    public function handle(Event $event)
9
    {
10
        $user = $event->user;
11
12
        if ($user && config("services.mixpanel.enable-default-tracking")) {
13
            $profileData = $this->getProfileData($user);
14
            $profileData = array_merge($profileData, $event->profileData);
15
16
            app('mixpanel')->identify($user->getKey());
17
            app('mixpanel')->people->set($user->getKey(), $profileData, request()->ip());
18
19
            if ($event->charge !== 0) {
20
                app('mixpanel')->people->trackCharge($user->id, $event->charge);
21
            }
22
23
            foreach ($event->trackingData as $eventName => $data) {
24
                app('mixpanel')->track($eventName, $data);
25
            }
26
        }
27
    }
28
29
    private function getProfileData($user) : array
30
    {
31
        $firstName = $user->first_name;
32
        $lastName = $user->last_name;
33
34
        if ($user->name) {
35
            $nameParts = explode(' ', $user->name);
36
            array_filter($nameParts);
37
            $lastName = array_pop($nameParts);
38
            $firstName = implode(' ', $nameParts);
39
        }
40
41
        $data = [
42
            '$first_name' => $firstName,
43
            '$last_name' => $lastName,
44
            '$name' => $user->name,
45
            '$email' => $user->email,
46
            '$created' => ($user->created_at
47
                ? (new Carbon())
48
                    ->parse($user->created_at)
49
                    ->format('Y-m-d\Th:i:s')
50
                : null),
51
        ];
52
        array_filter($data);
53
54
        return $data;
55
    }
56
}
57