Completed
Push — master ( 88d422...a6b19b )
by Gareth
01:56
created

API::withCustomAuthentication()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 3
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 1
rs 10
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 static function withCustomAuthentication($server, $authentication, $options = [])
117
    {
118 1
        return new static(ExchangeWebServices::fromCustomAuthentication(
119 1
            $server,
120
            $authentication,
121
            array_replace_recursive(self::$defaultClientOptions, $options)
122 1
        ));
123
    }
124
125 1
    public function getPrimarySmptEmailAddress()
126
    {
127 1
        if ($this->getPrimarySmtpMailbox() == null) {
128
            return null;
129 1
        }
130
131
        return $this->getPrimarySmtpMailbox()->getEmailAddress();
132
    }
133
134
    public function setPrimarySmtpEmailAddress($emailAddress)
135
    {
136
        $this->getClient()->setPrimarySmtpEmailAddress($emailAddress);
137
138
        return $this;
139 16
    }
140
141 16
    /**
142
     * Create items through the API client
143
     *
144 16
     * @param $items
145
     * @param array $options
146 16
     * @return Type
147 16
     */
148
    public function createItems($items, $options = array())
149 16
    {
150
        $items = Utilities\ensureIsArray($items);
151 16
        $request = array(
152
            'Items' => $items
153
        );
154 4
155
        $request = array_replace_recursive($request, $options);
156
        $request = Type::buildFromArray($request);
157 4
158 4
        $response = $this->getClient()->CreateItem($request);
159
160 4
        return $response;
161
    }
162 4
163
    public function updateItems($items, $options = array())
164 4
    {
165
        $request = array(
166 4
            'ItemChanges' => $items,
167 4
            'MessageDisposition' => 'SaveOnly',
168 4
            'ConflictResolution' => 'AlwaysOverwrite'
169
        );
170
171
        $request = array_replace_recursive($request, $options);
172
173
        $request = Type::buildFromArray($request);
174 1
175
        $response = $this->getClient()->UpdateItem($request);
176 1
        if ($response instanceof UpdateItemResponseMessageType) {
177 1
            return $response->getItems();
178 1
        }
179
180 1
        return Utilities\ensureIsArray($response);
181
    }
182
183 View Code Duplication
    public function createCalendars($names, BaseFolderIdType $parentFolder = null, $options = array())
184
    {
185
        if ($parentFolder === null) {
186
            $parentFolder = $this->getDistinguishedFolderId('calendar');
187
        }
188
189
        return $this->createFolders($names, $parentFolder, $options, 'IPF.Appointment');
190
    }
191
192 4 View Code Duplication
    public function createContactsFolder($names, BaseFolderIdType $parentFolder = null, $options = array())
193
    {
194 4
        if ($parentFolder === null) {
195
            $parentFolder = $this->getDistinguishedFolderId('contacts');
196 4
        }
197 4
198
        return $this->createFolders($names, $parentFolder, $options, 'IPF.Contact');
199
    }
200 4
201 4
    public function createFolders($names, BaseFolderIdType $parentFolder, $options = array(), $folderClass = null)
202
    {
203 4
        $names = Utilities\ensureIsArray($names);
204 4
        $names = array_map(function ($name) use ($folderClass) {
205 4
            return ['DisplayName' => $name, 'FolderClass' => $folderClass];
206
        }, $names);
207 4
208
        $request = [
209 4
            'Folders' => ['Folder' => $names]
210 4
        ];
211
212
        if ($parentFolder !== null) {
213
            $request['ParentFolderId'] = $parentFolder->toArray(true);
214
        }
215
216
        $request = array_merge_recursive($request, $options);
217
218
        $this->client->CreateFolder($request);
219
        return true;
220 3
    }
221
222 3
    /**
223
     * @deprecated Please use API::deleteFolders() instead
224
     *
225 4
     * @param BaseFolderIdType $folderId
226
     * @param array $options
227 4
     * @return Type
228
     */
229
    public function deleteFolder(BaseFolderIdType $folderId, $options = array())
230 4
    {
231
        return $this->deleteFolders($folderId, $options);
232 4
    }
233
234 4
    public function deleteFolders($folders, $options = array())
235 4
    {
236
        $folderIds = Utilities\getFolderIds($folders);
237
238
        $request = [
239
            'DeleteType' => 'HardDelete',
240
            'FolderIds' => $folderIds
241
        ];
242
243
        $request = array_merge_recursive($request, $options);
244
        return $this->client->DeleteFolder($request);
245
    }
246
247
    public function moveItem(Type\ItemIdType $itemId, BaseFolderIdType $folderId, $options = array())
248
    {
249
        $request = array(
250
            'ToFolderId' => $folderId->toArray(true),
251
            'ItemIds' => array('ItemId' => $itemId->toArray())
252
        );
253
254
        $request = array_merge_recursive($request, $options);
255 16
256
        return $this->client->MoveItem($request);
257 16
    }
258
259 16
    /**
260 16
     * @param $items Type\ItemIdType|Type\ItemIdType[]
261
     * @param array $options
262 16
     * @return bool
263 16
     */
264
    public function deleteItems($items, $options = array())
265
    {
266 16
        $items = Utilities\ensureIsArray($items, true);
267
268 16
        $items = array_map(function ($item) {
269
            $item = Type\ItemIdType::buildFromArray($item);
270 16
271 16
            return $item->toArray();
272 16
        }, $items);
273
274
        $request = array(
275 16
            'ItemIds' => array('ItemId' => $items),
276
            'DeleteType' => 'MoveToDeletedItems'
277
        );
278
279
        $request = array_replace_recursive($request, $options);
280
        $request = Type::buildFromArray($request);
281
        $this->getClient()->DeleteItem($request);
282
283 8
        //If the delete fails, an Exception will be thrown in processResponse before it gets here
284
        return true;
285
    }
286
287 8
    /**
288 8
     * @param $identifier
289
     * @param array $options
290 8
     * @return Type\BaseFolderType
291
     */
292 8 View Code Duplication
    public function getFolder($identifier, $options = [])
293
    {
294 8
        $request = array(
295
            'FolderShape' => array(
296 8
                'BaseShape' => array('_' => 'Default')
297
            ),
298 8
            'FolderIds' => $identifier
299
        );
300
301
        $request = array_replace_recursive($request, $options);
302
303
        $request = Type::buildFromArray($request);
304
305
        $response = $this->getClient()->GetFolder($request);
306
307
        return $response;
308 4
    }
309
310 4
    /**
311
     * Get a folder by it's distinguishedId
312 4
     *
313 4
     * @param string $distinguishedId
314 4
     * @param array $options
315 4
     * @return Type\BaseFolderType
316
     */
317
    public function getFolderByDistinguishedId($distinguishedId, $options = [])
318
    {
319
        return $this->getFolder(array(
320
            'DistinguishedFolderId' => array(
321
                'Id' => $distinguishedId,
322
                'Mailbox' => $this->getPrimarySmtpMailbox()
323
            )
324 4
        ), $options);
325
    }
326 4
327
    /**
328
     * @param string|BaseFolderIdType $folderId
329 4
     * @param array $options
330
     * @return Type\BaseFolderType
331
     * @throws API\Exception
332 4
     */
333
    public function getFolderByFolderId($folderId, $options = [])
334
    {
335
        if (is_string($folderId)) {
336
            $folderId = ['FolderId' => ['Id' => $folderId, 'Mailbox' => $this->getPrimarySmtpMailbox()]];
337
        } else {
338
            $folderId = $folderId->toArray(true);
339
        }
340 25
341
        return $this->getFolder($folderId, $options);
342 25
    }
343 17
344 17
    /**
345
     * @param string|BaseFolderIdType $parentFolderId
346
     * @param array $options
347 25
     * @return Type\BaseFolderType[]
348
     */
349 View Code Duplication
    public function getChildrenFolders($parentFolderId = 'root', array $options = array())
350 25
    {
351 25
        if (is_string($parentFolderId)) {
352 25
            $parentFolderId = $this->getDistinguishedFolderId($parentFolderId);
353
        }
354 25
355
        $request = array(
356 25
            'Traversal' => 'Shallow',
357
            'FolderShape' => array(
358
                'BaseShape' => 'AllProperties'
359 25
            ),
360
            'ParentFolderIds' => $parentFolderId->toArray(true)
361
        );
362
363
        $request = array_replace_recursive($request, $options);
364
365
        $request = Type::buildFromArray($request);
366
367
        /** @var \garethp\ews\API\Message\FindFolderResponseMessageType $folders */
368 25
        return $this->getClient()->FindFolder($request);
369
    }
370 25
371
    /**
372 25
     * @param string $folderName
373 25
     * @param string|BaseFolderIdType $parentFolderId
374 24
     * @param array $options
375
     * @return bool|Type\BaseFolderType
376 17
     */
377
    public function getFolderByDisplayName($folderName, $parentFolderId = 'root', $options = array())
378 4
    {
379
        $folders = $this->getChildrenFolders($parentFolderId, $options);
380
381
        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...
382
            if ($folder->getDisplayName() === $folderName) {
383
                return $folder;
384
            }
385
        }
386 5
387
        return false;
388 5
    }
389 4
390 4
    /**
391
     * @param $itemId array|Type\ItemIdType
392
     * @param array $options
393 5
     * @return Type
394 5
     */
395 5 View Code Duplication
    public function getItem($itemId, $options = array())
396
    {
397 5
        if ($itemId instanceof Type\ItemIdType) {
398
            $itemId = $itemId->toArray();
399 5
        }
400
401
        $request = array(
402
            'ItemShape' => array('BaseShape' => 'AllProperties'),
403
            'ItemIds' => array('ItemId' => $itemId)
404
        );
405
406
        $request = array_replace_recursive($request, $options);
407
408
        return $this->getClient()->GetItem($request);
409
    }
410 2
411
    /**
412
     * Get a list of sync changes on a folder
413 2
     *
414 2
     * @param BaseFolderIdType $folderId
415 2
     * @param null $syncState
416
     * @param array $options
417 2
     * @return SyncFolderItemsResponseMessageType
418
     */
419 2
    public function listItemChanges($folderId, $syncState = null, array $options = array())
420 1
    {
421 1
        $request = array(
422 1
            'ItemShape' => array('BaseShape' => 'AllProperties'),
423
            'SyncFolderId' => $folderId->toArray(true),
424 2
            'SyncScope' => 'NormalItems',
425
            'MaxChangesReturned' => '100'
426 2
        );
427 2
428
        if ($syncState != null) {
429 2
            $request['SyncState'] = $syncState;
430
            $request['ItemShape']['BaseShape'] = 'AllProperties';
431
        }
432
433
        $request = array_replace_recursive($request, $options);
434
435
        $request = Type::buildFromArray($request);
436
        $response = $this->getClient()->SyncFolderItems($request);
437
438
        return $response;
439
    }
440
441
    public function getServerTimezones($timezoneIDs = array(), $fullTimezoneData = false)
442
    {
443
        $request = GetServerTimeZonesType::buildFromArray(array(
444
            'returnFullTimeZoneData' => $fullTimezoneData
445
        ));
446
447
        if (!empty($timezoneIDs)) {
448
            $request->setIds($timezoneIDs);
449
        }
450
451
        $timezones = $this->getClient()->GetServerTimeZones($request);
452
        $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...
453
454
        return Utilities\ensureIsArray($timezones);
455
    }
456
457
    /**
458
     * @param Type\ItemIdType $itemId
459
     * @param $fromType
460
     * @param $destinationType
461
     * @param $mailbox
462
     *
463
     * @return Type\ItemIdType
464
     */
465
    public function convertIdFormat(Type\ItemIdType $itemId, $fromType, $destinationType, $mailbox)
466
    {
467
        $result = $this->getClient()->ConvertId(array(
468
            'DestinationFormat' => $destinationType,
469
            'SourceIds' => array(
470
                'AlternateId' => array(
471
                    'Format' => $fromType,
472
                    'Id' => $itemId->getId(),
473
                    'Mailbox' => $mailbox
474
                )
475
            )
476
        ));
477
478
        $itemId->setId($result->getId());
479 2
480
        return $itemId;
481 2
    }
482
483
    /**
484
     * @param Type\FindItemParentType|Type\FindFolderParentType $result
485 2
     *
486 2
     * @return Type\FindItemParentType|Type\FindFolderParentType
487
     */
488 2
    public function getNextPage($result)
489 2
    {
490
        if ($result->isIncludesLastItemInRange()) {
491 2
            return $result;
492 1
        }
493
494
        $currentPage = $result->getCurrentPage();
495 1
        $currentPage->setOffset($result->getIndexedPagingOffset());
496
497
        $lastRequest = $result->getLastRequest();
498
        $lastRequest->setIndexedPage($currentPage);
499
500
        if ($result instanceof Type\FindFolderParentType) {
501
            return $this->getClient()->FindFolder($lastRequest);
502
        }
503
504
        return $this->getClient()->FindItem($lastRequest);
505
    }
506
507
    /**
508
     * @param BaseFolderIdType $folderId
509
     * @param string $deleteType
510
     * @param bool $deleteSubFolders
511
     * @param array $options
512
     * @return EmptyFolderResponseType
513
     */
514
    public function emptyFolder(
515
        BaseFolderIdType $folderId,
516
        $deleteType = 'SoftDelete',
517
        $deleteSubFolders = false,
518
        array $options = []
519
    ) {
520
        $request = [
521
            'DeleteType' => $deleteType,
522 23
            'DeleteSubFolders' => $deleteSubFolders,
523
            'FolderIds' => $folderId->toArray(true)
524 23
        ];
525 23
526 23
        $request = array_merge_recursive($request, $options);
527 23
528 23
        return $this->getClient()->EmptyFolder($request);
529
    }
530
531
    protected function getDistinguishedFolderId($id = null, $changeKey = null)
532
    {
533
        return new Type\DistinguishedFolderIdType(
534
            $id,
535
            $changeKey,
536
            $this->getPrimarySmtpMailbox()
537
        );
538
    }
539
}
540