Completed
Push — master ( 9a8ecb...d328d0 )
by Gareth
02:37
created

API::createCalendars()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 8
Ratio 100 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 3
dl 8
loc 8
ccs 5
cts 5
cp 1
crap 2
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace garethp\ews;
4
5
use garethp\ews\API\ExchangeWebServices;
6
use garethp\ews\API\Message\EmptyFolderResponseType;
7
use garethp\ews\API\Message\GetServerTimeZonesType;
8
use garethp\ews\API\Message\SyncFolderItemsResponseMessageType;
9
use garethp\ews\API\Message\UpdateItemResponseMessageType;
10
use garethp\ews\API\Type;
11
use garethp\ews\API\Type\BaseFolderIdType;
12
13
/**
14
 * A base class for APIs
15
 *
16
 * Class BaseAPI
17
 * @package garethp\ews
18
 */
19
class API
20
{
21
    protected static $defaultClientOptions = array(
22
        'version' => ExchangeWebServices::VERSION_2010
23
    );
24
25 35
    public function __construct(ExchangeWebServices $client = null)
26
    {
27 35
        if ($client) {
28 35
            $this->setClient($client);
29 35
        }
30 35
    }
31
32
    /**
33
     * @return Type\EmailAddressType
34
     */
35 27
    public function getPrimarySmtpMailbox()
36
    {
37 27
        return $this->getClient()->getPrimarySmtpMailbox();
38
    }
39
40
    /**
41
     * Storing the API client
42
     * @var ExchangeWebServices
43
     */
44
    private $client;
45
46
    /**
47
     * Get a calendar item
48
     *
49
     * @param string $name
50
     * @return CalendarAPI
51
     */
52 6
    public function getCalendar($name = null)
53
    {
54 6
        $calendar = new CalendarAPI();
55 6
        $calendar->setClient($this->getClient());
56 6
        $calendar->pickCalendar($name);
57
58 6
        return $calendar;
59
    }
60
61
    /**
62
     * @param string $folderName
63
     * @return MailAPI
64
     */
65 7
    public function getMailbox($folderName = null)
66
    {
67 7
        $mailApi = new MailAPI();
68 7
        $mailApi->setClient($this->getClient());
69 7
        $mailApi->pickMailFolder($folderName);
70
71 7
        return $mailApi;
72
    }
73
74
    /**
75
     * Set the API client
76
     *
77
     * @param ExchangeWebServices $client
78
     * @return $this
79
     */
80 35
    public function setClient($client)
81
    {
82 35
        $this->client = $client;
83
84 35
        return $this;
85
    }
86
87
    /**
88
     * Get the API client
89
     *
90
     * @return ExchangeWebServices
91
     */
92 34
    public function getClient()
93
    {
94 34
        return $this->client;
95
    }
96
97 34
    public static function withUsernameAndPassword($server, $username, $password, $options = [])
98
    {
99 34
        return new static(ExchangeWebServices::fromUsernameAndPassword(
100 34
            $server,
101 34
            $username,
102 34
            $password,
103 34
            array_replace_recursive(self::$defaultClientOptions, $options)
104 34
        ));
105
    }
106
107 1
    public static function withCallbackToken($server, $token, $options = [])
108
    {
109 1
        return new static(ExchangeWebServices::fromCallbackToken(
110 1
            $server,
111 1
            $token,
112 1
            array_replace_recursive(self::$defaultClientOptions, $options)
113 1
        ));
114
    }
115
116 1
    public function getPrimarySmptEmailAddress()
117
    {
118 1
        if ($this->getPrimarySmtpMailbox() == null) {
119 1
            return null;
120
        }
121
122 1
        return $this->getPrimarySmtpMailbox()->getEmailAddress();
123
    }
124
125 1
    public function setPrimarySmtpEmailAddress($emailAddress)
126
    {
127 1
        $this->getClient()->setPrimarySmtpEmailAddress($emailAddress);
128
129 1
        return $this;
130
    }
131
132
    /**
133
     * Create items through the API client
134
     *
135
     * @param $items
136
     * @param array $options
137
     * @return Type
138
     */
139 16
    public function createItems($items, $options = array())
140
    {
141 16
        $items = Utilities\ensureIsArray($items);
142
        $request = array(
143
            'Items' => $items
144 16
        );
145
146 16
        $request = array_replace_recursive($request, $options);
147 16
        $request = Type::buildFromArray($request);
148
149 16
        $response = $this->getClient()->CreateItem($request);
150
151 16
        return $response;
152
    }
153
154 4
    public function updateItems($items, $options = array())
155
    {
156
        $request = array(
157 4
            'ItemChanges' => $items,
158 4
            'MessageDisposition' => 'SaveOnly',
159
            'ConflictResolution' => 'AlwaysOverwrite'
160 4
        );
161
162 4
        $request = array_replace_recursive($request, $options);
163
164 4
        $request = Type::buildFromArray($request);
165
166 4
        $response = $this->getClient()->UpdateItem($request);
167 4
        if ($response instanceof UpdateItemResponseMessageType) {
168 4
            return $response->getItems();
169
        }
170
171
        return Utilities\ensureIsArray($response);
172
    }
173
174 1 View Code Duplication
    public function createCalendars($names, BaseFolderIdType $parentFolder = null, $options = array())
175
    {
176 1
        if ($parentFolder === null) {
177 1
            $parentFolder = $this->getDistinguishedFolderId('calendar');
178 1
        }
179
180 1
        return $this->createFolders($names, $parentFolder, $options, 'IPF.Appointment');
181
    }
182
    
183 View Code Duplication
    public function createContactsFolder($names, BaseFolderIdType $parentFolder = null, $options = array())
184
    {
185
        if ($parentFolder === null) {
186
            $parentFolder = $this->getDistinguishedFolderId('contacts');
187
        }
188
189
        return $this->createFolders($names, $parentFolder, $options, 'IPF.Contact');
190
    }
191
192 4
    public function createFolders($names, BaseFolderIdType $parentFolder, $options = array(), $folderClass = null)
193
    {
194 4
        $names = Utilities\ensureIsArray($names);
195
        $names = array_map(function ($name) use ($folderClass) {
196 4
            return ['DisplayName' => $name, 'FolderClass' => $folderClass];
197 4
        }, $names);
198
199
        $request = [
200 4
            'Folders' => ['Folder' => $names]
201 4
        ];
202
203 4
        if ($parentFolder !== null) {
204 4
            $request['ParentFolderId'] = $parentFolder->toArray(true);
205 4
        }
206
207 4
        $request = array_merge_recursive($request, $options);
208
209 4
        $this->client->CreateFolder($request);
210 4
        return true;
211
    }
212
213
    /**
214
     * @deprecated Please use API::deleteFolders() instead
215
     *
216
     * @param BaseFolderIdType $folderId
217
     * @param array $options
218
     * @return Type
219
     */
220 3
    public function deleteFolder(BaseFolderIdType $folderId, $options = array())
221
    {
222 3
        return $this->deleteFolders($folderId, $options);
223
    }
224
225 4
    public function deleteFolders($folders, $options = array())
226
    {
227 4
        $folderIds = Utilities\getFolderIds($folders);
228
229
        $request = [
230 4
            'DeleteType' => 'HardDelete',
231
            'FolderIds' => $folderIds
232 4
        ];
233
234 4
        $request = array_merge_recursive($request, $options);
235 4
        return $this->client->DeleteFolder($request);
236
    }
237
238
    public function moveItem(Type\ItemIdType $itemId, BaseFolderIdType $folderId, $options = array())
239
    {
240
        $request = array(
241
            'ToFolderId' => $folderId->toArray(true),
242
            'ItemIds' => array('ItemId' => $itemId->toArray())
243
        );
244
245
        $request = array_merge_recursive($request, $options);
246
247
        return $this->client->MoveItem($request);
248
    }
249
250
    /**
251
     * @param $items Type\ItemIdType|Type\ItemIdType[]
252
     * @param array $options
253
     * @return bool
254
     */
255 16
    public function deleteItems($items, $options = array())
256
    {
257 16
        $items = Utilities\ensureIsArray($items, true);
258
259 16
        $items = array_map(function ($item) {
260 16
            $item = Type\ItemIdType::buildFromArray($item);
261
262 16
            return $item->toArray();
263 16
        }, $items);
264
265
        $request = array(
266 16
            'ItemIds' => array('ItemId' => $items),
267
            'DeleteType' => 'MoveToDeletedItems'
268 16
        );
269
270 16
        $request = array_replace_recursive($request, $options);
271 16
        $request = Type::buildFromArray($request);
272 16
        $this->getClient()->DeleteItem($request);
273
274
        //If the delete fails, an Exception will be thrown in processResponse before it gets here
275 16
        return true;
276
    }
277
278
    /**
279
     * @param $identifier
280
     * @return Type\BaseFolderType
281
     */
282 8
    public function getFolder($identifier)
283
    {
284
        $request = array(
285
            'FolderShape' => array(
286 8
                'BaseShape' => array('_' => 'Default')
287 8
            ),
288
            'FolderIds' => $identifier
289 8
        );
290 8
        $request = Type::buildFromArray($request);
291
292 8
        $response = $this->getClient()->GetFolder($request);
293
294 8
        return $response;
295
    }
296
297
    /**
298
     * Get a folder by it's distinguishedId
299
     *
300
     * @param string $distinguishedId
301
     * @return Type\BaseFolderType
302
     */
303 4
    public function getFolderByDistinguishedId($distinguishedId)
304
    {
305 4
        return $this->getFolder(array(
306
            'DistinguishedFolderId' => array(
307 4
                'Id' => $distinguishedId,
308 4
                'Mailbox' => $this->getPrimarySmtpMailbox()
309 4
            )
310 4
        ));
311
    }
312
313
    /**
314
     * @param string|BaseFolderIdType $folderId
315
     * @return Type\BaseFolderType
316
     */
317 4
    public function getFolderByFolderId($folderId)
318
    {
319 4
        if (is_string($folderId)) {
320
            $folderId = ['FolderId' => ['Id' => $folderId, 'Mailbox' => $this->getPrimarySmtpMailbox()]];
321
        } else {
322 4
            $folderId = $folderId->toArray(true);
323
        }
324
325 4
        return $this->getFolder($folderId);
326
    }
327
328
    /**
329
     * @param string|BaseFolderIdType $parentFolderId
330
     * @param array $options
331
     * @return Type\BaseFolderType[]
332
     */
333 25 View Code Duplication
    public function getChildrenFolders($parentFolderId = 'root', array $options = array())
334
    {
335 25
        if (is_string($parentFolderId)) {
336 17
            $parentFolderId = $this->getDistinguishedFolderId($parentFolderId);
337 17
        }
338
339
        $request = array(
340 25
            'Traversal' => 'Shallow',
341
            'FolderShape' => array(
342
                'BaseShape' => 'AllProperties'
343 25
            ),
344 25
            'ParentFolderIds' => $parentFolderId->toArray(true)
345 25
        );
346
347 25
        $request = array_replace_recursive($request, $options);
348
349 25
        $request = Type::buildFromArray($request);
350
351
        /** @var \garethp\ews\API\Message\FindFolderResponseMessageType $folders */
352 25
        return $this->getClient()->FindFolder($request);
353
    }
354
355
    /**
356
     * @param string $folderName
357
     * @param string|BaseFolderIdType $parentFolderId
358
     * @param array $options
359
     * @return bool|Type\BaseFolderType
360
     */
361 25
    public function getFolderByDisplayName($folderName, $parentFolderId = 'root', $options = array())
362
    {
363 25
        $folders = $this->getChildrenFolders($parentFolderId, $options);
364
365 25
        foreach ($folders as $folder) {
0 ignored issues
show
Bug introduced by
The expression $folders of type object<garethp\ews\API\Type> is not traversable.
Loading history...
366 25
            if ($folder->getDisplayName() === $folderName) {
367 24
                return $folder;
368
            }
369 17
        }
370
371 4
        return false;
372
    }
373
374
    /**
375
     * @param $itemId array|Type\ItemIdType
376
     * @param array $options
377
     * @return Type
378
     */
379 5
    public function getItem($itemId, $options = array())
380
    {
381 5
        if ($itemId instanceof Type\ItemIdType) {
382 4
            $itemId = $itemId->toArray();
383 4
        }
384
385
        $request = array(
386 5
            'ItemShape' => array('BaseShape' => 'AllProperties'),
387 5
            'ItemIds' => array('ItemId' => $itemId)
388 5
        );
389
390 5
        $request = array_replace_recursive($request, $options);
391
392 5
        return $this->getClient()->GetItem($request);
393
    }
394
395
    /**
396
     * Get a list of sync changes on a folder
397
     *
398
     * @param BaseFolderIdType $folderId
399
     * @param null $syncState
400
     * @param array $options
401
     * @return SyncFolderItemsResponseMessageType
402
     */
403 2
    public function listItemChanges($folderId, $syncState = null, array $options = array())
404
    {
405
        $request = array(
406 2
            'ItemShape' => array('BaseShape' => 'AllProperties'),
407 2
            'SyncFolderId' => $folderId->toArray(true),
408 2
            'SyncScope' => 'NormalItems',
409
            'MaxChangesReturned' => '100'
410 2
        );
411
412 2
        if ($syncState != null) {
413 1
            $request['SyncState'] = $syncState;
414 1
            $request['ItemShape']['BaseShape'] = 'AllProperties';
415 1
        }
416
417 2
        $request = array_replace_recursive($request, $options);
418
419 2
        $request = Type::buildFromArray($request);
420 2
        $response = $this->getClient()->SyncFolderItems($request);
421
422 2
        return $response;
423
    }
424
425
    public function getServerTimezones($timezoneIDs = array(), $fullTimezoneData = false)
426
    {
427
        $request = GetServerTimeZonesType::buildFromArray(array(
428
            'returnFullTimeZoneData' => $fullTimezoneData
429
        ));
430
431
        if (!empty($timezoneIDs)) {
432
            $request->setIds($timezoneIDs);
433
        }
434
435
        $timezones = $this->getClient()->GetServerTimeZones($request);
436
        $timezones = $timezones->TimeZoneDefinition;
0 ignored issues
show
Documentation introduced by
The property TimeZoneDefinition does not exist on object<garethp\ews\API\Type>. Since you implemented __set, maybe consider adding a @property annotation.

Since your code implements the magic setter _set, this function will be called for any write 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.");
        }
    }

}

Since the property has write access only, you can use the @property-write 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...
437
438
        return Utilities\ensureIsArray($timezones);
439
    }
440
441
    /**
442
     * @param Type\ItemIdType $itemId
443
     * @param $fromType
444
     * @param $destinationType
445
     * @param $mailbox
446
     *
447
     * @return Type\ItemIdType
448
     */
449
    public function convertIdFormat(Type\ItemIdType $itemId, $fromType, $destinationType, $mailbox)
450
    {
451
        $result = $this->getClient()->ConvertId(array(
452
            'DestinationFormat' => $destinationType,
453
            'SourceIds' => array(
454
                'AlternateId' => array(
455
                    'Format' => $fromType,
456
                    'Id' => $itemId->getId(),
457
                    'Mailbox' => $mailbox
458
                )
459
            )
460
        ));
461
462
        $itemId->setId($result->getId());
463
464
        return $itemId;
465
    }
466
467
    /**
468
     * @param Type\FindItemParentType|Type\FindFolderParentType $result
469
     *
470
     * @return Type\FindItemParentType|Type\FindFolderParentType
471
     */
472 2
    public function getNextPage($result)
473
    {
474 2
        if ($result->isIncludesLastItemInRange()) {
475
            return $result;
476
        }
477
478 2
        $currentPage = $result->getCurrentPage();
479 2
        $currentPage->setOffset($result->getIndexedPagingOffset());
480
481 2
        $lastRequest = $result->getLastRequest();
482 2
        $lastRequest->setIndexedPage($currentPage);
483
484 2
        if ($result instanceof Type\FindFolderParentType) {
485 1
            return $this->getClient()->FindFolder($lastRequest);
486
        }
487
488 1
        return $this->getClient()->FindItem($lastRequest);
489
    }
490
491
    /**
492
     * @param BaseFolderIdType $folderId
493
     * @param string $deleteType
494
     * @param bool $deleteSubFolders
495
     * @param array $options
496
     * @return EmptyFolderResponseType
497
     */
498
    public function emptyFolder(
499
        BaseFolderIdType $folderId,
500
        $deleteType = 'SoftDelete',
501
        $deleteSubFolders = false,
502
        array $options = []
503
    ) {
504
        $request = [
505
            'DeleteType' => $deleteType,
506
            'DeleteSubFolders' => $deleteSubFolders,
507
            'FolderIds' => $folderId->toArray(true)
508
        ];
509
510
        $request = array_merge_recursive($request, $options);
511
512
        return $this->getClient()->EmptyFolder($request);
513
    }
514
515 23
    protected function getDistinguishedFolderId($id = null, $changeKey = null)
516
    {
517 23
        return new Type\DistinguishedFolderIdType(
518 23
            $id,
519 23
            $changeKey,
520 23
            $this->getPrimarySmtpMailbox()
521 23
        );
522
    }
523
}
524