Event::get()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 31
rs 9.424
c 0
b 0
f 0
cc 3
nc 2
nop 4
1
<?php
2
3
namespace Spatie\GoogleCalendar;
4
5
use Carbon\Carbon;
6
use Carbon\CarbonInterface;
7
use DateTime;
8
use Google_Service_Calendar_Event;
9
use Google_Service_Calendar_EventDateTime;
10
use Google_Service_Calendar_EventSource;
11
use Illuminate\Support\Arr;
12
use Illuminate\Support\Collection;
13
use Illuminate\Support\Str;
14
15
class Event
16
{
17
    /** @var \Google_Service_Calendar_Event */
18
    public $googleEvent;
19
20
    /** @var string */
21
    protected $calendarId;
22
23
    /** @var array */
24
    protected $attendees;
25
26
    public function __construct()
27
    {
28
        $this->attendees = [];
29
        $this->googleEvent = new Google_Service_Calendar_Event;
30
    }
31
32
    /**
33
     * @param \Google_Service_Calendar_Event $googleEvent
34
     * @param $calendarId
35
     *
36
     * @return static
37
     */
38
    public static function createFromGoogleCalendarEvent(Google_Service_Calendar_Event $googleEvent, $calendarId)
39
    {
40
        $event = new static;
41
42
        $event->googleEvent = $googleEvent;
43
        $event->calendarId = $calendarId;
44
45
        return $event;
46
    }
47
48
    /**
49
     * @param array $properties
50
     * @param string|null $calendarId
51
     *
52
     * @return mixed
53
     */
54
    public static function create(array $properties, string $calendarId = null, $optParams = [])
55
    {
56
        $event = new static;
57
58
        $event->calendarId = static::getGoogleCalendar($calendarId)->getCalendarId();
59
60
        foreach ($properties as $name => $value) {
61
            $event->$name = $value;
62
        }
63
64
        return $event->save('insertEvent', $optParams);
65
    }
66
67
    public static function quickCreate(string $text)
68
    {
69
        $event = new static;
70
71
        $event->calendarId = static::getGoogleCalendar()->getCalendarId();
72
73
        return $event->quickSave($text);
74
    }
75
76
    public static function get(CarbonInterface $startDateTime = null, CarbonInterface $endDateTime = null, array $queryParameters = [], string $calendarId = null): Collection
77
    {
78
        $googleCalendar = static::getGoogleCalendar($calendarId);
79
80
        $googleEvents = $googleCalendar->listEvents($startDateTime, $endDateTime, $queryParameters);
81
82
        $googleEventsList = $googleEvents->getItems();
83
84
        while ($googleEvents->getNextPageToken()) {
85
            $queryParameters['pageToken'] = $googleEvents->getNextPageToken();
86
87
            $googleEvents = $googleCalendar->listEvents($startDateTime, $endDateTime, $queryParameters);
88
89
            $googleEventsList = array_merge($googleEventsList, $googleEvents->getItems());
90
        }
91
92
        $useUserOrder = isset($queryParameters['orderBy']);
93
94
        return collect($googleEventsList)
95
            ->map(function (Google_Service_Calendar_Event $event) use ($calendarId) {
96
                return static::createFromGoogleCalendarEvent($event, $calendarId);
97
            })
98
            ->sortBy(function (self $event, $index) use ($useUserOrder) {
99
                if ($useUserOrder) {
100
                    return $index;
101
                }
102
103
                return $event->sortDate;
104
            })
105
            ->values();
106
    }
107
108
    public static function find($eventId, string $calendarId = null): self
109
    {
110
        $googleCalendar = static::getGoogleCalendar($calendarId);
111
112
        $googleEvent = $googleCalendar->getEvent($eventId);
113
114
        return static::createFromGoogleCalendarEvent($googleEvent, $calendarId);
115
    }
116
117
    public function __get($name)
118
    {
119
        $name = $this->getFieldName($name);
120
121
        if ($name === 'sortDate') {
122
            return $this->getSortDate();
123
        }
124
125
        if ($name === 'source') {
126
            return [
127
                'title' => $this->googleEvent->getSource()->title,
128
                'url' => $this->googleEvent->getSource()->url,
129
            ];
130
        }
131
132
        $value = Arr::get($this->googleEvent, $name);
133
134
        if (in_array($name, ['start.date', 'end.date']) && $value) {
135
            $value = Carbon::createFromFormat('Y-m-d', $value)->startOfDay();
136
        }
137
138
        if (in_array($name, ['start.dateTime', 'end.dateTime']) && $value) {
139
            $value = Carbon::createFromFormat(DateTime::RFC3339, $value);
140
        }
141
142
        return $value;
143
    }
144
145
    public function __set($name, $value)
146
    {
147
        $name = $this->getFieldName($name);
148
149
        if (in_array($name, ['start.date', 'end.date', 'start.dateTime', 'end.dateTime'])) {
150
            $this->setDateProperty($name, $value);
151
152
            return;
153
        }
154
155
        if ($name == 'source') {
156
            $this->setSourceProperty($value);
157
158
            return;
159
        }
160
161
        Arr::set($this->googleEvent, $name, $value);
0 ignored issues
show
Documentation introduced by
$this->googleEvent is of type object<Google_Service_Calendar_Event>, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
162
    }
163
164
    public function exists(): bool
165
    {
166
        return $this->id != '';
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Spatie\GoogleCalendar\Event>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
167
    }
168
169
    public function isAllDayEvent(): bool
170
    {
171
        return is_null($this->googleEvent['start']['dateTime']);
172
    }
173
174
    public function save(string $method = null, $optParams = []): self
175
    {
176
        $method = $method ?? ($this->exists() ? 'updateEvent' : 'insertEvent');
177
178
        $googleCalendar = $this->getGoogleCalendar($this->calendarId);
179
180
        $this->googleEvent->setAttendees($this->attendees);
181
182
        $googleEvent = $googleCalendar->$method($this, $optParams);
183
184
        return static::createFromGoogleCalendarEvent($googleEvent, $googleCalendar->getCalendarId());
185
    }
186
187
    public function quickSave(string $text): self
188
    {
189
        $googleCalendar = $this->getGoogleCalendar($this->calendarId);
190
191
        $googleEvent = $googleCalendar->insertEventFromText($text);
192
193
        return static::createFromGoogleCalendarEvent($googleEvent, $googleCalendar->getCalendarId());
194
    }
195
196
    public function update(array $attributes, $optParams = []): self
197
    {
198
        foreach ($attributes as $name => $value) {
199
            $this->$name = $value;
200
        }
201
202
        return $this->save('updateEvent', $optParams);
203
    }
204
205
    public function delete(string $eventId = null)
206
    {
207
        $this->getGoogleCalendar($this->calendarId)->deleteEvent($eventId ?? $this->id);
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<Spatie\GoogleCalendar\Event>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
208
    }
209
210
    public function addAttendee(array $attendees)
211
    {
212
        $this->attendees[] = $attendees;
213
    }
214
215
    public function getSortDate(): string
216
    {
217
        if ($this->startDate) {
0 ignored issues
show
Documentation introduced by
The property startDate does not exist on object<Spatie\GoogleCalendar\Event>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
218
            return $this->startDate;
0 ignored issues
show
Documentation introduced by
The property startDate does not exist on object<Spatie\GoogleCalendar\Event>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
219
        }
220
221
        if ($this->startDateTime) {
0 ignored issues
show
Documentation introduced by
The property startDateTime does not exist on object<Spatie\GoogleCalendar\Event>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
222
            return $this->startDateTime;
0 ignored issues
show
Documentation introduced by
The property startDateTime does not exist on object<Spatie\GoogleCalendar\Event>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
223
        }
224
225
        return '';
226
    }
227
228
    public function getCalendarId(): string
229
    {
230
        return $this->calendarId;
231
    }
232
233
    protected static function getGoogleCalendar(string $calendarId = null): GoogleCalendar
234
    {
235
        $calendarId = $calendarId ?? config('google-calendar.calendar_id');
236
237
        return GoogleCalendarFactory::createForCalendarId($calendarId);
238
    }
239
240
    protected function setDateProperty(string $name, CarbonInterface $date)
241
    {
242
        $eventDateTime = new Google_Service_Calendar_EventDateTime;
243
244
        if (in_array($name, ['start.date', 'end.date'])) {
245
            $eventDateTime->setDate($date->format('Y-m-d'));
246
            $eventDateTime->setTimezone($date->getTimezone());
247
        }
248
249
        if (in_array($name, ['start.dateTime', 'end.dateTime'])) {
250
            $eventDateTime->setDateTime($date->format(DateTime::RFC3339));
251
            $eventDateTime->setTimezone($date->getTimezone());
252
        }
253
254
        if (Str::startsWith($name, 'start')) {
255
            $this->googleEvent->setStart($eventDateTime);
256
        }
257
258
        if (Str::startsWith($name, 'end')) {
259
            $this->googleEvent->setEnd($eventDateTime);
260
        }
261
    }
262
263
    protected function setSourceProperty(array $value)
264
    {
265
        $source = new Google_Service_Calendar_EventSource([
266
            'title' => $value['title'],
267
            'url' => $value['url'],
268
        ]);
269
270
        $this->googleEvent->setSource($source);
271
    }
272
273
    protected function getFieldName(string $name): string
274
    {
275
        return [
276
            'name' => 'summary',
277
            'description' => 'description',
278
            'startDate' => 'start.date',
279
            'endDate' => 'end.date',
280
            'startDateTime' => 'start.dateTime',
281
            'endDateTime' => 'end.dateTime',
282
        ][$name] ?? $name;
283
    }
284
}
285