Passed
Push — master ( 853bda...782fe1 )
by Guillaume
06:08
created

Toggl::extractFromData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.1481

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 11
ccs 4
cts 6
cp 0.6667
crap 2.1481
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Godbout\Alfred\Time\Services;
4
5
use Carbon\Carbon;
6
use Carbon\CarbonInterval;
7
use Exception;
8
use MorningTrain\TogglApi\TogglApi;
9
10
class Toggl extends TimerService
11
{
12
    private $client;
13
14
    private $data = null;
15
16
17 112
    public function __construct($apiToken)
18
    {
19 112
        $this->client = new TogglApi($apiToken);
20 112
    }
21
22 24
    public function projects()
23
    {
24 24
        return $this->extractFromData('projects');
25
    }
26
27 24
    public function tags()
28
    {
29 24
        return $this->extractFromData('tags');
30
    }
31
32
    public function pastTimers()
33
    {
34
        try {
35
            $togglTimers = $this->client->getTimeEntriesInRange(Carbon::today(), Carbon::today()->subDays(30));
36
37
            return $this->convertToPastTimers($togglTimers);
38
        } catch (Exception $e) {
39
            return [];
40
        }
41
    }
42
43
    public function startTimer()
44
    {
45
        try {
46
            $timer = $this->client->startTimeEntry([
47
                'description' => getenv('timer_description'),
48
                'pid' => getenv('timer_project_id'),
49
                'tags' => getenv('timer_tag') ? [getenv('timer_tag')] : '',
50
                'created_with' => 'Alfred Time'
51
            ]);
52
53
            if (! isset($timer->id)) {
54
                return false;
55
            }
56
        } catch (Exception $e) {
57
            return false;
58
        }
59
60
        return $timer->id;
61
    }
62
63
    public function stopCurrentTimer()
64
    {
65
        if ($timerId = $this->runningTimer()) {
66
            $response = $this->client->stopTimeEntry($timerId);
67
68
            if (! isset($response->id)) {
69
                throw new Exception("Can't stop current running timer.", 1);
70
            }
71
72
            return true;
73
        }
74
75
        return false;
76
    }
77
78 64
    public function runningTimer()
79
    {
80 64
        $timer = $this->client->getRunningTimeEntry();
81
82 64
        return $timer->id ?? false;
83
    }
84
85
    public function continueTimer($timerId)
86
    {
87
        /**
88
         * Timer attributes are stored in env variables
89
         * gathered in startTimer.
90
         */
91
        return $this->startTimer();
92
    }
93
94
    public function deleteTimer($timerId)
95
    {
96
        try {
97
            $this->client->deleteTimeEntry($timerId);
98
        } catch (Exception $e) {
99
            return false;
100
        }
101
102
        return true;
103
    }
104
105 48
    private function extractFromData($needle)
106
    {
107 48
        $data = $this->getData();
108
109 48
        if (! isset($data->$needle)) {
110 48
            return [];
111
        }
112
113
        $nonDeletedData = $this->filterOutServerwiseDeletedItemsFromData($data->$needle);
114
115
        return array_column($nonDeletedData, 'name', 'id');
116
    }
117
118 48
    private function getData()
119
    {
120 48
        if (is_null($this->data)) {
121 48
            return $this->client->getMe(true);
122
        }
123
124
        return $this->data;
125
    }
126
127
    private function filterOutServerwiseDeletedItemsFromData($items = [])
128
    {
129
        return array_filter($items, function ($item) {
130
            return ! isset($item->server_deleted_at);
131
        });
132
    }
133
134
    protected function convertToPastTimers($togglTimers)
135
    {
136
        $projects = $this->projects();
137
138
        return array_reverse(
139
            array_map(function ($togglTimer) use ($projects) {
140
                return $this->buildPastTimerObject($togglTimer, $projects);
141
            }, $togglTimers)
142
        );
143
    }
144
145
    protected function buildPastTimerObject($togglTimer, $projects)
146
    {
147
        $pastTimer['id'] = $togglTimer->id;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$pastTimer was never initialized. Although not strictly required by PHP, it is generally a good practice to add $pastTimer = array(); before regardless.
Loading history...
148
        $pastTimer['description'] = $togglTimer->description ?? '';
149
        $pastTimer['duration'] = CarbonInterval::seconds($togglTimer->duration)->cascade()->format('%H:%I:%S');
150
151
        if (isset($togglTimer->pid)) {
152
            $pastTimer['project_id'] = $togglTimer->pid;
153
            $pastTimer['project_name'] = $projects[$togglTimer->pid];
154
        }
155
156
        if (isset($togglTimer->tags)) {
157
            $pastTimer['tags'] = implode(', ', (array) $togglTimer->tags);
158
        }
159
160
        return (object) $pastTimer;
161
    }
162
}
163